var carousel_items = [];
var center_id = 0;
var max_id = 0;

/**
 * Call back after new item is visible
 **/
function visibleInCallback(carousel, li, index, state){
  var dx = li.firstChild.id;
  
  if(index > max_id){		//animating next
    if(dx == 1){
      center_id = carousel_items.length;
    }else{
      center_id = dx - 1;
    }
  }else{			//animating prev
    if(dx == carousel_items.length){
      center_id = 1;
    }else{
      center_id = dx;
      center_id++;
    }
  }
  max_id = index;
  updateCenterInfo(center_id);
  alphaAll();
}

function alphaAll(){
    var carousel = jQuery('#mycarousel');
    if(carousel){
        var allImages = carousel.find('li a img').addClass();
        var centerImage = carousel.find('li a#'+center_id+' img').css('border-color', 'blue');
        allImages.removeClass('slider-thumb-noalpha').addClass('slider-thumb-alpha');
        centerImage.addClass('slider-thumb-noalpha');
    }
}

/**
 * Updates the center content
 *
 * @xid : id of data that needs to be displayed
 **/
function updateCenterInfo(xid){
  if(xid - 1 >= 0){
    $("#slider-title").html(carousel_items[xid - 1].caption);
    $("#slider-desc").html(carousel_items[xid - 1].desc);
  }
}

jQuery(document).ready(function() { 
    $.ajax({
	type: "GET",
	url: "featuredcompaniesxml.aspx",
	dataType: "xml",
	success: function(xml) {
	  var id = 0;
	    $(xml).find('photo').each(function(){
		id++;
		var thumb = $(this).find('thumb').attr('src');
                var caption = $(this).find('caption').attr('text');
                var desc = $(this).find('desc').text();
                var url = $(this).find('url').attr('link');

                carousel_items.push({id:id, thumb:thumb, caption:caption, desc:desc, url:url});
		jQuery('#mycarousel').append('<li><a id="' + id + '"href="javascript:itemClicked(' + id + ');"><img src="' + thumb + '" width="100" height="100" alt="' + caption + '" border="0" /></a></li>');
	    });
            
             jQuery('#mycarousel').jcarousel({
                scroll: 1,
		wrap: 'circular',
                itemVisibleInCallback: {onAfterAnimation: visibleInCallback}
            });
             
        },
        error: function(jqXHR, textStatus, errorThrown){

        }
    });

});

/**
 * Called when thumbnail is clicked
 *
 * @id : id of item clicked
 **/
function itemClicked(id){
  var carousel = jQuery('#mycarousel').data('jcarousel');
  if(id == center_id){  			//launch url
    window.open(carousel_items[id - 1].url);
  }else{
      if(id > center_id && center_id != 1){
	carousel.next();
      }else if((id < center_id && center_id != carousel_items.length) || id == carousel_items.length){					//animate to center
	carousel.prev();
      }else if(id > center_id && center_id == 1){
	carousel.next();
      }
      else if(id < center_id && center_id == carousel_items.length && id != 1){					//animate to center
	carousel.prev();
      }else{
	carousel.next();
      }
  }
}
