/**
 * photo viwer carousel lib
 * @author sash 
 * @version $Id: photo_carousel.js 5547 2010-10-07 01:03:47Z omid $
 */

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]);
        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]);
        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.photo_height + 'px';
          $('div#photo-carousel-fullphoto').css('height',height).hide();
          $('div#photo-carousel-fullphoto').html("<img src=\""+item.src_photo+"\" height=\""+item.photo_height+"\" width=\""+item.photo_width+"\" border=\"0\" />").fadeIn('normal');
		  refresh_count = refresh_count +1;
          $('h1#photo-title').html(item.title);
          $('p#photo-description').html(item.description);
          //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);
          updatePrintPhoto(item);
          togglePopupIcon(item);
          //remember clicked item
          photo_carousel_content_id = item.content_id;
        }
        else{
          $(listItems[i]).css('border','1px solid #FFFFFF');
        }
      })
    }

/**
 * 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)){
      // Add the item
      carousel.add(i,"<div class=\"photo-carousel-item-wrapper\"><div class=\"photo-carousel-item-overlay\"><img id=\"itemimg_"+i+"\" src=\""+item.src_thumbnail+"\" width=\"147\" height=\"83\" border=\"0\" /></div><div class=\"photo-carousel-tdesc\" id=\"itemdesc_"+i+"\" style=\"margin: 0;\">"+item.title+"</div></div>");
      }
    })
    carousel.options.size = photoCarouselItems.length;
    $("div#photo-carousel-clip ul li div.photo-carousel-item-wrapper img[id*='itemimg']").click(photocarousel_loadMainPhoto);
    $("div#photo-carousel-clip ul li div.photo-carousel-item-wrapper div[id*='itemdesc']").click(photocarousel_loadMainPhoto);
    selected_photo_index = photo_carousel_selected_index - 1;
    $('div#photo-carousel-fullphoto').html("<img id=\"full-photo\" src=\""+photoCarouselItems[selected_photo_index].src_photo+"\" height=\""+photoCarouselItems[selected_photo_index].photo_height+"\" width=\""+photoCarouselItems[selected_photo_index].photo_width+"\" border=\"0\" />").fadeIn('fast');
	refresh_count = refresh_count +1;
    //set default selection
    var listItems = $("div#photo-carousel-clip ul li div.photo-carousel-item-wrapper");
    //update title & description
    $('h1#photo-title').html(photoCarouselItems[selected_photo_index].title);
    $('p#photo-description').html(photoCarouselItems[selected_photo_index].description);
    $(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]);
    //override print icon
    updatePrintPhoto(photoCarouselItems[selected_photo_index]);
    //update enlarge icon
    togglePopupIcon(photoCarouselItems[selected_photo_index]);
  }
  //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.photo_height + 'px';
      $('div#photo-carousel-fullphoto').css('height',height).hide();
      $('div#photo-carousel-fullphoto').html("<img src=\""+item.src_photo+"\" height=\""+item.photo_height+"\" width=\""+item.photo_width+"\" border=\"0\" />").fadeIn('normal');
	  refresh_count = refresh_count +1;
      $('h1#photo-title').html(item.title);
      $('p#photo-description').html(item.description);
      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 = photoCarouselItems.length -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) {	
	  try{
		var iframes = $("iframe[id='dart-iframe']");
		jQuery.each(iframes,function(i,v){
		   v.contentWindow.location.reload(true);
		})
	  }
	  catch(e){
	  }
	}
}

/**
 * reloads dart ads
 * @return void
 */
   
function reloadDartAds(){
  try{
    //check click state
    if(photo_carousel_clk_state==1){
      photo_carousel_clk_state = 0;
      //return;
    }
    else{
      photo_carousel_clk_state = 1;
    }
		var dartIDs = [9001,9026,9003,9046];
		var links = [];
		var images = [];
    var link1, image1;
    
	  if(dartData.length==0){
		  $("a[id^='dart-link-']").each(function(){
		  var arr = this.id.split('-');
		  var href = this.href;
		  jQuery.each(dartIDs,function(i,v){
        if(v==arr[2]){
           links.push({pagepos: arr[2], link: href});
        }
      })
    })
    
    $("img[id^='dart-image-']").each(function(){
		  var arr = this.id.split('-');
		  var src = this.src;
		  jQuery.each(dartIDs,function(i,v){
        if(v==arr[2]){
          images.push({pagepos: arr[2], image: src});
        }
      })
    })

    for(var i=0;i<dartIDs.length;i++){
      link1 = image1 = null; 
      for(var j=0;j<links.length;j++){
		      if(links[j].pagepos==dartIDs[i]){
		        link1 = links[j].link;
		        break;
          }
      }

      for(var j=0;j<images.length;j++){
		      if(images[j].pagepos==dartIDs[i]){
		        image1 = images[j].image;
		        break;
          }
      }
      if(link1 && image1){
        dartData.push({pagepos: dartIDs[i], image: image1, link: link1});
      }
    }
	}

	jQuery.each(dartIDs,function(i, pagepos){
		  var tid = '&transactionID='+Math.round(Math.random()*10000000);
		  var links, images;
		  for(var j=0;j<dartData.length;j++){
		      if(dartData[j].pagepos==pagepos){
			     links = $("a[id='dart-link-"+pagepos+"']");
			     images = $("img[id='dart-image-"+pagepos+"']");
			     links[0].href = dartData[j].link + tid;
           images[0].src = dartData[j].image + tid;
		       break;
          }
      }
    })
    
    //refresh side ad
    //refreshDartIframe('9028');
	}
	catch(e){
	 //alert(e.toString());
	}
}

 /**
  * refreshes iframe 
  */ 

 function refreshDartIframe(id){
  if(!id){
    return;
  }
  try{
    var iframe = $("iframe[id='dart-ifr-"+id+"']");
    if(!iframe || !iframe.length){
      return;
    }
    iframe[0].contentWindow.location.reload(true);
  }
  catch(e){
  }
 }

/**
 * updates omniture tracking
 * @param object item 
 */
 
 function updateOmnitureTracker(item){
  if(!item || !item.content_id || !item.identifier || !item.title){
    return;
  }
  var tracker_url = 'http://metrics.premiereinteractive.com/b/ss/ccpremiere,ccpremiere10,ccpremiereconservativetalk/1/G.4--NS/1255377556';
  
  var trackerData = {
            pageName: omnitureTrackDataStatic.omniture_category + ":" + item.title + " - Photos",
            g: "http://www.hannity.com/photo/plink/"+item.identifier+"/"+item.content_id,
            c4: item.content_id,
            c6: "SeanHannity",
            c8: "NEWSTALK",
            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;
 }
 
 /**
  * changes print icon click to permalink page
  * @param object item  
  */ 

 function updatePrintPhoto(item){
  if(!item || !item.content_id || !item.identifier){
    return;
  }
  var img = $("img[id='cb-print-icon']");
  if(!img || !img.length || img.length!=1 || !img[0].src){
    return;
  }
  $(img[0]).bind('click',function(){
    var pattern = /\-/gi;
    var id = item.identifier.replace(pattern,'_');
    //@todo - switch to independent function
    MM_openBrWindow('/photo/plink/'+id+'/'+item.content_id+'?mode=print','bobandtomprint','resizable=yes,scrollbars=yes,width=400,height=500');
    return false;
  })
 }

 /**
  * enables/disables pop-up icon
  */ 
  
  function togglePopupIcon(item){
    if(!item){
      return;
    }
    var link = '';
    if(item.src_photo_orig){
      link = '<a href="javascript:popImage(\''+item.src_photo_orig+'\')"><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/photogallery/misc_arrowgallery'+direction+'.gif" border="0" width="11" height="20" />';
  }
  else{
    nav_icon = '<img src="/images/photogallery/misc_arrowgallery'+direction+'_inactive.gif" border="0" width="11" height="20" />';
  }
  $('div#'+id).html(nav_icon);
 }
 

