$(document).ready(function() {
	if (typeof ssProp !== 'undefined'){
		// External data must be present
		if (typeof(slideshowData) === 'undefined') { if (typeof window.console == 'object') { console.log('No slideshow data found.'); } }
		else {
			ssProp['data']= slideshowData;
			slideShowDisplay.init(ssProp);
		}
	}
	slideShowOverlay();
});

//example config to be configured inline (on page):
/*
var ssProp = { 
	id:'slideshow',
	imgShowCount: 7,
	linkHref: 'http://' + location.host + location.pathname + '?slide='
};
*/ 
var slideShowDisplay = {
	slideshow: {},
	boolCheck: {},
	init: function(prop) {
		var bool = this.boolCheck;
		for (i in prop) { this.slideshow[i] = prop[i]; }
		this.currentItem = ($.query.get('slide'))?$.query.get('slide'):1;
		this.slideshow['obj']= $("#"+this.slideshow['id']);
		this.count = (this.slideshow['data']['items']).length;
		this.linkHref = this.slideshow['linkHref'];
		this.showText();
		if (!bool['navigation']) { this.mainNav(); }
		if (!bool['mainImage']) { this.showMainImage(); }
		if (!bool['thumbnail']) { this.thumbnailCarousel(); }
		if (!bool['showOverlay']) { this.showOverlay(); }
	},
	initInline: function(prop) {
		prop['data'] = window.slideshowData;
		currentSlideNum = ($.query.get('slide'))?$.query.get('slide'):1
		document.title += " - Slide " + currentSlideNum + " of " + window.slideshowData.items.length;
		this.init(prop);
	},
	reset: function() {	},
	showOverlay: function() {
		var currentItem = this.currentItem;
		if (currentItem==this.count) { setTimeout(function(){ showOverlay(); },10000); }
		this.boolCheck['showOverlay']=true;
	},
	mainNav: function() {
		var thisObj = this;
		var sshow = this.slideshow['obj'];
		var count = this.count; 
		var currentItem = parseInt(this.currentItem);
		if (currentItem<=1) { // Previous button
			$("#mainslidePrev",sshow).addClass("previousInactive").removeClass("previous")
				.unbind("click");
		} else {
			$("#mainslidePrev",sshow).addClass("previous").removeClass("previousInactive")
				.unbind("click")
				.click(function(){ 
					thisObj.currentItem = currentItem-1;
					thisObj.navigate.main.pageBrowse(thisObj);
					//thisObj.navigate.main.inPageBrowse(thisObj);
				});
		}
		if (currentItem>=count) { // Next button
			$("#mainslideNext",sshow).addClass("nextInactive").removeClass("next")
				.unbind("click")
				.click(function(){
					showOverlay();
					clearTimeout(thisObj.showOverlayTimeout);
					thisObj.boolCheck['showOverlay']=true;
				});
		} else {
			$("#mainslideNext",sshow).addClass("next").removeClass("nextInactive")
				.unbind("click")
				.click(function(){ 
					thisObj.currentItem = currentItem+1;
					thisObj.navigate.main.pageBrowse(thisObj); 
					//thisObj.navigate.main.inPageBrowse(thisObj);
				});
		}
		thisObj.boolCheck['navigation']=true;
	},
	showText: function() {
		var thisObj = this;
		var sshow = this.slideshow['obj'];
		var count = this.count; 
		var currentItem = parseInt(this.currentItem);
		var data = this.slideshow['data']['items'][this.currentItem-1];
		var sideStr = [];
		$("#mainSlidePager",sshow).html(currentItem+' of '+count); // Nav title
		sideStr.push('<h3>'+data['title']+'</h3>');
		sideStr.push('<p>'+data['description']+'</p>');
		sideStr.push((data['source'].length>0)?'<p><span>Source:</span> '+data['source']+'</p>':'');
		$(".slideSideCol .slidedesc").html(sideStr.join(" "));
	},
	showMainImage: function() {
		var thisObj = this;
		var sshow = this.slideshow['obj'];
		var data = this.slideshow['data']['items'][this.currentItem-1];
		var img = '<li><img id="mainslideimage" src="'+data['media']['m']+'" alt="'+data['alt']+'"/></li>';
		$("#mainSlide",sshow).html(img);
		$("#mainSlide",sshow).parent().removeClass("tempHeight");
		if ($("#mainSlide li img",sshow).size()>0) thisObj.boolCheck['mainImage']=true;
	},
	navigate: {
		main: {
			pageBrowse: function(thisObj) { window.location = thisObj.linkHref+(thisObj.currentItem+""); },
			inPageBrowse: function(thisObj) {
				thisObj.showMainImage();
				thisObj.mainNav();
				thisObj.showOverlay();
			}
		}
	},
	thumbnailCarousel: function() {
		var thisObj = this;
		var sshow = this.slideshow['obj'];
		var data = this.slideshow['data']['items'];
		var showCount = this.slideshow['imgShowCount'];
		var currentItem = this.currentItem;
		var linkHref = this.linkHref;
		var imgStr = [];
		$.each(data,function(i,item){
			var cleanTitle = escape(item.title);
			var count = i+1;
			imgStr.push('<li><a href="javascript:void(0);"><img'+((currentItem==count)?' class="activeSlide"':'')+' src="'+item.media.tm+'" alt="'+cleanTitle+'" slideid="'+count+'" width="60" height="60" /></a></li>')
		});	
		$("#thumb-carousel",sshow).html(imgStr.join(" "));
		// Initialize Slider
		thisObj['thumbnailSlider'] = $("#thumb-carousel",sshow).slider({ callback:thisObj.thumbnailCarouselCallback,scroll:1,visible:1,showObj:thisObj });
		// Initialize Position
		if (currentItem>showCount) {
			thisObj['thumbnailSlider'].slideTo(currentItem-showCount);
		}
		// Initialize events
		$("#thumb-carousel li a",sshow).each(function(i){
			$(this).unbind("click").click(function(){
				window.location = linkHref+((i+1)+"");
			})
			$("img",this).hover(function(){ mouseOverListener(this); },function(){ mouseOutListener(this); })
		});
		if(data.length>0) { thisObj.boolCheck['thumbnail']=true; }
		
		function mouseOverListener(obj) {
			var descriptionHeight = $(sshow).height();
			/* "CONSTANTS" NEEDED for bubble placement to work right*/ 
			var TOP_TO_IMAGE = 60;
			var IMAGE_T0_MENU = 55;
			var BUBBLE_HEIGHT = 30;
			var SLIGHT_OFFSET = 85;
			// IE 7's spacing is different for some reason.
			var IE7_OFFSET = 15;
	        var ulPos = $(".slide_carousel",sshow).offset();
			var imgPos = $(obj).offset();
			var imgPosLeft = (imgPos.left-ulPos.left)+2;
			var carouselHeight = $(".slide_carousel",sshow).height();
			var imageHeight = $("#mainSlide li img",sshow).height();
			var dekHeight = $("#sliderdesc",sshow).height();
			
			var bottomSpace = descriptionHeight - parseInt(TOP_TO_IMAGE+imageHeight+IMAGE_T0_MENU+carouselHeight );
			var imgPosTop = TOP_TO_IMAGE + imageHeight + (BUBBLE_HEIGHT - 10);
			//var imgPosTop = descriptionHeight - (bottomSpace+carouselHeight-BUBBLE_HEIGHT)+(dekHeight-SLIGHT_OFFSET);
			if ($.browser.msie && parseInt($.browser.version) == 7) { imgPosTop -= IE7_OFFSET; }

			var slide = $(obj).attr("slideid");
			var imgCaptionLength = $(obj).attr("alt").length;
			var altCaption = unescape($(obj).attr("alt"));
			var imgCaption = (imgCaptionLength>43)?altCaption.substring(0,43)+'...':altCaption;
			$(".slide_title .bubble-mid",sshow).html("<p>"+imgCaption+"</p>");
			var bubbleWidth = $(".slide_title .bubble-mid",sshow).width() ;
  			if(parseFloat(bubbleWidth)<34){
  				$(".slide_title .bubble-mid",sshow).css("width","34px");
			}

  			$(".slide_title",sshow).css({ visibility:"visible",left:imgPosLeft+"px",top:imgPosTop+"px" });
		};
		
		function mouseOutListener(obj) {
			$(".slide_title",sshow).css("visibility","hidden");
		}
		
	},
	thumbnailCarouselCallback: function(obj) {
		var thisObj = this.showObj;
		var sshow = thisObj.slideshow['obj'];
		var currentItem = parseInt(thisObj.currentItem);
		var count = thisObj.count;
		var showCount = thisObj.slideshow['imgShowCount'];
		
		//thumbnail slideshow
		if (currentItem<=1) {
			$(".slide_carousel .slide-prev input",sshow).addClass("leftBtnInactive").removeClass("leftBtn");
		} else {
			$(".slide_carousel .slide-prev input",sshow).addClass("leftBtn").removeClass("leftBtnInactive");
		}
		$(".slide_carousel .slide-prev input",sshow)		
			.unbind("click")
			.click(function(){
				obj.slidePrev();
				if (obj.opts.slideLeft) {
					if (obj.opts.index<(obj.totalPage)-1) {
						$(".slide_carousel .slide-next input",sshow).addClass("rightBtn").removeClass("rightBtnInactive")
					}
					if (obj.opts.index<=0) {
						$(this).addClass("leftBtnInactive").removeClass("leftBtn");
		            }
		        }
		        return false;
			});
		if (currentItem>=count) {
			$(".slide_carousel .slide-next input",sshow).addClass("rightBtnInactive").removeClass("rightBtn");
		} else {
			$(".slide_carousel .slide-next input",sshow).addClass("rightBtn").removeClass("rightBtnInactive");
		}
		$(".slide_carousel .slide-next input",sshow)
			.unbind("click")
			.click(function(){
				if ((obj.opts.index+showCount)<obj.totalPage) { obj.slideNext(); }
				else { if (currentItem==obj.totalPage) { overlayWithReplay('on'); } }
				if (obj.opts.slideRight) {
					if ((obj.opts.index+showCount)>0) {
						$(".slide_carousel .slide-prev input",sshow).addClass("leftBtn").removeClass("leftBtnInactive");
					}
					if ((obj.opts.index+showCount)>=obj.totalPage) {
						$(this).addClass("rightBtnInactive").removeClass("rightBtn");
					}
				}
				return false;
			});
	}
};

// Slideshow Overlay
function slideShowOverlay() {
	$("#slideoverlayreplay").hide();
	$("#slideshow .morevideos_placeholder").each(function(){ 
		$("a",this).attr("href","javascript:void(0);")
			.click(function(){ overlayWithReplay(''); }); 
	});
	
	$("#bigboxreplay").removeClass("overlaybox");
	//overlaySlideshow //#bigbox
	var slider2 = $("#bigbox").slider({ callback:overlaySlider,li:590,visible:1,scroll:1,padding:10,speed:1000 });

	//disable next button
	if (slider2.totalPage<=1) {
		$("#slideoverlayreplay .overlay_carousel .slide-next input").addClass("rightBtnInactive").removeClass("rightBtn");
	}
	
	// Related data (?)
	if ((typeof relatedsData !== 'undefined') && relatedsData.items.length > 0) {
		var html = [];
		html.push('<h4>Related Articles</h4><ul>');
		$.each(relatedsData.items,function(i,item){
			html.push('<li><a href="'+item.url+'">'+item.headline+'</a></li>');
		});
		html.push('</ul>');
		$(".slideSideCol .sliderelated").html(html.join(" "));
	}
}

// Legacy functions, optimized
/*
 * Modified by btobon
 * v 1.02
 */

// number of images shown in the main slider, for calculating when to disable the right arrow button
var mainSliderNumShownImages = 7;
// number of images shown in the overlay slider, for calculating when to disable the right arrow button
var overlaySliderNumShownImages = 1;

function changeClass() {
	var msClass = $("#seeMoreSlides").attr("class");
	$("#seeMoreSlides").attr("class",(msClass=='moreslides')?"moreslides_off":msClass);
}

function generatePager(cur, tot) {
    var output = '';
    for (i=0; i<=tot; i++) {
		output += '<img src="images/'+((i==cur)?'dot_red':'dot_clear')+'.gif" page="'+i+'"/>';
    }
    return output;
}

//overlay slideshow
function overlay(divId) {
	$("#"+divId).each(function(){
		$("#bigbox",this).css("right","0px");
		$(".overlay_carousel .slide-prev input",this).addClass("leftBtnInactive").removeClass("leftBtn");
		$(".overlay_carousel .slide-next input",this).addClass("rightBtn").removeClass("rightBtnInactive");
		$(this).css("visibility","visible");
		$(this).toggle();
	});
}

function overlayWithReplay(isOn) {
	var recon = $("#bigboxreplay").html();
	var con = $("#bigbox").html()
    if (isOn) {
    	if ($('#bigbox li.replay').size()<=0) {
    		$('#bigbox').empty().append(recon);
    		$('#bigboxreplay').empty().append(con);
    	}
    } else {
    	if ($('#bigbox li.replay').size()>0) {
    		$('#bigbox').empty().append(recon);
        	$('#bigboxreplay').empty().append(con);
    	}
    }
    overlay('slideoverlay');	
}

function overlaySlider(obj) {
	
	$("#slideoverlay, #slideoverlayreplay").each(function(){
		var idObj = this;
		var thisId = $(this).attr("id");
		$(".overlay_carousel .slide-prev input",idObj).click(function(){
			obj.slidePrev();
			if (obj.opts.slideLeft) {
				//make next active
				if (obj.opts.index<(obj.totalPage)-1) {
					$(".overlay_carousel .slide-next input",idObj).addClass("rightBtn").removeClass("rightBtnInactive");
	            }
	            //make prev inactive
	            if (obj.opts.index<1) {
					$(this).addClass("leftBtnInactive").removeClass("leftBtn");
	            }
	        }
	        return false;
		});
		$(".overlay_carousel .slide-next input",idObj).click(function(){
			if ((obj.opts.index+overlaySliderNumShownImages)<(obj.totalPage)) {
	            obj.slideNext();
	        }
			if (obj.opts.slideRight) {
	            //make prev active
	            if (obj.opts.index>0) {
					$(".overlay_carousel .slide-prev input",idObj).addClass("leftBtn").removeClass("leftBtnInactive");
	            }
	            //make next inactive
	            if ((obj.opts.index+overlaySliderNumShownImages)>=(obj.totalPage)) {
					$(this).addClass("rightBtnInactive").removeClass("rightBtn");
	            }
	        }
	        return false;
		});
		
		$(".header",idObj).each(function(){
			$(".closetext",this).html('<a href="#">close</a>');
			
			$(".close a, .closetext a",this).each(function(){
				$(this).attr("href","javascript:void(0);")
					.click(function(){
						overlay(thisId);
						obj.opts.index = 0;
						return false;
					});
			});
				
		});
	})
}

function showOverlay() {
  overlayWithReplay('on');
  return false;
}