/**
 * photo viwer carousel lib
 * @author sash 
 * @version $Id: photo_carousel.js 4005 2010-03-05 23:29:52Z vivek $
 */

var photo_carousel_current_index = null;
var photo_carousel_clk_state = 0;
var refresh_count = 0;
/**
 * callback function
 * custom controls for Photo Carousel
 */
 
 
function photocarousel_initCallback(carousel) {
  try{
    jQuery('#photo-carousel-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#photo-carousel-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
    
    //bind external controls
    jQuery('#photo-carousel-prev-external').bind('click', function() {
        if(photo_carousel_current_index<carousel.first-1 || photo_carousel_current_index>carousel.last-1){
          //rewind carousel if selected item gets out of focus
          var rewind_index = photo_carousel_scroll*Math.floor((photo_carousel_current_index)/photo_carousel_scroll)+1;
          carousel.scroll(rewind_index);
        }
        updateOmnitureTracker(photoCarouselItems[photo_carousel_current_index]);
		updateURL(photoCarouselItems[photo_carousel_current_index]);
       // updatePrintPhoto(photoCarouselItems[photo_carousel_current_index]);
        togglePopupIcon(photoCarouselItems[photo_carousel_current_index]);
        reloadDartFrameAds();
        return false;
    });
    jQuery('#photo-carousel-next-external').bind('click', function() {
        if(photo_carousel_current_index<carousel.first-1 || photo_carousel_current_index>carousel.last-1){
          //rewind carousel if selected item gets out of focus
          var rewind_index = photo_carousel_scroll*Math.floor((photo_carousel_current_index)/photo_carousel_scroll)+1;
          carousel.scroll(rewind_index);
        }
        updateOmnitureTracker(photoCarouselItems[photo_carousel_current_index]);
		updateURL(photoCarouselItems[photo_carousel_current_index]);
        //updatePrintPhoto(photoCarouselItems[photo_carousel_current_index]);
        togglePopupIcon(photoCarouselItems[photo_carousel_current_index]);
        reloadDartFrameAds();
        return false;
    });
    
    $('div#photo-carousel-clip').css('visibility','visible');
  }
  catch(e){
  }
}

/** 
 * enables/disables paging arrows 
 */

function photocarousel_buttonNextCallback(carousel,el,active){
  if(active){
    toggleNavigationIcons(true,'photo-carousel-next','right');
    $('div#photo-carousel-next').css({'cursor': 'pointer'});
  }
  else{
    toggleNavigationIcons(false,'photo-carousel-next','right');
    $('div#photo-carousel-next').css({'cursor': 'default'});
  }
  
}

/** 
 * enables/disables paging arrows 
 */
 
function photocarousel_buttonPrevCallback(carousel,el,active){
  if(active){
    toggleNavigationIcons(true,'photo-carousel-prev','left');
    $('div#photo-carousel-prev').css({'cursor': 'pointer'});
  }
  else{
    toggleNavigationIcons(false,'photo-carousel-prev','left');
    $('div#photo-carousel-prev').css({'cursor': 'default'});
  }
}

/**
 * callback function to load main photo
 */
 
function photocarousel_loadMainPhoto(){
      var arr = $(this).attr('id').split('_');
		  if(!arr || !arr.length || arr.length!=2){
			 return;
		  }
		  var listItems = $("div#photo-carousel-clip ul li div.photo-carousel-item-wrapper");
		  //find & update big image
		  jQuery.each(photoCarouselItems,function(i, item){
        if(i == arr[1]){
          //don't load same photo second time
          //@todo
          /*
          if(photo_carousel_content_id == item.content_id){
            return false;
          }
          */
          //set selection on li item
          $(listItems[i]).css('border','2px solid #B30202');
          var height = item.p_h + 'px';
          $('div#photo-carousel-fullphoto').css('height',height).hide();
		  var ind = item.po.lastIndexOf(".");
	  	  var photo_src = "http://www.jimrome.com/cimages/"+item.po.substring(0,ind)+"_photo_medium."+item.po.substring(ind+1,item.po.length);
          $('div#photo-carousel-fullphoto').html("<img src=\""+photo_src+"\" height=\""+item.p_h+"\" width=\""+item.p_w+"\" border=\"0\" />").fadeIn('normal');
		  refresh_count = refresh_count +1;
          $('h1#photo-title').html(item.t);
          $('p#photo-description').html(item.d);
		  var cats = "";
		  jQuery.each(item.cat, function(i, val) {
		  	cats += "<a href='/photo/category/"+val.cl+"'>"+val.ct+"</a>";
			if (i+1 < item.cat.length)
			cats+= "&nbsp;|&nbsp;";	
	});
		  if (cats == "") cats = "Not Available";
		  $('span#photo-category').html(cats);
		  
		  var albs = "";
		  jQuery.each(item.alb, function(i, val) {
		  	albs += "<a href='/photo/album/"+val.al+"'>"+val.at+"</a>";
			if (i+1 < item.alb.length)
			albs+= "&nbsp;|&nbsp;";	
	});
		  albs += "";
		  if (albs == "") albs = "Not Available";
		  $('span#photo-album').html(albs);

          //remember current index
          photo_carousel_current_index = i;
          //update external controls
          //static call
          CarouselExternalControl.prototype.updateNav();
          reloadDartFrameAds();
          //update omniture tracker, print photo and popup icon
          updateOmnitureTracker(item);
		  updateURL(item);
          //updatePrintPhoto(item);
          togglePopupIcon(item);
          //remember clicked item
          photo_carousel_content_id = item.content_id;
        }
        else{
          $(listItems[i]).css('border','none');
        }
      })
    }
/**
 * populate carousel dynamically
 */
function mycarousel_itemAddCallback(carousel, first, last, data)
{
    // Set the size of the carousel
    //carousel.size(parseInt(jQuery('total', xml).text()));

    /*jQuery('image', xml).each(function(i) {
        carousel.add(first + i, mycarousel_getItemHTML(jQuery(this).text()));
    });*/
	
	for(j=0;j<data.length;j++) {
		var i = first + j - 1;
		var item = data[j];
		photoCarouselItems[i] = item;
		var ind = item.po.lastIndexOf(".");
		var thumb_src = "http://www.jimrome.com/cimages/"+item.po.substring(0,ind)+"_article_medium."+item.po.substring(ind+1,item.po.length);
	    carousel.add(i,"<div class=\"photo-carousel-item-wrapper\"><div class=\"photo-carousel-item-overlay\"><img id=\"itemimg_"+i+"\" src=\""+thumb_src+"\" border=\"0\" /></div><div class=\"photo-carousel-tdesc\" id=\"itemdesc_"+i+"\" style=\"margin: 0;\">"+item.t+"</div></div>");
	   
	}

};

/**
 * populate carousel dynamically
 */
 
function photocarousel_itemLoadCallback(carousel,state){
  if(!photoCarouselItems){
    return;
  }
 
  var selected_photo_index;
  if(state == 'init'){
    jQuery.each(photoCarouselItems,function(i, item){
    if(!carousel.has(i)){

	  var ind = item.po.lastIndexOf(".");
	  var thumb_src = "http://www.jimrome.com/cimages/"+item.po.substring(0,ind)+"_article_medium."+item.po.substring(ind+1,item.po.length);
      carousel.add(i,"<div class=\"photo-carousel-item-wrapper\"><div class=\"photo-carousel-item-overlay\"><img id=\"itemimg_"+i+"\" src=\""+thumb_src+"\" border=\"0\" /></div><div class=\"photo-carousel-tdesc\" id=\"itemdesc_"+i+"\" style=\"margin: 0;\">"+item.t+"</div></div>");
      }
    })
    //carousel.options.size = photoCarouselItems.length;
    //debug - spoof large carousel size for testing
    carousel.options.size = photoCarouselActualLength;
    
    //Changed jQuery.click() to jQuery.live() to support event binding for elements added via ajax calls
    $("div#photo-carousel-clip ul li div.photo-carousel-item-wrapper img[id*='itemimg']").live("click",photocarousel_loadMainPhoto);
    $("div#photo-carousel-clip ul li div.photo-carousel-item-wrapper div[id*='itemdesc']").live("click",photocarousel_loadMainPhoto);

    selected_photo_index = photo_carousel_selected_index - 1;
	var ind = photoCarouselItems[selected_photo_index].po.lastIndexOf(".");
	var photo_src = "http://www.jimrome.com/cimages/"+photoCarouselItems[selected_photo_index].po.substring(0,ind)+"_photo_medium."+photoCarouselItems[selected_photo_index].po.substring(ind+1,photoCarouselItems[selected_photo_index].po.length);
    $('div#photo-carousel-fullphoto').html("<img id=\"full-photo\" src=\""+photo_src+"\" height=\""+photoCarouselItems[selected_photo_index].p_h+"\" width=\""+photoCarouselItems[selected_photo_index].p_w+"\" border=\"0\" />").fadeIn('fast');
    //set default selection
    var listItems = $("div#photo-carousel-clip ul li div.photo-carousel-item-wrapper");
	refresh_count = refresh_count +1;
    //update title & description
    $('h1#photo-title').html(photoCarouselItems[selected_photo_index].t);
    $('p#photo-description').html(photoCarouselItems[selected_photo_index].d);	
	
	var cats = "";
	jQuery.each(photoCarouselItems[selected_photo_index].cat, function(i, val) {
		cats += "<a href='/photo/category/"+val.cl+"'>"+val.ct+"</a>";	
		if (i+1 < photoCarouselItems[selected_photo_index].cat.length)
			cats+= "&nbsp;|&nbsp;";	
	});
	if (cats == "") cats = "Not Available";
	$('span#photo-category').html(cats);
	
	var albs = "";
	jQuery.each(photoCarouselItems[selected_photo_index].alb, function(i, val) {
		  	albs += "<a href='/photo/album/"+val.al+"'>"+val.at+"</a>";
			if (i+1 < photoCarouselItems[selected_photo_index].alb.length)
			albs+= "&nbsp;|&nbsp;";	
	});
	if (albs == "") albs = "Not Available";
	$('span#photo-album').html(albs);


    $(listItems[selected_photo_index]).css('border','2px solid #B30202');
    
    //remember current index
    photo_carousel_current_index = selected_photo_index;
    
    //update external controls
    //static call
    CarouselExternalControl.prototype.updateNav();
    
    //update omniture tracker
    updateOmnitureTracker(photoCarouselItems[selected_photo_index]);
	updateURL(photoCarouselItems[selected_photo_index]);
    //override print icon
    //updatePrintPhoto(photoCarouselItems[selected_photo_index]);
    //update enlarge icon
    togglePopupIcon(photoCarouselItems[selected_photo_index]);
  } else {
	  // Check if the requested items already exist.  Checks index for first photo of current page through last photo of next page
	  
	  if(carousel.last+5 > carousel.options.size-1) {
		  currLast = carousel.options.size-1;
	  } else {
		  currLast = carousel.last+5;
	  }//make sure we don't check for items past the end of the carousel
	  if (!carousel.has(carousel.first-1, currLast)) {
		  
		  //items from current carousel page aren't loaded, so get them via ajax
		  var offset = carousel.first - 1;
		  var limit = 12;
		  if(photoCarouselType == "most-recent") {
			  var url = "/photo-ajax/category/most-recent/"+offset+"/"+limit+"/";
		  } else if(photoCarouselType == "album") {
			  var url = "/photo-ajax/album/"+albumSelected+"/"+offset+"/"+limit+"/";
		  }
		  jQuery.getJSON(
	        url,
	        function(data) {
	            mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, data);
	        }
		  );
	  }
	  
  }
  //set pager
  var pager = new CarouselPager(carousel,selected_photo_index);
  pager.updateUI();
}

/**
 * class represents external controls
 */

/**
 * constructor
 * @param integer index 
 */
  
function CarouselExternalControl() {
  this.next_index = null;
  this.prev_index = null;
}

/**
 * calculates indexes for external pagination
 */
 
CarouselExternalControl.prototype.calculate = function(){
  if(photo_carousel_current_index < (photoCarouselItems.length-1)){
    this.next_index = photo_carousel_current_index + 1;
  }
  else{
    this.next_index = null;
  }
  if(photo_carousel_current_index > 0){
    this.prev_index = photo_carousel_current_index - 1;
  }
  if(photo_carousel_current_index==null){
    this.prev_index = null;
  }
}

/**
 * loads main photo
 * @see photocarousel_loadMainPhoto()
 */
 
CarouselExternalControl.prototype.loadMainPhoto = function(index){
  if(index==null){
    return;
  }
  var listItems = $("div#photo-carousel-clip ul li div.photo-carousel-item-wrapper");
  //find & update big image
	jQuery.each(photoCarouselItems,function(i, item){
  if(i == index){
    //set selection on li item
      $(listItems[i]).css('border','2px solid #B30202');
      var height = item.p_h + 'px';
	  var ind = item.po.lastIndexOf(".");
	  var photo_src = "http://www.jimrome.com/cimages/"+item.po.substring(0,ind)+"_photo_medium."+item.po.substring(ind+1,item.po.length);
      $('div#photo-carousel-fullphoto').css('height',height).hide();
      $('div#photo-carousel-fullphoto').html("<img src=\""+photo_src+"\" height=\""+item.p_h+"\" width=\""+item.p_w+"\" border=\"0\" />").fadeIn('normal');
	  refresh_count = refresh_count +1;
      $('h1#photo-title').html(item.t);
      $('p#photo-description').html(item.d);
	  
	  var cats = "";
		  jQuery.each(item.cat, function(i, val) {
		  	cats += "<a href='/photo/category/"+val.cl+"'>"+val.ct+"</a>";	
			if (i+1 < item.cat.length)
			cats+= "&nbsp;|&nbsp;";	
	});
		  if (cats == "") cats = "Not Available";
		  $('span#photo-category').html(cats);
		  
		  var albs = "";
		  jQuery.each(item.alb, function(i, val) {
		  	albs += "<a href='/photo/album/"+val.al+"'>"+val.at+"</a>";	
			if (i+1 < item.alb.length)
			albs+= "&nbsp;|&nbsp;";	
	});
		  if (albs == "") albs = "Not Available";
		  $('span#photo-album').html(albs);
		  
      photo_carousel_current_index = i;
      //static call
      CarouselExternalControl.prototype.calculate();
    }
    else{
      $(listItems[i]).css('border','1px solid #FFFFFF');
    }
  })
}

/**
 * move to prev photo
 */

CarouselExternalControl.prototype.prev = function(){
  this.calculate();
  this.loadMainPhoto(this.prev_index);
  this.updateNav();
}

/**
 * move to next photo
 */

CarouselExternalControl.prototype.next = function(){
  this.calculate();
  this.loadMainPhoto(this.next_index);
  this.updateNav();
}


/**
 * enables/disables prev/next navigation
 */

CarouselExternalControl.prototype.updateNav = function(){
    var l = photoCarouselActualLength -1;
    var active = {'opacity': '1.0','filter': 'alpha(opacity=100)','-moz-opacity': '1.0','cursor': 'pointer'}
    var inactive = {'opacity': '0.5','filter': 'alpha(opacity=50)','-moz-opacity': '0.5','cursor': 'default'}
    
    if(photo_carousel_current_index==l){
      $('div#photo-carousel-next-external').css(inactive);
    }
    else{
      $('div#photo-carousel-next-external').css(active);
    }
    if(photo_carousel_current_index==0){
      $('div#photo-carousel-prev-external').css(inactive);
    }
    else{
      $('div#photo-carousel-prev-external').css(active);
    }
}

/**
 * attach click event to external control
 */
 
jQuery(document).ready(function() {
  $('div#photo-carousel-prev-external').click(function(){
    var extCtrl = new CarouselExternalControl();
    extCtrl.prev();
  })
  $('div#photo-carousel-next-external').click(function(){
    var extCtrl = new CarouselExternalControl();
    extCtrl.next();
  })
})

/**
 * class represents paging for Carousel
 */
 
/**
 * constructor
 * @param jCarousel carousel
 */
  
function CarouselPager(carousel) {
  this.total = carousel.options.size || null;
  this.items_per_page = carousel.options.scroll || null;
  this.first_item_in_range = carousel.first;
  this.last_item_in_range = carousel.last;
}

/**
 * updates UI 
 * @return void 
 */
 
CarouselPager.prototype.updateUI = function(){
  var  num_items = this.last_item_in_range;
  if(this.total < num_items){
    num_items = this.total;
  }
  $("div#photo-carousel-pager").html(this.first_item_in_range + ' - ' + num_items + ' of ' + this.total);
} 

 /**
  * reloads dart ads (frame) 
  */ 
function reloadDartFrameAds(){
	if (refresh_count % 3 == 0) {
		var iframes = $("iframe[id='dart-iframe']");
		jQuery.each(iframes,function(i,v){
			try{
				v.contentWindow.location.reload(true);
			}
			catch(e){
				var temp = v.src
				v.src = '';
				v.src = temp;
			}
		})
	}
}

/**
 * updates omniture tracking
 * @param object item 
 */
 
 function updateOmnitureTracker(item){
  if(!item || !item.id || !item.t){
    return;
  }
  var tracker_url = 'http://metrics.premiereinteractive.com/b/ss/ccpremiere,ccpremiere07/1/G.4--NS/1255377556';
  
  var trackerData = {
            pageName: omnitureTrackDataStatic.omniture_category + ":" + item.t + " - Photos",
            g: "http://www.jimrome.com/photo/plink/"+item.id,
			c3: item.t,
			c5: "website",
            c6: "JimRome",
            c8: "SPORTS",
            c10: omnitureTrackDataStatic.omniture_category,
            c35: site_visitor
            }
  var trackImg = $("img[id='omniture-tracker']");
  if(!trackImg || !trackImg.length || trackImg.length!=1 || !trackImg[0].src){
    return;
  }
  var arr = [];
  jQuery.each(trackerData,function(prop,value){
    arr.push(prop + "=" + escape(value));
  })
  var src = tracker_url + '?' + arr.join("&");
  trackImg[0].src = src;
 }

/**
 * updates omniture tracking
 * @param object item 
 */
 
 function updateURL(item){
  if(!item || !item.id || !item.t){
    return;
  }
  clickTitle = item.t + " - Photos - The Jim Rome Show";
  clickURL = "http://"+location.host+'/photo/plink/'+item.id;
  //window.location.hash = item.id;
 }
 
 
 /**
  * enables/disables pop-up icon
  */ 
  
  function togglePopupIcon(item){
    if(!item){
      return;
    }
    var link = '';
    if(item.enlarge == '1'){
      link = '<a href="javascript:popImage(\'http://www.jimrome.com/cimages/'+item.po+'\')"><img src="/images/icons/icon_enlarge.gif" border="0" width="34" height="24" /></a>';
    }
    else{
      link = '<img src="/images/icons/icon_enlarge_inactive.gif" border="0" width="34" height="24" />';
    }
    $('div#photo-carousel-enlarge-icon').html(link);
  } 

/**
 * enables/disables nav arrows
 * @param boolean is_on
 * @param string id
 * @param string direction [left,right] 
 */
 
 function toggleNavigationIcons(is_on,id,direction){
  if(!id || !direction){
    return;
  }
  var nav_icon;
  if(is_on){
    nav_icon = '<img src="/images/icons/icon_arrowgallery'+direction+'.gif" border="0" />';
  }
  else{
    nav_icon = '<img src="/images/icons/icon_arrowgallery'+direction+'_inactive.gif" border="0" />';
  }
  $('div#'+id).html(nav_icon);
 }
 

