var auto_play;
var counterID;
var carItem;
var loading=true;
var loadThumbs=false;
var thumbUrl="";
var thumbNum;
var thumbData;
var loadDir="";
var ssData="";
var ssNum=0;
var currentPhoto = 1;
var previousPhoto = 1;
var jsonUrl = "";
var dynamicData;
var slideNum;
var restartAuto=false;
var runwayLooks = "runway look, collection, details, runway hits, runway misses";
var isRunwayLook;
var interstitialTimer;
var scrollTop=0;
var jared;

function startSlideshow(curr, num){
	if(typeof curr == "object")
		ssNum = $nymag_j(".slideshow-link").index($nymag_j(curr).parents(".module").find(".slideshow-link"));
	else
		ssNum = curr;
		
	jsonUrl = ssLinks[ssNum];
	dynamicData = (jsonUrl.search(/search.cgi/) > 0) ? true : false;
	if(num){
		slideNum=parseInt(num);
		if(dynamicData){
			jsonUrl = jsonUrl.replace(/Nao=\d*/,"Nao=" + ((Math.ceil(slideNum/15)-1)*15+1));
			currentPhoto = slideNum%15;
			if(currentPhoto == 0) currentPhoto=15;
		} else {
			currentPhoto = slideNum;
		}
	} else {
		slideNum=1;
	}	
	
	loading=true;
	ssData = "";
	counterID=1;
	hideAds();
	$nymag_j("#slide-img-col ul").html("").css("left","0");
	$nymag_j("#thumbnails").css("height","1px").hide();
	$nymag_j("#thumbnails .thumb-wrp ul.thumbs").html("");
	$nymag_j("#slideshow-btns .next, #runway-next, #slideshow-btns .prev, #runway-previous").unbind("click");
	scrollTop = document.getElementById('slideshow-container').offsetTop;
	if($nymag_j.browser.msie)
			$nymag_j("#slideshow-container").css("left",$nymag_j('#wrap')[0].offsetLeft + "px");
	$nymag_j('#slideshow-container').jqmShow();
	return false;
}

$nymag_j("#slideshow-container").jqm({
	onHide: function(h){
		$nymag_j("#slideshow-btns .stop").click();
		if($nymag_j.browser.msie){
			h.w.hide();
			h.o.remove();
		} else {
			h.w.fadeOut(500);
			h.o.css("opacity","1").css("filter","alpha(opacity=100)").fadeOut(1000, function callback(){ h.o.remove(); });	
		}
		location.hash = " ";
		showAds();
	},
	onShow: function(h){
		if($nymag_j.browser.msie){
			h.w.show();
		//	h.o.css("opacity",".97").css("filter","alpha(opacity=97)").show();
			$nymag_j("#ajax-load-gfx").show();
			$nymag_j.getJSON(jsonUrl, function(data){ $nymag_j("#ajax-load-gfx").hide(); buildCarousel(data); });
			if(!scrollTop) scrollTop = document.getElementById('slideshow-container').offsetParent.offsetTop;
			window.scrollTo(0,scrollTop);
			window.nymag.dcads.reloadAd("728x90","slideshow",true);
			window.nymag.dcads.reloadAd("300x250","slideshow",true);
		} else {
			h.o.hide();
			h.o.css("opacity",".97").css("filter","alpha(opacity=97)").fadeIn(
				1000,
				function callback(){
					h.w.show();
					$nymag_j("#ajax-load-gfx").show();
					$nymag_j.getJSON(jsonUrl, function(data){ $nymag_j("#ajax-load-gfx").hide(); buildCarousel(data); });
					if(!scrollTop) scrollTop = document.getElementById('slideshow-container').offsetParent.offsetTop;
					window.scrollTo(0,scrollTop);
					window.nymag.dcads.reloadAd("728x90","slideshow",true);
					window.nymag.dcads.reloadAd("300x250","slideshow",true);
				}
			);
		}
	}
});

$nymag_j("#header-container h5 a").click(function(){
	$nymag_j("#slideshow-container").jqmHide();
	return false;
});

function interstitial(elem){
	if(counterID>=7){ 
		restartAuto = ($nymag_j("#slideshow-btns .stop").css("display")=="none") ? false : true;
		$nymag_j("#slideshow-btns .stop").click();
		$nymag_j("#slideshow-container").addClass("interstitial");
		if($nymag_j.browser.msie && $nymag_j.browser.version==6){
			window.scroll(0,0);
			$nymag_j("#slideshow-container").css("top","0").css("left","0").css("width","100%").css("height","100%");
		}
		
		$nymag_j("#slideshow-container .interstitial").fadeIn("slow");
		if($nymag_j.browser.safari)
			$nymag_j("#slideshow-container").removeClass("interstitial");
	
		window.nymag.dcads.reloadAd("700x440","slideshow-interstitial",true);
		counterID=0;
		interstitialTimer = setTimeout(continueSlideshow,15000);
	}
	$nymag_j(".photo-credit",elem).fadeOut("slow");
	//elem.children("img").animate({"opacity":".25","filter":"alpha(opacity=25)"});
	//if(isRunwayLook) elem.children("img").css("opacity",".25").css("filter","alpha(opacity=25)");
}
function continueSlideshow(){
	clearTimeout(interstitialTimer);
	$nymag_j("#slideshow-container").removeClass("interstitial");
	if($nymag_j.browser.msie && $nymag_j.browser.version==6){
		$nymag_j("#slideshow-container .interstitial").fadeOut("slow",function(){
			$nymag_j("#slideshow-container").css("top","0").css("left","18%").css("width","980px").css("height","");
		});
	}
	else
		$nymag_j("#slideshow-container .interstitial").fadeOut("slow");
	window.scroll(0,scrollTop);

	if(restartAuto)
		$nymag_j("#slideshow-btns .play").click();
}

function showAds(){
	$nymag_j("#728x90").show();
	$nymag_j("#160x600").show();
	$nymag_j("#336x280").show();
	$nymag_j("#260x60").show();
	$nymag_j("body").children("div[id*='VwP236']").css({display:"none"});
}
function hideAds(){
	$nymag_j("#728x90").hide();
	$nymag_j("#160x600").hide();
	$nymag_j("#336x280").hide();
	$nymag_j("#260x60").hide();
	$nymag_j("body").children("div[id*='VwP236']").css({display:"none"});
}
function scrollingAdd(curr_div, car){
	if(currentPhoto<ssData.slideshow.slides.count){
		var addCount = 2;
		var addPhoto = parseInt(ssData.slideshow.slides.count)-addCount;
		var addUrl = ssData.slideshow.nextDataUrl;
		if(car.dir=="back"){
			addCount = -3;
			addPhoto = 2;
			addUrl = ssData.slideshow.previousDataUrl;
		}
	
		if((currentPhoto==addPhoto) && (addUrl != "0")){
			$nymag_j("#ajax-load-gfx").show(); 
			$nymag_j.getJSON(addUrl, function(data){ $nymag_j("#ajax-load-gfx").hide();  loadNextDataSet(data); });
			carItem = car;
			return false;
		}
		else if((currentPhoto >= 1) && (currentPhoto <= ssData.slideshow.slides.count-2)){
			var nextImg = currentPhoto+addCount;
			if( ((car.dir=="next") && (currentPhoto < ssData.slideshow.slides.count-2)) || ((car.dir=="back") && (currentPhoto > 3)) )
				$nymag_j("#slide-img-col ul li:eq(" + (nextImg) + ") img").attr("src","" + ssData.slideshow.slides.slide[nextImg].path);
			car.goCall(car.goNext);
		}
		else {
			car.goCall(car.goNext);
		}
	} else {
		if(car.dir == "back"){
			//if(isRunwayLook) curr_div.children("img").css("opacity",".25").css("filter","alpha(opacity=25)");
			car.goCall(car.goNext);
		} else{
			$nymag_j("#ajax-load-gfx").show(); 
			$nymag_j.getJSON(jsonUrl, function(data){ $nymag_j("#ajax-load-gfx").hide(); reloadSlideshow(data,1); });
		}
	}
}
function updateData(elem){
	//if(isRunwayLook) elem.children("img").animate({"opacity":"1","filter":"alpha(opacity=100)"});
	//if(isRunwayLook) elem.children("img").css("opacity","1").css("filter","alpha(opacity=100)");
	
	slideshowStatCall(ssData.slideshow.type);
	
	previousPhoto = currentPhoto;
	currentPhoto = $nymag_j("#slide-img-col ul li").index(elem) + 1;
	
	// if back button pressed, cancel auto-play
	if(previousPhoto > currentPhoto) $nymag_j("#slideshow-btns .stop").click();
	
	// update page data for photo
	changeInfo(elem);
	
	// increase interstitial counter			
	counterID++;
	
	// update hash
	parent.location.hash = "slide"+ ssData.slideshow.slides.slide[currentPhoto-1].count + "&ss" + (ssNum+1);
	slideNum = parseInt(ssData.slideshow.slides.slide[currentPhoto-1].count);
	
	// reload ads
	window.nymag.dcads.reloadAd("728x90","slideshow",true);
	window.nymag.dcads.reloadAd("300x250","slideshow",true);
}
function changeInfo(elem){
	var iDiv = $nymag_j("#right-textAndAd-col");
	var label_url;
	
	// Update Slide #
	$nymag_j("#page-number").html(ssData.slideshow.slides.slide[currentPhoto-1].count + " of " + ssData.slideshow.totalslides);
	
	// Update Source Text
	$nymag_j(".photo-credit",elem).html("Photo: " + ssData.slideshow.slides.slide[currentPhoto-1].source).fadeIn("slow");
	
	//Updating Label
	if(isRunwayLook)
		label_url = (typeof ssData.slideshow.slides.slide[currentPhoto-1].collection_url != "undefined") ? ssData.slideshow.slides.slide[currentPhoto-1].collection_url : "#"; 
	else
		label_url =  ssData.slideshow.slides.slide[currentPhoto-1].label_profile_url;
	if(label_url=="") label_url="#";
	$nymag_j("h3 a",iDiv).html(ssData.slideshow.slides.slide[currentPhoto-1].label).attr("href",label_url).attr("title","See More " + ssData.slideshow.slides.slide[currentPhoto-1].label);
	
	// Update Season
	if(typeof ssData.slideshow.slides.slide[currentPhoto-1].season != "undefined"){
		var collection_url = (typeof ssData.slideshow.slides.slide[currentPhoto-1].collection_url != "undefined") ? ssData.slideshow.slides.slide[currentPhoto-1].collection_url : "#"; 
		if(collection_url=="") collection_url="#";
		$nymag_j("#slideshow-dek .season",iDiv).html("<a href='" + collection_url + "'>" + ssData.slideshow.slides.slide[currentPhoto-1].season + "</a>");
	}
	else
		$nymag_j("#slideshow-dek .season",iDiv).html("");
		
	// Update Caption
	if(!isRunwayLook){
		if(typeof ssData.slideshow.slides.slide[currentPhoto-1].caption != "undefined")
			$nymag_j("#slideshow-dek .season",iDiv).html(ssData.slideshow.slides.slide[currentPhoto-1].caption);
		else
			$nymag_j("#slideshow-dek .season",iDiv).html("");
	}
	
	//Update Model
	if(ssData.slideshow.slides.slide[currentPhoto-1].model != "") {
		if(ssData.slideshow.type.toLowerCase() == "off runway look"){
			$nymag_j("#more-links-bottom",iDiv).html('Model: <a href=\"#\" onclick=\"$nymag_j(\'#slideshow-container\').jqmHide();return false;\" title="See More ' + ssData.slideshow.slides.slide[currentPhoto-1].model + '">' + ssData.slideshow.slides.slide[currentPhoto-1].model + "</a>");
		} else {
			var model_url = (typeof ssData.slideshow.slides.slide[currentPhoto-1].model_url != "undefined") ? ssData.slideshow.slides.slide[currentPhoto-1].model_url : "#"; 
			if(model_url=="") model_url="#";
			$nymag_j("#more-links-bottom",iDiv).html('Model: <a href="' + model_url + '" title="See More ' + ssData.slideshow.slides.slide[currentPhoto-1].model + '">' + ssData.slideshow.slides.slide[currentPhoto-1].model + "</a>");
		}
	} else
		$nymag_j("#more-links-bottom",iDiv).html("").attr("href","").attr("title","");
	
	// Update Collection
	if(ssData.slideshow.type.toLowerCase() != "collection"){
		if(typeof ssData.slideshow.slides.slide[currentPhoto-1].collection_url != "undefined")
			$nymag_j("#slideshow-dek .complete-collection",iDiv).html('<a href="' + ssData.slideshow.slides.slide[currentPhoto-1].collection_url + '">See the complete collection</a>');
		else
			$nymag_j("#slideshow-dek .complete-collection",iDiv).html("");
	}


	if(isRunwayLook){
		// Buid Save to Album Form & set html back to normal
		var form_string = '<form name="save_to_album" ' 
						+ 'action="' + window.nymag.domains.my + '/myfashion/savetheselooks">'
						+ '<input type="hidden" name="rm" value="add_img"/>'
						+ '<input type="hidden" name="collection" value="' 
						+ ssData.slideshow.slides.slide[currentPhoto-1].label + ' "/>' 
						+ '<input type="hidden" name="designer" value="' 
						+ ssData.slideshow.slides.slide[currentPhoto-1].label + '"/>'
						+ '<input type="hidden" name="designer_page" value="'
						+ ssData.slideshow.slides.slide[currentPhoto-1].label_profile_url + '" />'
						+ '<input type="hidden" name="img" value="' 
						+ ssData.slideshow.slides.slide[currentPhoto-1].path + '"/>'
						+ '</form>';
		$nymag_j("#save_to_album_form").html(form_string);
		$nymag_j("#runway-controls-right-top .savedlook").html("Save look");
		$nymag_j("#runway-controls-right-top .savedlook").attr("href","javascript:save_this_look();").removeClass("savedlook").addClass("savelook");
		
		// Check if we voted yet
		$nymag_j.post(
			"/urr/rtl.pl",
			{
				c_paging: "off",
				c_sort_bar: "off",
				context_name: "RTL",
				listing_type: "RTL",
				qc_caid: "qcComments",
				rm: "listings_page",
				top: 0,
				listing_id: ssData.slideshow.slides.slide[currentPhoto-1].path.replace("http://images.nymag.com","").replace("/images/","/slideshow.html?qc_sguid=images/")
			},
			function(data){
				// If they didn't vote put vote links up
				// If(else) they did vote put their vote w/ the percentage of people who agree
				if(data==""){
					$nymag_j("#runway-controls-left .uppercase").html("Rate this Look");
					$nymag_j("#runway-controls-left ul").css("background","transparent");
					$nymag_j("#runway-controls-left ul").html('<li class="hit"><a href="javascript:voteHidFab(10);">Hit</a></li><li class="miss"><a href="javascript:voteHidFab(0);">Miss</a></li>');
				} else {
					$nymag_j("#runway-controls-left .uppercase").html(parseInt(data) + "% agree it's a");
					$nymag_j("#runway-controls-left ul").css("background","#1a1a1a");
					if(parseInt(data.replace(/\d*, /,"")))
						$nymag_j("#runway-controls-left ul").html("<li class=\"vote-hit\"><a>Vote Hit</a></li>");
					else
						$nymag_j("#runway-controls-left ul").html("<li class=\"vote-miss\"><a>Vote Miss</a></li>");
				}
			},
			"text"
		);
	}
}

function voteHidFab(vote){
	var url = "/urr/rtl.pl";
	var sendData = {
		context_name: "RTL",
		rm: "save_new_review",
		qc_caid: "qcComments",
		listing_type: "RTL",
		listing_id: ssData.slideshow.slides.slide[currentPhoto-1].path.replace("http://images.nymag.com","").replace("/images/","/slideshow.html?qc_sguid=images/"),
		urr_ratings_category_id_342: vote
	};

	$nymag_j("#ajax-load-gfx").show();
	$nymag_j.post(
		url,
		sendData,
		function(data){
			var iDiv = $nymag_j("#runway-controls-left");
			$nymag_j("#ajax-load-gfx").hide();
			$nymag_j(".uppercase",iDiv).html(data + "% agree it's a");
			$nymag_j("ul",iDiv).css("background","#1a1a1a");
			if(vote)
				$nymag_j("ul",iDiv).html("<li class=\"vote-hit\"><a>Vote Hit</a></li>");
			else
				$nymag_j("ul",iDiv).html("<li class=\"vote-miss\"><a>Vote Miss</a></li>");
		}, 
		"text"
	);
}
	
function initCarousel(){
	isRunwayLook = (runwayLooks.search(ssData.slideshow.type.toLowerCase()) >= 0) ? true : false;
	$nymag_j("#slide-img-col").jCarouselLite({
		btnNext: "#slideshow-btns .next, #runway-next",
		btnPrev: "#slideshow-btns .prev, #runway-previous",
		visible: (isRunwayLook ? 1.7966 : 1),
		scroll: 1,
		circular: false,
		easing: "easeInSine",
		speed: 500,
		start: currentPhoto-1,
		beforeStart: interstitial,
		addOnScroll: scrollingAdd,
		afterEnd: updateData
	})
	
	parent.location.hash = "slide"+ ssData.slideshow.slides.slide[currentPhoto-1].count + "&ss" + (ssNum+1);
	slideshowStatCall(ssData.slideshow.type);
	
	//Update Next to Logo
	var rubricText = ssData.slideshow.type.toLowerCase();
	if(rubricText == "off runway look")
		rubricText = "Off the Runway";
	else if(rubricText == "runway look")
		rubricText = "Runway Looks";
	else if(rubricText == "party")
		rubricText = "Parties";
	else if(rubricText == "backstage")
		rubricText = "Front Row";
	else if(rubricText == "details")
		rubricText = "Details";
	else if(rubricText == "collection")
		rubricText = "Collections";
	$nymag_j("#header-container .slideshow-rubric").html(rubricText);
	
	//Update Title
	if(ssData.slideshow.type.toLowerCase() == "runway look") $nymag_j("#header-container h2").html("<a href=\"#\" onclick=\"$nymag_j('#slideshow-container').jqmHide();return false;\">Runway Search Result</a>");
	else if(ssData.slideshow.type.toLowerCase() == "off runway look") $nymag_j("#header-container h2").html(ssData.slideshow.slides.slide[0].model);
	else $nymag_j("#header-container h2").html(ssData.slideshow.collection);
	
	if(ssData.slideshow.type.toLowerCase() == "collection"){
		$nymag_j("#slideshow-dek .complete-collection").html("See the complete collection").attr("href",ssData.slideshow.collection_url);
	}

	if(ssData.slideshow.fullscreen != "") startFullscreen(ssData.slideshow.fullscreen);

	//Update Current Photo's Opacity
	//$nymag_j("#slide-img-col ul li:eq(" + (currentPhoto-1) + ")").children("img").animate({"opacity":"1","filter":"alpha(opacity=100)"});
	//if(isRunwayLook) $nymag_j("#slide-img-col ul li:eq(" + (currentPhoto-1) + ")").children("img").css("opacity","1").css("filter","alpha(opacity=100)");

	changeInfo($nymag_j("#slide-img-col ul li:eq(" + (currentPhoto-1) + ")"));
	if(isRunwayLook){
		if($nymag_j.browser.msie && $nymag_j.browser.version==6)
			$nymag_j("#slide-img-col ul").css("margin-left","135px");
		else
			$nymag_j("#slide-img-col ul").css("margin-left","144px");
	}
}

function buildCarousel(data){
	$nymag_j("#slide-img-col ul").html("");
	ssData=data;
	isRunwayLook = (runwayLooks.search(ssData.slideshow.type.toLowerCase()) >= 0) ? true : false;

	if(isRunwayLook) $nymag_j("#slideshow-content-container").removeClass().addClass("runway-look");
	else $nymag_j("#slideshow-content-container").removeClass().addClass(ssData.slideshow.type.replace(/ /g,"-"));
	
	for(var i=0; i<ssData.slideshow.slides.slide.length; i++){
		if( (i>=currentPhoto-3) && (i<=currentPhoto+1) )
			$nymag_j("#slide-img-col ul").append('<li><img src="' + ssData.slideshow.slides.slide[i].path + '" /><div class="photo-credit">Photo: ' + ssData.slideshow.slides.slide[i].credit + '</div></li>');
		else
			if(i==0) $nymag_j("#slide-img-col ul").append('<li><img src="' + ssData.slideshow.slides.slide[i].path + '" /><div class="photo-credit">Photo: ' + ssData.slideshow.slides.slide[i].credit + '</div></li>');
			else $nymag_j("#slide-img-col ul").append('<li><img src="" /><div class="photo-credit"></div></li>');
	}
	if (isRunwayLook)
		$nymag_j("#slide-img-col ul").append("<li></li>");

	if((currentPhoto>=14) && (ssData.slideshow.nextDataUrl != "0")){
		loadDir="next";
		$nymag_j("#ajax-load-gfx").show(); 
		$nymag_j.getJSON(ssData.slideshow.nextDataUrl, function(data){ $nymag_j("#ajax-load-gfx").hide();  buildCarouselSecondary(data); });
	} else if((currentPhoto==1) && (ssData.slideshow.previousDataUrl != "0")){
		loadDir="prev";
		$nymag_j("#ajax-load-gfx").show(); 
		$nymag_j.getJSON(ssData.slideshow.previousDataUrl, function(data){ $nymag_j("#ajax-load-gfx").hide(); buildCarouselSecondary(data); });
	} else {
		loading=false;
		initCarousel();
	}
	
	if($nymag_j("#thumbnails").height() == 610)
		$nymag_j("#slideshow-footer .thumbnails").click();
}

function buildCarouselSecondary(data){
	ssData.slideshow.slides.count = parseInt(ssData.slideshow.slides.count) + parseInt(data.slideshow.slides.count);
	if(loadDir=="next"){
		ssData.slideshow.nextDataUrl = data.slideshow.nextDataUrl;
		$nymag_j("#slide-img-col ul li:last").remove();
		
		for(var i=0; i<data.slideshow.slides.slide.length; i++){
			ssData.slideshow.slides.slide.push(data.slideshow.slides.slide[i]);
			if(i<=1)
				$nymag_j("#slide-img-col ul").append('<li><img src="' + data.slideshow.slides.slide[i].path + '" /><div class="photo-credit">Photo: ' + ssData.slideshow.slides.slide[i].credit + '</div></li>');
			else
				$nymag_j("#slide-img-col ul").append('<li><img src="" /><div class="photo-credit"></div></li>');
		}
		if (isRunwayLook)
			$nymag_j("#slide-img-col ul").append("<li></li>");
	} else {
		ssData.slideshow.previousDataUrl = data.slideshow.previousDataUrl;
		
		for(var i=data.slideshow.slides.slide.length-1; i>=0; i--){
			ssData.slideshow.slides.slide.unshift(data.slideshow.slides.slide[i]);
			if((i==0) || (i>=data.slideshow.slides.slide.length-1))
				$nymag_j("#slide-img-col ul").prepend('<li><img src="' + data.slideshow.slides.slide[i].path + '" /><div class="photo-credit">Photo: ' + ssData.slideshow.slides.slide[i].credit + '</div></li>');
			else
				$nymag_j("#slide-img-col ul").prepend('<li><img src="" /><div class="photo-credit"></div></li>');
			
		}
		currentPhoto += 15;
	}
	loading = false;
	loadDir="";
	initCarousel();
}

function loadNextDataSet(data){
	ssData.slideshow.currentDataUrl = data.slideshow.currentDataUrl;
	ssData.slideshow.slides.count = parseInt(ssData.slideshow.slides.count) + parseInt(data.slideshow.slides.count);

	if(carItem.dir=="next"){
		ssData.slideshow.nextDataUrl = data.slideshow.nextDataUrl;
		if (isRunwayLook)
			$nymag_j("#slide-img-col ul li:last").remove();
		for(var i=0; i<data.slideshow.slides.slide.length; i++){
			ssData.slideshow.slides.slide.push(data.slideshow.slides.slide[i]);
			if(i==0)
				carItem.addCall('<li><img src="' + data.slideshow.slides.slide[i].path + '" /><div class="photo-credit">Photo: ' + data.slideshow.slides.slide[i].credit + '</div></li>', carItem.dir);
			else
				carItem.addCall('<li><img src="" /></li>', carItem.dir);
		}
		if (isRunwayLook)
			carItem.addCall('<li><div class="photo-credit"></div></li>', carItem.dir);
		carItem.goCall(carItem.goNext);
	} else {
		ssData.slideshow.previousDataUrl = data.slideshow.previousDataUrl;
		for(var i=data.slideshow.slides.slide.length-1; i>=0; i--){
			ssData.slideshow.slides.slide.unshift(data.slideshow.slides.slide[i]);
			if(i==0)
				carItem.addCall('<li><img src="' + data.slideshow.slides.slide[i].path + '" /><div class="photo-credit">Photo: ' + data.slideshow.slides.slide[i].credit + '</div></li>', carItem.dir);
			else
				carItem.addCall('<li><img src="" /><div class="photo-credit"></div></li>', carItem.dir);
		}
		currentPhoto += 13;
		$nymag_j("#slide-img-col ul li:eq(" + (currentPhoto-1) + ") img").attr("src","" + ssData.slideshow.slides.slide[currentPhoto-1].path);
		carItem.goCall(currentPhoto);
	}
}

function buildThumbnails(data){
	var li_class = '';
	if(!dynamicData){
		thumbData = data;
		var count = isRunwayLook ? 29 : 20;
		var upper_limit = (thumbNum+count > thumbData.slideshow.slides.count) ? thumbData.slideshow.slides.count : thumbNum+count;
		for(var i=(thumbNum-1); i<upper_limit; i++){
			li_class = '';
			if(thumbData.slideshow.slides.slide[i].count == slideNum)
				li_class = 'active';
			$nymag_j("#thumbnails .thumb-wrp ul.thumbs").append('<li class="' + li_class + '"><a href="javascript:thumbToSlide(\'' + (i+1) + '\');"><img src="' + thumbData.slideshow.slides.slide[i].thumb + '" /></a></li>');
		}
		$nymag_j("#thumbnails .thumb-wrp ul.thumbs")
	} else if(loading){
		thumbData.slideshow.slides.count = parseInt(thumbData.slideshow.slides.count) + parseInt(data.slideshow.slides.count);
		thumbData.slideshow.nextDataUrl = data.slideshow.nextDataUrl;
		for(var i=0; i<data.slideshow.slides.slide.length; i++){
			thumbData.slideshow.slides.slide.push(data.slideshow.slides.slide[i]);
			li_class = '';
			if(data.slideshow.slides.slide[i].count == slideNum)
				li_class = 'active';
			$nymag_j("#thumbnails .thumb-wrp .thumbs").append('<li class="' + li_class + '"><a href="javascript:thumbToSlide(\'' + (i+16) + '\');"><img src="' + data.slideshow.slides.slide[i].thumb + '" /></a></li>');
		}
		loading = false;
		loadThumbs = false;
	} else {
		thumbData = data;
		for(var i=0; i<data.slideshow.slides.slide.length; i++){
			li_class = '';
			if(thumbData.slideshow.slides.slide[i].count == slideNum)
				li_class = 'active';
			$nymag_j("#thumbnails .thumb-wrp ul.thumbs").append('<li class="' + li_class + '"><a href="javascript:thumbToSlide(\'' + (i+1) + '\');"><img src="' + thumbData.slideshow.slides.slide[i].thumb + '" /></a></li>');
		}
		
		thumbNum+=15;
		if(thumbNum < parseInt(thumbData.slideshow.totalslides)){
			thumbUrl = thumbUrl.replace(/Nao=\d*/,"Nao=" + thumbNum);
			loading=true;
			$nymag_j("#ajax-load-gfx").show(); 
			$nymag_j.getJSON(thumbUrl, function(data){ $nymag_j("#ajax-load-gfx").hide(); buildThumbnails(data); });
		} else {
			loadThumbs = false;
		}
	}
}

function reloadSlideshow(data, num){
	ssData="";
	$nymag_j("#thumbnails .thumb-wrp ul.thumbs").html("");
	$nymag_j("#slideshow-btns .next, #runway-next, #slideshow-btns .prev, #runway-previous").unbind("click");
	$nymag_j("#slide-img-col ul").html("");
	currentPhoto=parseInt(num);
	slideNum=parseInt(data.slideshow.slides.slide[currentPhoto-1].count);
	parent.location.hash = "slide"+ slideNum + "&ss" + (ssNum+1);
	loading=true;
	buildCarousel(data);
}

function loadThumbnails(startNum){
	$nymag_j("#thumbnails .thumb-wrp ul.thumbs").html("");
	if(dynamicData){
		thumbNum = startNum;
		thumbUrl = ssData.slideshow.currentDataUrl.replace(/Nao=\d*/,"Nao=" + thumbNum);
		loadThumbs = true;
		$nymag_j("#ajax-load-gfx").show(); 
		$nymag_j.getJSON(thumbUrl, function(data){ $nymag_j("#ajax-load-gfx").hide(); buildThumbnails(data); });
	} else {
		thumbNum = startNum;
		loadThumbs = true;
		buildThumbnails(ssData);
	}
}

function thumbToSlide(num){
	reloadSlideshow(thumbData, num);
}

function closeThumbs(){
	$nymag_j("#thumbnails .thumb-wrp ul.thumbs").html("");
	$nymag_j("#thumbnails").animate({"height":"1px"},1000,"easeOutExpo", function callback(){ $nymag_j(this).hide(); });
}

function closeLoginPanel(){
	$nymag_j("#login-wrp").html("");
	$nymag_j("#login-wrp").animate({"height":"1px"},1000,"easeOutExpo", function callback(){ $nymag_j(this).hide(); });
	updateLoginMessage();
}

// Get Cookie -------------------------------------------------------
function get_cookie(name) {
    var search = name + "=";
    var returnvalue = "";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(search);
        // if cookie exists
        if (offset != -1) { 
            offset += search.length;
            // set index of beginning of value
            end = document.cookie.indexOf(";", offset);
            // set index of end of cookie value
            if (end == -1) end = document.cookie.length;
            returnvalue=unescape(document.cookie.substring(offset, end));
        }
    }

  return returnvalue;
}


// Check if User is logged In ---------------------------------------
function user_is_logged_in() {
    var session = get_cookie("nymag_session");
    var session_state = get_cookie("nymag_session_state");
    return (session && session_state) ? true : false; 
}

// Open Login Window ------------------------------------------------
function open_login_win(url) {
    qtwin = window.open(url,"login_win",'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=730,height=700');
    qtwin.focus();
}

// Save Look ---------------------------------------------------------
function save_this_look() {
    if ( user_is_logged_in() ) {
		$nymag_j("#ajax-load-gfx").show();
		$nymag_j.getJSON(window.nymag.domains.my + "/myfashion/savetheselooks?callback=?&rm=add_img&collection="+document.save_to_album.collection.value+"&designer="+document.save_to_album.designer.value+"&designer_page="+document.save_to_album.designer_page.value+"&img="+document.save_to_album.img.value);
	} 
    else {
		$nymag_j("#login-wrp").show().animate({"height":"595px"},1000,"easeOutExpo", function(){
			loadLogin("#login-wrp", save_this_look);
		});
    }
}

function save_look(data){
	$nymag_j("#ajax-load-gfx").hide();
	$nymag_j("#runway-controls-right-top .savelook").html("Saved");
	$nymag_j("#runway-controls-right-top .savelook").removeAttr("href").removeClass("savelook").addClass("savedlook");
}

// Goto Collection Homepage -------------------------------------------
function goto_collection_homepage( window ) {
    // get image path
    var cur_image_path = src[current_index];
    // replace anything after designer root
    cur_image_path = cur_image_path.replace(/(\/images\/)?[^\/]+jpg/,"");
    // replace http base with server base
    cur_image_path = cur_image_path.replace(/http:\/\/[^\/]+/,'');
    open_url( window, cur_image_path );
}

// Go to Top 100 -----------------------------------------------------
function get_top_100() {
    document.location.href = "/redirects/top100looks.html"; 
}

function startFullscreen(url, slide){
	$nymag_j.getScript("http://cache.nymag.com/scripts/swfobject.1.4.4.js", function(){
		var so = new SWFObject("/swf/fs_slideshow.swf", "fs_slideshow", "164", "33", "9", "#0c0c0c");
		so.addParam("allowFullScreen", "true");
		so.addParam("wmode", "opaque");
		so.addParam("allowScriptAccess","always");
		
		// Path to the XML data source
		so.addVariable("slideshow_xml_url", url);
		
		
		// DoubleClick Ad Tag
		so.addVariable("adTag",	fullScreen_slideshow_ad_tag);
		
		// DoubleClick ad holder SWF
		so.addVariable("doubleclick_ad_swf", "/swf/doubleclick_ad.swf");
		
		// DoubleClick ad refresh 0 = do not show ad / 1 = update ad every slide / 2 = update ad every 2 slides
		// / etc ...
		so.addVariable("doubleclick_ad_refresh", fullScreen_slideshow_refresh_freq);
		
		// Top 100 Link
		so.addVariable("top100", "http://nymag.com/search/search.cgi?t=fashion-hit&q=year:2009|short%20season:fall|collection%20type:rtw");
		
		
		// Omniture
		so.addVariable("omniture_channel", "Fashion Channel:Fashion Shows:The Show:Collection Slideshow:Full Screen Runway Slideshow");
		so.addVariable("omniture_evar3", "Fashion Channel:Fashion Shows:The Show:Collection Slideshow:Full Screen Runway Slideshow");
		so.addVariable("omniture_evar4", "Fashion Channel,Fashion Shows,The Show,Collection Slideshow,Full Screen Runway Slideshow");
		so.addVariable("omniture_prop6", "Fashion Channel,Fashion Shows,The Show,Collection Slideshow,Full Screen Runway Slideshow");
		so.addVariable("omniture_hier1", "Fashion Channel,Fashion Shows,The Show,Collection Slideshow,Full Screen Runway Slideshow");
		so.addVariable("omniture_prop2", "Fashion Slideshows");
		so.addVariable("omniture_prop3", "Full Screen Slideshows");
		
		// path to JPEG, SWF, GIF or PNG button for initial state of application
		// note: width and height defined above should be the width and height of this image
		so.addVariable("fs_button", "/gfx/sect/slideshows/fullscreen.gif");
		so.addVariable("fs_button_hi", "/gfx/sect/slideshows/fullscreen_hover.gif");
		
		// current photo to display when fullscreen view opens (optional)
		so.addVariable("photo", 1);
		
		so.write("fullscreen");	
	});
}

function buildThumbNav(currSlide, numPanels){
	var prevHellip, nextHellip, lowerbound, upperbound;
	if(numPanels <= 9){
		prevHellip = false;
		nextHellip = false;
		lowerbound = 2;
		upperbound = numPanels-1;
	} else {
		prevHellip = false;
		lowerbound = 2;
		if(currSlide > 5){
			lowerbound = currSlide-3;
			prevHellip=true;
		}
		nextHellip = true;
		upperbound = lowerbound+6;
		if(upperbound > numPanels-4){
			upperbound = numPanels-1;
			nextHellip = false;
		}
	}
	
	$nymag_j("#thumbnails .thumb-wrp .pagination ul li").removeClass("current");
	$nymag_j("#thumbnails .thumb-wrp .pagination ul li.prev a, #thumbnails .thumb-wrp .pagination ul li.next a").removeClass("nolink");
	
	//prevHellip
	if(prevHellip) $nymag_j("#thumbnails .thumb-wrp .pagination ul li:eq(2)").show();
	else $nymag_j("#thumbnails .thumb-wrp .pagination ul li:eq(2)").hide();
	
	//nextHellip
	if(nextHellip) $nymag_j("#thumbnails .thumb-wrp .pagination ul li:eq(10)").show();
	else $nymag_j("#thumbnails .thumb-wrp .pagination ul li:eq(10)").hide();
	
	//Last Panel
	if(numPanels>1)
		$nymag_j("#thumbnails .thumb-wrp .pagination ul li:eq(11) a").show().html(numPanels);
	else
		$nymag_j("#thumbnails .thumb-wrp .pagination ul li:eq(11) a").hide();
		
	for(var i=3; i<=9; i++){
		if(lowerbound<numPanels){
			var li_class = (lowerbound==currSlide) ? "current" : "";
			$nymag_j("#thumbnails .thumb-wrp .pagination ul li:eq(" + i + ")").show().addClass(li_class).children(0).html(lowerbound);
		} else {
			$nymag_j("#thumbnails .thumb-wrp .pagination ul li:eq(" + i + ")").hide();
		}
		lowerbound += 1;
	}
	
	if(currSlide==1){
		$nymag_j("#thumbnails .thumb-wrp .pagination ul li.first").addClass("current");
		$nymag_j("#thumbnails .thumb-wrp .pagination ul li.prev a").addClass("nolink");
	}
	if(currSlide==numPanels) {
		$nymag_j("#thumbnails .thumb-wrp .pagination ul li.last").addClass("current");
		$nymag_j("#thumbnails .thumb-wrp .pagination ul li.next a").addClass("nolink");
	}
}

$nymag_j("#thumbnails .thumb-wrp .pagination ul li a").click(function(){
	var nextPanel;
	var currItem = $nymag_j(this);
	if(currItem.html()=="next"){
		if(currItem.hasClass("nolink")) return false;
		nextPanel = parseInt(currItem.parents(1).find("li.current a").html())+1;
	} else if(currItem.html()=="prev"){
		if(currItem.hasClass("nolink")) return false;
		nextPanel = parseInt(currItem.parents(1).find("li.current a").html())-1;
	} else if(currItem.html()=="..."){
		return false;
	} else {
		if(currItem.parent().hasClass("current"))	return false;
		nextPanel = parseInt(currItem.html());
	}

	buildThumbNav(nextPanel,Math.ceil(ssData.slideshow.totalslides/(isRunwayLook ? 30 : 21)));
	
	loadThumbnails((nextPanel-1)*(isRunwayLook ? 30 : 21)+1);
	
	return false;
});

$nymag_j(document).ready(function(){
	if($nymag_j.browser.msie){
		$nymag_j("#slideshow-container").insertBefore("#wrap");
		$nymag_j("#content-primary-wrap #slideshow-container").remove();
	}
	//Check if slideNum is in the hash
	
	$nymag_j("#slideshow-btns .play").bind("click",function(){
		auto_play = setInterval(function(){$nymag_j("#slideshow-btns .next").click()}, 4000);
		$nymag_j(this).hide();
		$nymag_j(this).next().show();

		return false;
	});
	$nymag_j("#slideshow-btns .stop").bind("click",function(){
		clearInterval(auto_play);
		$nymag_j(this).hide();
		$nymag_j(this).prev().show();
		
		return false;
	});
	
	$nymag_j("#slideshow-footer .thumbnails").bind("click",function(){

		if($nymag_j("#thumbnails").height() == 610){
			$nymag_j("#thumbnails").animate({"height":"1px"},1000,"easeOutExpo", function callback(){ $nymag_j(this).hide(); });
		} else {
			$nymag_j("#thumbnails").show().animate({"height":"610px"},1000,"easeOutExpo", function(){
				$nymag_j("#slideshow-btns .stop").click();
				var count = isRunwayLook ? 30 : 21;
				var num_panels = Math.ceil(ssData.slideshow.totalslides/count);
				var curr_slide = Math.floor((slideNum-1)/count+1);
				
				buildThumbNav(curr_slide,num_panels);

				var tempPhoto = slideNum%count;
				if(tempPhoto==0) tempPhoto=count;
				loadThumbnails(slideNum-tempPhoto+1);
			});				
		}
		return false;
	});
	
	var autoStart = location.hash.match(/slide([\d]*)(&ss([\d])*)*/);
	if(autoStart){
		ssNum = (autoStart[2]) ? parseInt(autoStart[3])-1 : 0;
		slideNum = autoStart[1];

		startSlideshow(ssNum,slideNum);
	}
});


//Stat Call Data
function slideshowStatCall(section){
	var heirarchy="";
	var title="";
	
	if(section == "off runway look"){
		title = "Model Off the Runway Slideshow";
		heirarchy="Fashion Channel:Models:Model Topic:Model Slideshows:Off the Runway";
	} else if(section == "runway look") {
		title = "Runway Look Search Slideshow";
		heirarchy="Fashion Channel:Fashion Shows:Looks:Looks Search & Slideshows:Looks Slideshow";
		if(window.location.href.search("search.cgi") < 0){
			title = "Model On the Runway Slideshow";
			heirarchy="Fashion Channel:Models:Model Topic:Model Slideshows:On the Runway";
		} else if(window.location.href.search("t=fashion-hit") >= 0){
			title = "Runway Rankings: Hits Slideshow";
			heirarchy="Fashion Channel:Fashion Shows:Looks:Runway Rankings:Hits";
		} else if(window.location.href.search("t=fashion-miss") >= 0) {
			title = "Runway Rankings: Misses Slideshow";
			heirarchy="Fashion Channel:Fashion Shows:Looks:Runway Rankings:Misses";
		}
	} else if(section == "runway hits") {
		title = "Runway Rankings: Hits Slideshow";
		heirarchy="Fashion Channel:Fashion Shows:Looks:Runway Rankings:Hits";
	} else if(section == "runway misses") {
		title = "Runway Rankings: Misses Slideshow";
		heirarchy="Fashion Channel:Fashion Shows:Looks:Runway Rankings:Misses";
	} else if(section == "collection") {
		title = "Runway Collection Slideshow";
		heirarchy="Fashion Channel:Fashion Shows:The Show:Collection Slideshow:Runway Slideshow";
	} else if(section == "details") {
		title = "Details Slideshow";
		heirarchy="Fashion Channel:Fashion Shows:The Show:Collection Slideshow:Details Slideshow";
	} else if(section == "party") {
		title = "Party Slideshow";
		heirarchy="Fashion Channel:Fashion Shows:The Show:Parties:Party Slideshow";
	} else if(section == "backstage") {
		title = "Front Row/Backstage Slideshow";
		heirarchy="Fashion Channel:Fashion Shows:The Show:Front Row & Backstage:Front Row Slideshow";
	} else if(section == "runway beauty") {
		title = "Runway Beauty Slideshow";
		heirarchy="Fashion Channel:Fashion Shows:The Show:Front Row & Backstage:Runway Beauty Slideshow";
	} else if(section == "industry player") {
		title = "Industry Player Profile: Slideshow";
		heirarchy="Fashion Channel:Industry Players:Industry Player Topic:People Slideshows";
	}
	var url = window.location.href;
	if(url.match(/#slide[\d*]/)){
		url = url.replace(/slide[\d*]/,"");
		if(url.search(/ss[\d*]/) < 0) url += "ss1";
		else url = url.replace(/&ss/,"ss");
	}
		
	nymag_setMetadata({'content.hierarchy' : heirarchy});
	nymag_setMetadata({'content.hierarchy.title' : title});
	nymag_setMetadata({'content.type' : 'Fashion Slideshows'});
	nymag_setMetadata({'content.subtype' : 'Slideshow'});
	nymag_setMetadata({'content.pagename' : url});
	nymag_pageView();
}
