var isDebug = false;

/*-------------------------------------------*\
                 DYNAMIC LEADS
\*-------------------------------------------*/
var currentTab=1;		//Keeps track of the current tab for rotating.
var dlRotate;			//Stores the interval for tab switching so it can be stopped.
var dlRunning = false;	//Keeps track of whether or not the auto scroll is running.
var dlNumTabs;			//Counts the number of tabs once the DOM is ready.
var firstLoad = true;	//Modifies the Toggle function on the first page load.
var dlIsFade = false	//Checks if a fading tranistion is required.
var dlIsTabs = false	//Checks if tab switch is required.
var dlIsCount = false	//Checks if a counter needs to be displayed.
var dlFade = false;	//Keeps track of fading well it is occuring.
var dlFadeTime = 200;
if(readCookie("dlTime") != null)
	var dlTime = (readCookie("dlTime") * 1000) + (dlFadeTime * 2); //Keeps track of the flipping interval
else
	var dlTime = 7000 + (dlFadeTime * 2); //Keeps track of the flipping interval

function dlToggle() { //Starts/stops the auto switching
	if(dlRunning) {
		clearInterval(dlRotate);
		dlRunning = false;
		$(".rotateNav a.pause").removeClass("pause").addClass("play");
	} else {
		(firstLoad && dlIsTabs)?firstLoad=false:dlCycle("next");
		dlRotate = setInterval('dlCycle("'+'next'+'")', dlTime);
		dlRunning = true;
		if(!dlIsTabs) refreshAd("#bigbox","bigbox"); //If this is a gallery and not DL tabs refresh the ads when the user hits play.
		$(".rotateNav a.play").removeClass("play").addClass("pause");
	}
}

function dlCycle(direction) { //Goes to next or previous tab
	if(direction == "next") {
		dlSwitch(currentTab>=dlNumTabs?1:currentTab+1);
	} else {
		dlSwitch(currentTab==1?dlNumTabs:currentTab-1);
	}
}

function dlSwitch(tabNum) { //Goes to the requested tab
	
	if(dlIsCount) $(".rotateCount span").html(tabNum);
	function dlTabSwitch() {
		
		//omniture tracking
		if(!dlIsTabs && !dlRunning) {
			slideViewAutoPlay(MyOmnitureVariables.articlename,MyOmnitureVariables.articlename+" (Pic#="+tabNum+")");
			//if(isDebug) console.log(MyOmnitureVariables.articlename+" (Pic#="+tabNum+")");
		} else if(!dlIsTabs && dlRunning) {
			slideViewAutoPlay(MyOmnitureVariables.articlename+"-auto",MyOmnitureVariables.articlename+"-auto (Pic#="+tabNum+")");
			//if(isDebug) console.log(MyOmnitureVariables.articlename+"-auto (Pic#="+tabNum+")");
		}
		if(dlIsTabs) {
			$("#dl .tabs .active").removeClass("active");
			$("#dl .tabs li").eq(tabNum-1).addClass("active");
		}
	}
	
	if(dlIsFade) {
		if(!dlFade) {
			dlTabSwitch();
			dlFade = true;
			$(".rotateItem").eq(currentTab-1).fadeOut(dlFadeTime,function(){
				$(".rotateItem").eq(tabNum-1).fadeIn(dlFadeTime,function(){dlFade = false;});
			});
			currentTab=parseInt(tabNum);
		}
	} else {
		dlTabSwitch();
		$(".rotateItem").eq(currentTab-1).hide();
		$(".rotateItem").eq(tabNum-1).show();
		currentTab=parseInt(tabNum);
	}

}

var isCTRL = false;
var isFocus = false;
function arrowSwitch(Event) {
	if(Event==null) Event=event; //IE doesn't pass the event!
	if(Event.keyCode == 37 && isCTRL) { //left 37
		if(dlRunning) dlToggle();
		dlCycle("previous");
	} else if(Event.keyCode == 39 && isCTRL) { //right 39
		if(dlRunning) dlToggle();
		dlCycle("next");
	} else if(Event.keyCode == 17) {
		isCTRL = true;
	}
	
	if(Event.keyCode == 9 && !isFocus) { //outlines are turned off for firefox until the user hits tab
		$("a").addClass("withFocus");
		isFocus = true;
	}
	
}

function arrowCancel(Event) {
	if(Event==null) Event=event; //IE doesn't pass the event!
	if(Event.keyCode == 17) {
		isCTRL = false;
	}	
}

function dlTimeChange(newTime) {
	dlTime = (newTime * 1000) + (dlFadeTime * 2);
	if(dlRunning) {
		dlToggle();
		$(".rotateNav a.play").removeClass("play").addClass("pause"); //toggle removes this class, but since we aren't really toggling lets put it back.
		setTimeout("dlToggle()",dlTime);
	}
	createCookie("dlTime",newTime,1000);
}

function dlSlideCookie() { //Changes the default slider value for the DLs if a cookie is set
	if(readCookie("dlTime") != null) {
		var current = $("ul.dlTimeChange li.default");
		$("ul.dlTimeChange li").filter(function(index) {
			return parseInt($(this).html()) == parseInt(readCookie("dlTime"));
		}).addClass("default");
		if($("ul.dlTimeChange li.default").size() == 2) { //Checks to see if a new default was found, if not nothing changes.
			current.removeClass("default");
			return true;
		} else {
			return false;	
		}
	} else {
		return false;	
	}
}

/*-------------------------------------------*\
                 TAB SWITCH
\*-------------------------------------------*/
var tabFade = false;	//Keeps track of fading well it is occuring.
function tabSwitch(linkElement) { //Goes to the requested tab
	var tabContainer = linkElement.parents(".tabsContainer").eq(0);
	var oldTab = tabContainer.children(".active").eq(0);
	var newTab = $(linkElement.attr("href"));
	if(!tabFade && !oldTab.is(linkElement.attr("href"))) {
		tabFade = true;
		switchActiveTab(linkElement);
		oldTab.fadeOut(200,function(){
			newTab.fadeIn(200,function(){
				oldTab.removeClass("active");
				newTab.addClass("active");
				tabFade = false;
			});
		});
	}
}

function switchActiveTab(linkElement) { //Applys the class of active to whatever link element is passed and removes it from all its siblings
	var currentLI = linkElement.parent();
	currentLI.siblings().removeClass("active");
	currentLI.addClass("active");
}

/*-------------------------------------------*\
                 WEATHER
\*-------------------------------------------*/
function bindChooseCity() {
	$("#chooseCity").bind("click", function(){ //Choose city for weather
		overlay("/html/weather.html",397);
		return false;
	});
}

function populateCity(prov) {
	var city = document.getElementById("city");
	var allCities;
	if(prov != "NULL") {
		allCities = '<option value="NULL" id="selectCity">Select your city/town</option>';
		city.disabled = false;
		for(i=0;i<cities[prov].length;i++) {
			allCities = allCities+'<option value="'+cities[prov][i].toLowerCase()+'">'+cities[prov][i]+'</option>';
		}
		$(city).html(allCities);
		$("#selectCity").attr("selected","selected");		
	} else {
		city.disabled = true;
		$(city).html('<option value="NULL" selected="selected">Select your city/town</option>');
	}
}

function submitWeather(form) {
	if(form.province.value != "NULL" && form.city.value != "NULL") {
		eraseCookie("weatherfile");
		createCookie("weatherfile",form.country.value+"_"+form.province.value.toLowerCase()+"_"+form.city.value.toLowerCase().replace(/ /g,"")+".html",1000);
		$("#weatherAjax").empty();
		closeOverlay();
		$.get("/library/weather.php?"+ajaxNoCache(), function(data){
			$("#weatherAjax").html(data);
			bindChooseCity();
		});
	} else {
		alert("Please fill out the form before submitting");	
	}
}

/*-------------------------------------------*\
                 OVERLAY
\*-------------------------------------------*/
function overlay(fileName,width) {
	$.get(fileName, function(data){
		var htmlStart = '<div id="overlayFade"></div><div id="overlay">';
		var htmlFinish = '</div>';
		$("body").append(htmlStart+data+htmlFinish);
		var overlayDiv = $("#overlay");
		$("#overlayFade").css("height",$("body").height()+"px");
		positionOverlay(width,$("#overlay").height());
		overlayDiv.css("width", width+"px");
		overlayDiv.fadeIn(600);
		$("#popHead a").bind("click", function(){
			closeOverlay();
			return false;
		});
		$("#overlayFade").bind("click", function(){closeOverlay();});

	});
}

function closeOverlay() {
	$("#overlay").fadeOut(600, function() {
		$("#overlayFade").remove();
		$("#overlay").remove();
	});
}

function positionOverlay(width,height) { //Slight modification of a function from thickbox http://jquery.com/demo/thickbox/
	$("#overlay").css({marginLeft: '-' + parseInt((width / 2),10) + 'px', width: width + 'px'});
		if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
			$("#overlay").css({marginTop: '-' + parseInt((height / 2),10) + 'px'});
	}
}

/*-------------------------------------------*\
                 COOKIES
\*-------------------------------------------*/
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/*-------------------------------------------*\
                 DROP DOWN
\*-------------------------------------------*/
function dropDown(dropdown) {
	$("#"+dropdown).toggle();
	if($("#"+dropdown).css("display") == "none") {
		$("html").unbind();
	} else {
		$("html").bind("click", function(){
		  dropDown(dropdown);
		});	
	}
}

/*-------------------------------------------*\
            STORY LIST HOVER STATES
\*-------------------------------------------*/
function bindStoryClick(which) {
	which.click(function() { 
		window.location = ($(this).children("h4").children("a").eq(0).attr("href"));
	});
}

function bindStoryHover(which) {
	which.hover(function(){
		$(this).addClass("storyHover");
		bindStoryClick($(this));
	},function(){
		$(this).removeClass("storyHover");
	});
}

function unbindStoryHover(which) {
	which.unbind();
}


/*-------------------------------------------*\
                 SLIDE BAR
\*-------------------------------------------*/
function bindSlider() {
	$(".slider .marker").each(function(i){
			var thisthis = $(this);
			var centerMarker = thisthis.filter(".centerMarker").size();				
			var markerWidth = thisthis.width();				
			var thisli = $(thisthis.parents(".sliderContainer").children("ul").children("li"));
			var whichli = thisli.index($(thisli.parent().children(".default"))[0]);
			var liSize = thisli.size();
			var negativeMargin = -1*markerWidth/2;
			var parent = thisthis.parents(".slider").eq(0);
			var slideWidth = parent.width();
			var displayX = Math.round(slideWidth/(liSize-1)*whichli);
			var sepX;
			var lr;
			var sepMargin = 0; var tempMargin = 0;
			parent.siblings(".slideValue").eq(0).children("span").html(thisli.filter(".default").eq(0).html());
			for(i=0;i<liSize;i++) {
				sepX = Math.round(slideWidth/(liSize-1)*i)
				if(i==1)
					tempMargin = sepMargin = parent.children(".seperator").eq(0).width()/-2;
				if((i+1)==liSize){
					lr="right";
					tempMargin = sepX = 0;
				} else {
					lr="left";
				}
				parent.append('<div class="seperator" style="'+lr+':'+sepX+'px;margin-left:'+tempMargin+'px"></div>');
			}
			if(centerMarker) {
				if(whichli==0)
					displayX = displayX - sepMargin;
				else if((whichli+1)==liSize)
					displayX = displayX + sepMargin;
			} else {
				if(whichli==0)
					displayX = displayX - negativeMargin;
				else if((whichli+1)==liSize)
					displayX = slideWidth - markerWidth - negativeMargin;
			}
			thisthis.css({"left":displayX+"px","margin-left":negativeMargin+"px"});
	}).bind("mousedown", function(){
		var markers = new Array();
		$(this).parents(".sliderContainer").children("ul").children("li").each(function(i){
			markers[i] = $(this).html();
		});
		slider(this,markers);
		return false;
	}).show();
}

function slider(object,markers) {
	if($.browser.msie) document.onselectstart = function() {return false;}; //This stops IE from selecting text while sliding the bar
	
	var howMany = markers.length;
	
	var snapX; //keeps track of which marker to snap to
	var innerX; //keeps track of the marker position when dragging
	
	object = $(object); //marker DOM object
	var centerMarker = object.filter(".centerMarker").size();
	var markerWidth = object.width();
	var negativeMargin = Math.round(-1*markerWidth/2); //Used for centering the bullet
	var parent = object.parents(".slider").eq(0); //Marker container DOM object
	var slideWidth = parent.width();
	var sepMargin = Math.round(parent.children(".seperator").eq(0).width()/-2);
	if(centerMarker) {
		var end = slideWidth + sepMargin;
		var negativeMargin = sepMargin;
	} else {
		var end = slideWidth - markerWidth - negativeMargin;
	}
	var slideStart = parent.offset().left; //Where on the page the container is located to adjust absolute positioning
	var ul = parent.siblings("ul").eq(0);
	var internalMarkers = Math.round(slideWidth/(howMany-1));
	var prevSnapX = -10; //Used to see if the number to be displayed is different from the previous
	$("body").css("cursor","default").mousemove(function(event) {
		innerX = event.pageX - slideStart;
		if(innerX < (0-negativeMargin))
			innerX = 0-negativeMargin;
		else if(innerX > end)
			innerX = end;
		snapX = internalMarkers * Math.round(innerX/internalMarkers);
		if(snapX != prevSnapX && innerX >= 0 && innerX <= end) {
			ul.children("li.default").removeClass("default");
			ul.children().eq(snapX/internalMarkers).addClass("default");
			parent.siblings(".slideValue").eq(0).children("span").html(ul.children().eq(snapX/internalMarkers).html());
			prevSnapX = snapX;
		}
		object.css({left:(innerX)+"px"});
	}).bind("mouseup", function(){
		if($.browser.msie) document.onselectstart = null;
		var displayX = snapX;
		if(snapX == 0)
			displayX = 0-negativeMargin;
		else if(snapX >= (slideWidth-(internalMarkers/2)))
			displayX = end;
		//object.css("left",displayX+"px");
		object.animate({left:displayX+"px"},800);
		$("body").css("cursor","auto").unbind();
		var endFunction = ul.attr("class");
		eval(endFunction + '('+ul.children(".default").html()+')');
	});
}

/*-------------------------------------------*\
                 TEXT RESIZE
\*-------------------------------------------*/
function sizeText(whichLink,className) {
	var whichLinkClass = "a."+(whichLink.attr("class")).substring(0,3);
	$("#content").removeClass("sml").removeClass("med").removeClass("lrg").addClass(className);
	$(".articleControls a").removeClass("active");
	$(whichLinkClass).addClass("active");
	createCookie("textSize",className,1000);
	fixIE6Head();
	return true;
}

function highlightSize() {
	var textSize = readCookie("textSize");
	if(textSize == null || !(textSize == "sml" || textSize == "med" || textSize == "lrg"))
		textSize = "sml";
	$("."+textSize).addClass("active");
}

/*-------------------------------------------*\
                 CONTENT SWAP
\*-------------------------------------------*/
var baseUrl = window.location.href.replace(/^(.*?)[#](.*?)$/i,"$1");
var ajaxUrl = ajaxPath(window.location.href);
var urlChange = false;

//Starts checking for url changes to fake back buttons
function urlChangeJob() {
	urlChange = setInterval("newUrl()", 1000);
}

function contentSwap(linkElement,div,noHash) {
	//noHash is set to true if the user hits the back button to a url without a hash
	noHash = typeof(noHash) != 'undefined' ? noHash : false; //default value
	var isFirstLoad = firstPageLoad; //if its the first page load don't refresh the ad unit.
	var isTab = (linkElement.parents(".tabs").size()>0);
	if(urlChange)
		clearInterval(urlChange);
	//$("#fakeBack").attr("name",linkElement.attr("href").substring(1));
	var url = linkElement.attr("href").substring(1);
	currentUrl = (!noHash?"#"+url:"");
	//If its not a content swap tab we need to see which tab should be active after the swap
	if(linkElement.parents("ul.contentSwap").size()==0)
		linkElement = $("ul.tabs.contentSwap li").children('a[@href$="'+linkElement.attr("href")+'"]');
	switchActiveTab(linkElement);
	$(div).load(url+"?"+ajaxNoCache(),function() {
		if(!isTab) { //if we aren't switching content with a tab lets scroll up to where the content is!
			$('html,body').animate({scrollTop: $("#content").offset().top}, 1000);
		}
		resestContentSwap(div);
		pageInit();
		urlChangeJob();
		if(!isFirstLoad) {
			refreshAd("#bigbox","bigbox");
			refreshAd("#skyscraper","skyscraper");
			var storyHeadline = $(".articleHead h3").eq(0).html();
			if(!storyHeadline) storyHeadline =  $(".breadCrumb h2 a").eq(0).html();
			ButtonClick(linkElement.children("strong").html()+"-"+storyHeadline);
			//if(isDebug) console.log(linkElement.children("strong").html()+"-"+storyHeadline);
		}
	}).html('<div class="ajaxLoader">Loading</div>');
	return false;
}

function resestContentSwap(div) {
	$(div).css({display:"block"});
	$("#channelContent").css({paddingTop:"8px"});
}

function loadHash(linkElement) { //loads the content after the hash mark.
	var noHash;	
	if(typeof(linkElement) != 'undefined') {
		linkElement	= linkElement;
		noHash = true;
	} else {
		linkElement = $('.tabs.contentSwap a[@href$="'+document.location.hash.substring(1)+'"]')
		noHash = false;
	}
	
	if(linkElement.size() != 0) {
		contentSwap(linkElement,"#contentSwap",noHash);
	} else {
		resestContentSwap("#contentSwap");
	}
}

function ajaxPath(href) {
	var urlPieces = parseUrl(href); //holds the url pieces.
	urlPieces.file = urlPieces.file.replace(/(\d+)(.*?)(\.html)/i,"$1$3");
	return urlPieces.path+"pf-"+urlPieces.file;
}

var currentUrl = document.location.hash;
function newUrl() {
	if(document.location.hash != currentUrl) {
		currentUrl = document.location.hash;
		if(!document.location.hash.substring(1))
			loadHash($('.tabs.contentSwap a[@href$="'+ajaxUrl+'"]'),true);
		else
			loadHash();
	}
}

var isHash = false; //true when there is a hash in the url on page load.
if(document.location.hash.substring(1) && (ajaxUrl != document.location.hash.substring(1))) {
	isHash = true;
	$("head").append('<style type="text/css">#contentSwap { display:none; } #channelContent { padding-top:700px; }</style>'); //makes room for the content about to be loaded through ajax
	if ($.browser.safari){ $("head").find("style:last").append(" ") } //work around for safari ignoring the above line.
}

//This function is used to put a unique number at the end of each ajax call to prevent ie from caching it.
function ajaxNoCache() {
	var rand = Math.floor(Math.random()*8999999999)+1000000000;
	return "&ajaxcache="+rand;
}

/*-------------------------------------------*\
                 AJAX SCROLL
\*-------------------------------------------*/
var ajaxScrollRunning = false;
function ajaxScroll(direction,container) {
	var getHowMany = 10 //How many new elements are retrieved with each ajax call
	var scrollHowMany = 5;
	
	if(((direction == "next" && container.children(".next.disabledn").size() == 0) || (direction == "prev" && container.children(".prev.disabledp").size() == 0)) && !ajaxScrollRunning) {
		ajaxScrollRunning = true;
		if(direction == "next") {
			var directionN = -1;
			var oppDirection = "prev";
		} else {
			var directionN = 1;
			var oppDirection = "next";
		}
		
		var nextBtn = container.children(".next");
		var vals = nextBtn.attr("rel").split(",");
		vals[0] = parseInt(vals[0]); //How many are to the right that have not been displayed.
		vals[1] = parseInt(vals[1]); //The position of the last item being shown.
		vals[2] = parseInt(vals[2]); //The total number of items.
		vals[3] = vals[3]; //The section
		var thisUL = container.children(".scrollingInner").children("ul");
		var thisLI = thisUL.children("li");
		var thisLIRightMargin = parseInt(thisLI.css("margin-right").replace("px",""));
		var scrollBoxWidth = thisLI.width() + thisLIRightMargin;
		var currentLocation = thisUL.css("left").replace("px","");
		var whereToMove = parseInt(currentLocation) + (parseInt(directionN*scrollBoxWidth)*scrollHowMany);
		var totalWidth = container.children(".scrollingInner").width();
		var howManyFit = Math.floor((totalWidth+thisLIRightMargin)/scrollBoxWidth);

		if(direction == "next") {
			vals[1] = vals[1] + scrollHowMany;
			vals[0] = vals[0] - scrollHowMany;
			if(vals[0] < 5) {
				if(vals[0]+vals[1]!=vals[2]) {
					ajaxScrollGet(direction,thisUL,"/photos/data/pf-home.html",vals[1]+vals[0]+1,getHowMany,vals[3]);
					var currentULWidth = parseInt(thisUL.css("width").replace("px",""));
					var newULWidth = currentULWidth + (getHowMany*scrollBoxWidth);
					thisUL.css("width",newULWidth+"px");
					vals[0] = vals[0] + getHowMany;
				}
			}
		} else {
			vals[0] = vals[0] + scrollHowMany;
			vals[1] = vals[1] - scrollHowMany;
		}

		if(whereToMove < 0)
			container.children(".prev.disabledp").toggleClass("disabledp");
		else
			container.children(".prev").toggleClass("disabledp");
		
		if(vals[1] < vals[2])
			container.children(".next.disabledn").toggleClass("disabledn");
		else
			container.children(".next").toggleClass("disabledn");

		nextBtn.attr("rel",vals[0]+","+vals[1]+","+vals[2]+","+vals[3]);
		//console.log(vals[0]," ",vals[1]," ",vals[2]);
		thisUL.animate({left: whereToMove},1000,function(){
			refreshAd("#skyscraper","skyscraper")
			ajaxScrollRunning = false;
		});

	}


}

function ajaxScrollGet(direction,thisUL,url,start,howMany,section) {
	$.ajax({
		type: "GET",
		url: url+"?sect="+section+"&start="+start+"&howmany="+howMany+ajaxNoCache(),
		dataType: "html",
		success: function(data) {
			if(direction=="next")
				thisUL.append(data);
			else
				thisUL.prepend(data);
		}
	});
}

/*-------------------------------------------*\
		          AD REFRESH
\*-------------------------------------------*/

//replaces the random number at the end of the ad tag
function randomOrd(url,exclude) {
	exclude = typeof(exclude) != 'undefined' ? exclude : false; //default value
	if(exclude)
		url = url.replace(/(.*?);ord=(.*?)/,"$1;!exclusion="+exclude+";ord=$2");	
	var rand = Math.floor(Math.random()*8999999999)+1000000000;
	return url.replace(/(.*?)ord=(.*?)(\?|\;)(.*)/,"$1ord="+rand+"$3$4");
}

function refreshAd(div,type) {
	var whichDiv = $(div);
	var refreshAdTag = whichDiv.children("script").eq(1).attr("src");
	if(refreshAdTag) {
		whichDiv.html('<iframe src="/html/adrefresh-iframe.html?url='+randomOrd(refreshAdTag,"expandable")+'" frameborder="0" scrolling="no" id="'+div.substring(1)+'_iframe" class="iframe_'+type+'"><\/iframe>');
	} else {
		var adFrame = document.getElementById(div.substring(1)+'_iframe');
		var frameSrc = randomOrd(adFrame.src);
		whichDiv.children("iframe").remove();
		whichDiv.html('<iframe src="'+frameSrc+'" frameborder="0" scrolling="no" allowtransparency="true" id="'+div.substring(1)+'_iframe" class="iframe_'+type+'"><\/iframe>');
	}

}

/*-------------------------------------------*\
          SUNSHINE GIRL CALENDAR
\*-------------------------------------------*/

function bindSunshine() {
	activeGirl();
	$("#previousSunshineGirls .miniNav a").unbind("click").bind("click", function(){ 
		var toReplace = $("#previousSunshineGirls .inner");
		var isCalendar = $(this).html()!="Last 7 Days";
		if(isCalendar)
			$("#previousSunshineGirls").addClass("sunshineCalendarBox");
		else
			$("#previousSunshineGirls").removeClass("sunshineCalendarBox");
		toReplace.html('<div class="ajaxLoader">Loading</div>');
		$.get($(this).attr("href")+"?"+ajaxNoCache(), function(data){
			toReplace.html(data);
			if($.browser.msie) $(".redlineFade").css("bottom","-1px"); //This is the exact same as the style set in the stylesheet. IE6 just refuses to apply it after the ajax content is loaded
			bindSunshine();
			refreshAd("#skyscraper","skyscraper");
		});
		return false;
	});
}

function activeGirl() {
	var urlPieces = parseUrl(window.location.pathname);
	var currentGirl;
	if(urlPieces.file) { //if its not the homepage we match by donut id.
		currentGirl = urlPieces.file;
	} else { //if it is we match by top story date.
		$("dl img").eq(0).attr("src").match(/\/sunshinegirl\/[\d]{4}\/[\d]{2}\/[\d]{2}\//);
		var whichFolder = RegExp['$&'];
		currentGirl = whichFolder;
	}
	$("#sunshineGirlPage .imgHList li a[@href*="+currentGirl+"]").eq(0).parent().addClass("active");	
}

/*-------------------------------------------*\
          COMMENTS
\*-------------------------------------------*/
function submitComment(commentForm) {
	var fields = new Array();
	var action = "/library/commentsubmit.php"; //commentForm.attr("action");
	
	fields["author"] = $("#commentForm *[name=author]");
	fields["email"] = $("#commentForm *[name=email]");
	fields["story_id"] = $("#commentForm *[name=story_id]");
	fields["section"] = $("#commentForm *[name=section]");
	fields["channel"] = $("#commentForm *[name=channel]");
	fields["comment"] = $("#commentForm *[name=comment]");
	
	var parameters = {
		author: fields["author"].val(),
		email: fields["email"].val(),
		story_id: fields["story_id"].val(),
		section: fields["section"].val(),
		channel: fields["channel"].val(),
		comment: fields["comment"].val()
	};
	
	if(formValidate(fields)) {
		$("#commentForm .submitBtn").attr("disabled","disabled"); //don't allow people to submit twice or the crazies to do it three times.
		$.post(action,parameters,
			function(data) {
				$("#commentForm .submitBtn").removeAttr("disabled");
				commentSuccess();
				return false;
			}
		);
	}
	return false;
}

function formValidate(fields) {
	var mistake = false;
	for ( var i in fields ) {
		if(fields[i].val()=="") {
			fields[i].addClass("formFail");
			mistake = true;
		} else {
			fields[i].removeClass("formFail");
		}
	}
	if(mistake && $("p.formError").size()==0) {
		$(".formContainer").append('<p class="formError"><span>Please complete all fields before submitting.</span></p>');
		$("p.formError").fadeIn(500)
	}
		
	return !mistake;
}

function commentSuccess() {
	$(".formContainer p.formError").remove();
	var container = $(".formContainer");
	container.css("height",container.height()+"px");
	container.html("<div class=\"formResult\"><p class=\"bold\">Thank you for your contribution to torontosun.com.</p><p>This section is fully moderated. Your comment will appear below once viewed by our editorial staff.</p></div>");
	container.animate({height: '7.5em'}, 1000);
	$("div.formResult").fadeIn(1500,function(){
		refreshAd("#bigbox","bigbox");
		refreshAd("#skyscraper","skyscraper");
	});
}

//Ajax calls for switching comment pages.
function bindCommentPages() {
	$("#comments ul.pages a").bind("click",function(){
		commentPage($(this));
		return false;
	});
}

//Code that runs after the comments switch pages
function commentPageFinish() {
	bindCommentPages();
	refreshAd("#bigbox","bigbox");
	refreshAd("#skyscraper","skyscraper");
}

function commentPage(linkElement) {
	var linkOptions = (linkElement.attr("href")).replace(/(.*?)\?(.*)/i,"?$2");
	var replaceDiv = $("#commentListing");
	replaceDiv.css("height",replaceDiv.height()+"px");
	replaceDiv.html('<div class="ajaxLoader">Loading</div>');
	$.get("/library/comments.php"+linkOptions+ajaxNoCache(), function(data){
		replaceDiv.html(data).css("height","auto");
		if(linkElement.parent().parents("ul.marginTop").size() == 1) {
			$('html,body').animate({scrollTop: replaceDiv.offset().top}, 1000, function(){
				commentPageFinish();
			});
		} else {
			commentPageFinish();
		}
	});	
}





/*-------------------------------------------*\
          EMAIL TO A FRIEND
\*-------------------------------------------*/

function bindEmail() {
	$(".articleControls .icon_email").bind("click", function(){ //Choose city for weather
		overlay("/html/emailpopup.html",397);
		return false;
	});
}

function closeit() {
	closeOverlay();
}

/*-------------------------------------------*\
	          REPORT TYPO
\*-------------------------------------------*/
function bindTypo() {
	$(".articleControls li.typo a").bind("click", function(){ //Choose city for weather
		overlay("/html/typopopup.html",397);
		return false;
	});
}


/*-------------------------------------------*\
          PARSE URL
\*-------------------------------------------*/
function parseUrl(url_data) {
	var e=/^((http|ftp):\/)?\/?([^:\/\s]+)(:\d+|)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-\/\.]+)?$/;
	if (url_data.match(e)) {
	return  {
		url: RegExp['$&'],
		protocol: RegExp.$2,
		host:RegExp.$3,
		port:RegExp.$4,
		path:RegExp.$5,
		file:RegExp.$7,
		hash:RegExp.$8};
	} else {
		return  {url:"", protocol:"",host:"",path:"",file:"",hash:""};
	}
}

/*-------------------------------------------*\
          EXPAND SOCIAL
\*-------------------------------------------*/
var moreRunning = false;
var moreExpanded = false;
function moreSocial(linkElement) {
	if(!moreRunning) {
		thisUL = linkElement.siblings("ul.social");
		moreRunning = true;
		if(!moreExpanded) {
			linkElement.html("&ndash;").attr("title","Cliquez pour fermer");
			thisUL.animate({height:"110px"},500,function(){moreRunning = false;thisUL.toggleClass("borderBottom");});
		} else {
			linkElement.html("+").attr("title","Cliquez pour ouvrir");
			thisUL.toggleClass("borderBottom");
			thisUL.animate({height:"17px"},500,function(){moreRunning = false;});
		}
		
		moreExpanded = !moreExpanded;
	}
}

/*-------------------------------------------*\
          IE6 TEST
\*-------------------------------------------*/

function isIE6() {
	return $.browser.msie6 = $.browser.msie &&
				parseInt($.browser.version) == 6 &&
				!window["XMLHttpRequest"];
}

//The article head needs to be an even height in IE6 so it respects absolutely positioning things to the bottom (the content swap tabs)
function fixIE6Head() {
	if(isIE6()) { //The article head needs to be an even height in IE6 so it respects absolutely positioning things to the bottom (the content swap tabs)
		var articleHead = $("#content .articleHead").eq(0);
		if(articleHead.height()%2 != 0)
			articleHead.height(articleHead.height()+1);
	}
}
/*-------------------------------------------*\
         CODE THAT RUNS ON PAGE LOAD
\*-------------------------------------------*/
var firstPageLoad = true;
function pageInit() {
	
	//RESET VARIABLES FOR AJAX CALLS
	currentTab=1;		//Keeps track of the current tab for rotating.
	firstLoad = true;	//Modifies the Toggle function on the first page load.
	dlFade = false;		//Keeps track of fading well it is occuring.
	if(dlRunning) {
		clearInterval(dlRotate);
		dlRunning = false;
	}
	
	//Takes care of the dynamic leads if they exist.
	if($(".rotateBox").size() != 0) {
		if($(".rotateBox.rotateFade").size() != 0) dlIsFade = true; //Checks if the tabs should fade

		dlNumTabs = $(".rotateItem").size(); //Checks how many tabs there are
		if($(".rotateBox .tabs").size() != 0) { //Checks if there are tabs
			dlIsTabs = true;
			dlToggle();
			$(".rotateBox .tabs a").bind("click", function(){ //binds function to dl tabs
				if(dlRunning) dlToggle();
				dlSwitch($(this).attr("href").substring(4));
				return false;
			});
		}

		$(".rotateNav a").bind("click", function(){ //binds functions to dl nav
			//if($(this).attr("href")=="#toggle"){
			if($(this).attr("href").indexOf("#toggle")!=-1){
				dlToggle();
			} else {
				if(dlRunning) dlToggle();
				dlCycle($(this).attr("href").slice(-4));
				if(!dlIsTabs) refreshAd("#bigbox","bigbox");
			}
			return false;
		});

		if($(".rotateCount").size() != 0) { //Checks if there is a counter that needs to be updated
			dlIsCount = true;
			$(".rotateCount").html("<span>1</span> of "+dlNumTabs)	
		}

		document.onkeydown = arrowSwitch;
		document.onkeyup = arrowCancel;
	}

	dlSlideCookie(); //Changes the default slider value for the DLs if a cookie is set
	bindSlider(); //adds the slider functionality

	bindEmail(); //bind send to a friend link.
	bindTypo(); //bind report typo link.

	//Binds the buttons for vertical scrolling boxes
	$(".extraVideoList a.scroll").bind("click", function(){
		verticalScroll($(this).attr("href").slice(-4),$(this).parent(),2,true);
		return false;
	});

	//Binds the buttons for scrolling ajax boxes
	$(".icon_print").bind("click", function(){
		window.print();
		return false;
	});

	$(".sizeText a").click(function(){
		sizeText($(this),$(this).attr("class"));
		return false;
	});
	highlightSize() //highlights the current text size
	
	$("span.chop:not(.chopped)").append("&hellip;").addClass("chopped");

	//This needs to happen before adding the rel swap stuff
	if(firstPageLoad) {
		$("#popularLatest .tabs a").unbind("click").bind("click", function(){ //latest/popular story tabs
			tabSwitch($(this));
			return false;
		});
	}

	$('a[rel$="swap"]').attr("rel","swapped").attr("href",function() { 
		return "#"+ajaxPath(this.href);
	}).unbind("click").click(function(){
		contentSwap($(this),"#contentSwap");
	});
	
	//Dirty hack for stupid IE positioning. Otherwise nested images are not clickable. TODO: Fix this crap without javascript.
	if($.browser.msie) {
		$(".imgList span.imgBorder img, ul.imageHomepage.imageHomepageTab li span.imgBorder img").unbind("click").click(function() { 
			var theLink = $(this).parents("a").eq(0).attr("href")
			if($(this).parent().parents('a[rel$="blank"]').size()==1)
				window.open(theLink);
			else
				window.location = (theLink);
		});
	}

	$("#commentForm").submit(function(){
		submitComment($(this));
		return false;
	});
	
	//Ajax calls for switching comment pages.
	bindCommentPages();
	
	$("a.moreSocial").bind("click", function(){
		moreSocial($(this));
		return false;
	});
	
	$('a[@rel$="overlay"]').unbind("click").click(function(){
		overlay($(this).attr("href"),397);
		return false;
	});
	
	if(firstPageLoad) {
		
		fixIE6Head();
		
		$('a[@rel$="blank"]').attr("target","_blank"); // Sets links with the rel of "blank" to open in a new window
		$('a.moreWeather').attr("target","_blank"); // Sets links with the rel of "blank" to open in a new window
		
		bindChooseCity(); //for weather selection
		
		$(".ddBorder2").bind("click", function(){ //Bind drop down menus
			dropDown($(this).attr("rel"));
			return false;
		});
	
		//Popup poll links
		$(".#pollForm a").bind("click", function(){
			afficheResultats($(this).attr("href"),$(this).attr("rel"));
			return false;
		});
		
		bindStoryHover($("div.story"));	
		$("div.story a").hover(function(){$(this).parents(".story").unbind("click")},function(){bindStoryClick($(this).parents(".story"))});
	
		//Widgets
		if($("#widgets").size()!=0){
			var so = new FlashObject("http://www.torontosun.com/images/widgets/widget_v3_tsun.swf", "ca", "572", "205", "7", "#ffffff");
			so.addVariable("config", "http://www.torontosun.com/images/widgets/canoeen_wv3.xml");
			so.addParam("quality", "high");
			so.addParam("salign", "t");
			so.addParam("wmode", "transparent");
			so.write("widgets");
		}
		
		//Alternate colors on some lists
		var isAltColor = false;
		$("ul.altColors li").each(function(){
			var thisthis = $(this);
			if(thisthis.attr("class")=="sectionTitle") isAltColor = true;
			if(isAltColor) thisthis.addClass("altBG");
			isAltColor = !isAltColor;
		});
		
		//Altername colors on table rows
		$("table.altColors tbody tr:even").addClass("altBG");
		
		
		//Binds the buttons for scrolling ajax boxes
		$(".scrollingBox .scroll").bind("click", function(){
			ajaxScroll($(this).attr("href").substring(1),$(this).parent());
			return false;
		});

		if($("#sunshineGirlPage").size()!=0)
			bindSunshine(); //binds ajax calls for the sunshine girl calendar 

		//These links are used to fake out the back button in IE.
		//It doesn't harm other browsers, but they don't need it.
		/*$("ul.tabs.dl.contentSwap a").each(function(a){
			$("body").prepend('<a name="'+$(this).attr("href").substring(1)+'"></a>');			
		});*/

		//for the gallery archive page this makes the entire table rows link to the gallery
		$("#galleryList tr:gt(0)").css("cursor","pointer").bind("click",function(){
			window.location = ($(this).children("td").eq(0).children("a").attr("href"));
		});
		
		if(isHash) loadHash();

		firstPageLoad = false;
	} else {
		$('#contentSwap a[@rel$="blank"]').attr("target","_blank");
	}

	$('#meteo_container a[@rel$="meteo"').click('return _link_meteo(this)');
	_meteo_change(true);
}

$(document).ready(function(){
    setTimeout(pageInit,1);
});





function _link_meteo(anchor) { 
	_linkmeteo = window.open(anchor.href,null,'height=260,width=420,status=no,toolbar=no,menubar=no,location=no');
	setTimeout('_linkmeteo.focus();',250);
	return false;
}
