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() {
		var omnitureSuiteNames = {
			'calgarysun'	: 'cnocalgarysuncomprod',
			'edmontonsun'	: 'cnoedmontonsuncomprod',
			'lfpress'	: 'cnolfpresscanoecaprod',
			'ottawasun'	: 'cnoottawasuncomprod',
			'torontosun'	: 'cnotorontosuncomprod',
			'winnipegsun'	: 'cnowinnipegsuncomprod'
		};
		
		//Omniture Tracking
		if (!dlIsTabs && !dlRunning) {
			slideViewSingleAccount(MyOmnitureVariables.articlename, MyOmnitureVariables.articlename + ' (Pic#=' + tabNum + ')', omnitureSuiteNames[thisWebsite()]);
		} else if (!dlIsTabs && dlRunning) {
			slideViewSingleAccount(MyOmnitureVariables.articlename + '-auto', MyOmnitureVariables.articlename + '-auto (Pic#=' + tabNum + ')', omnitureSuiteNames[thisWebsite()]);
		}
		
		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("weatherid");
		createCookie("weatherid",form.country.value+"_"+form.province.value.toLowerCase()+"_"+form.city.value.toLowerCase().replace(/ /g,"+"),1000);
		$("#weatherAjax").empty();
		closeOverlay();
		$.get("/library/weather/display_weather_strip.php?"+ajaxNoCache(), function(data){
			$("#weatherAjax").html(data);
			bindChooseCity();
		});
	} else {
		alert("Please fill out the form before submitting");	
	}
}

/*
	ADD STYLESHEET
*/
function addStyleSheet(href,media) {
	var oLink = document.createElement("link");
	// Append the <link> and then set the attributes, or else IE will not like it. The feeling is mutual, IE.
	oLink.media = media
	oLink.href = href;
	oLink.rel = "stylesheet";
	oLink.type = "text/css";
	$("head").append(oLink);
}

function removeStyleSheet(href) {
	if($.browser.msie || $.browser.safari) {
		$('link[href$="'+href+'"]').attr("href","");
	} else {
		$('link[href$="'+href+'"]').remove();
	}
}

/*
	OVERLAY
*/
function overlay(fileName,width) {
	fileName = fileName + (fileName.indexOf("?") == -1?"?":"") + ajaxNoCache();
	addStyleSheet("/styles/print_overlay.css","print"); //adds a print stylesheet for print the overlay
	$.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() {
	removeStyleSheet("/styles/print_overlay.css"); //adds a print stylesheet for print the overlay
	$("#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'});
	}
}

function overlayImage(fileName) {
	$("body").append('<div id="overlayFade"></div>');
	$("#overlayFade").css("height",$("body").height()+"px");
	$("#overlayFade").bind("click", function(){closeOverlay();});
	addStyleSheet("/styles/print_overlay.css","print"); //adds a print stylesheet for print the overlay

	var theImage = new Image();
	
	theImage.onload = function(){
		// Resizing large images - orginal from thickbox.
		var pagesize = getPageSize();
		var x = pagesize[0] - 150;
		var y = pagesize[1] - 150;
		var imageWidth = theImage.width;
		var imageHeight = theImage.height;
		if (imageWidth > x) {
			imageHeight = imageHeight * (x / imageWidth); 
			imageWidth = x; 
			if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
			}
		} else if (imageHeight > y) { 
			imageWidth = imageWidth * (y / imageHeight); 
			imageHeight = y; 
			if (imageWidth > x) { 
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x;
			}
		}
		// End Resizing
		
		var divWidth = imageWidth + 20;
		var divHeight = imageHeight + 30;
		var htmlStart = '<div id="overlay" class="overlayImage">';
		var htmlImage = '<img src="'+fileName+'" alt="Image Popup" width="'+imageWidth+'" height="'+imageHeight+'" style="margin:10px 10px 0;display:block;" />';
		var htmlFinish = '<p class="bold" style="text-align:right;padding-right:10px;line-height:20px;"><a href="#">close</a></div>';
		$("body").append(htmlStart+htmlImage+htmlFinish);

		var overlayDiv = $("#overlay");
		positionOverlay(divWidth,divHeight);
		overlayDiv.css({"width":divWidth+"px","height":divHeight+"px"});
		overlayDiv.fadeIn(600);
		$("#overlay a").bind("click", function(){
			closeOverlay();
			return false;
		});
	};
	
	theImage.src = fileName;

}

function getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
	arrayPageSize = new Array(w,h) 
	return arrayPageSize;
}

/*
	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()+')');
	});
}

//Initializes the "rotate nav" (combination of slider, left, right and play/pause buttons) for use.
function bindRotateNav() { 
	$(".rotateNav a").bind("click", function(){ //binds functions to dl nav
		if($(this).attr("href").indexOf("#toggle")!=-1){
			dlToggle();
		} else {
			if(dlRunning) dlToggle();
			dlCycle($(this).attr("href").slice(-4));
		}
		if(!dlIsTabs) { //refresh ads on gallerys but not dl tabs
			refreshAd("#bigbox","bigbox");
			refreshAd("#banner","superbanner");
			refreshAd("#skyscraper","skyscraper");
		}
		return false;
	});

	if($(".rotateCount").size() != 0) { //Checks if there is a counter that needs to be updated
		dlNumTabs = $(".rotateItem").size(); //Checks how many tabs there are
		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
}

/*
	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) {
	//Any time content is swapped, we must destroy the TwitterFeed object, if it exists.
	//This prevents a nasty tab flickering bug.
	if (typeof twitterFeed != "undefined") {
		if (typeof twitterFeed.destroy === "function") {
			twitterFeed.destroy();
		}
	}

	//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();
		bindRotateNav();
		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;
	if(document.location.hash.charAt(1)=="/") { //only blank the div for pages that load other content via ajax
		$("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 refreshAd2(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>');
	}

}

function refreshAd(div,type) {
	var whichDiv = $(div);
	if(whichDiv.data("adtag") == undefined)
		whichDiv.data("adtag", whichDiv.children("script").eq(1).attr("src"));

	if(whichDiv.data("adtag") != undefined) {
		var frameSrc = '/html/adrefresh-iframe.html?url='+randomOrd(whichDiv.data("adtag"),"expandable");
		whichDiv.html('<iframe src="'+frameSrc+'" frameborder="0" scrolling="no" allowtransparency="true" id="'+div.substring(1)+'_iframe" class="iframe_'+type+'"><\/iframe>');
	}
}

//Refreshes all ads on the page!
function refreshAllAds() {
	refreshAd("#bigbox","bigbox");
	refreshAd("#banner","superbanner");
	refreshAd("#skyscraper","skyscraper");
}


/*
	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.
		var sunSrc = $("dl img").eq(0);
		if(sunSrc.size()!=0) {
			sunSrc.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");	
}

/*
	SURVEY CONTENT TYPE
*/
function bindSurveyStory() {
	$(".storySurvey #survey").submit(function(){ 
		surveyStorySubmit($(this));
		return false;
	}); 
}

function surveyStorySubmit(survey) {
	var theForm = $(survey);
	$("#contentSwap").html('<div class="ajaxLoader">Loading</div>');
	$.post( 
		ajaxPath(theForm.attr("action")), 
		theForm.serialize(), 
		function(data){ 
			$("#contentSwap").html(data);
			$('html,body').animate({scrollTop: $("#content").offset().top}, 1000);
			bindSurveyStory();
		} 
	);
}



/*
	VERTICAL SCROLL
*/
var verticalScrollRunning = false;
function verticalScroll(direction,container,howMany,isAdRefresh) {
	if(!verticalScrollRunning) {
		verticalScrollRunning = true;
		var thisUL = container.children(".inner").children("ul");
		var totalHeight = thisUL.height();
		var boxHeight = thisUL.children("li").eq(0).height();
		var scrollDis = boxHeight*howMany;
		var noMove = false; //if its true it shouldnt scroll and thus will not.
		var nextLimit = (-1*(totalHeight-boxHeight*howMany));
		var positionTop = parseInt(thisUL.css("top").replace("px",""));
		var whereToMove;
		
		if(direction=="next") {
			whereToMove = positionTop - scrollDis;
			container.children("a.scroll.disabledp").removeClass("disabledp");
			if(whereToMove <= nextLimit) container.children("a.scroll.next").addClass("disabledn");
			if(positionTop <= nextLimit) noMove = true;
		} else {
			whereToMove = positionTop + scrollDis;
			container.children("a.scroll.disabledn").removeClass("disabledn");
			if(whereToMove == 0) container.children("a.scroll.prev").addClass("disabledp");
			if(positionTop == 0) noMove = true;
		}
		
		if(!noMove)
			thisUL.animate({top: whereToMove},700,function(){
				verticalScrollRunning = false;
				if(isAdRefresh) refreshAd("#bigbox","bigbox");
			});
		else
			verticalScrollRunning = false;
	}
}

/*
	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","Click here to close");
			thisUL.animate({height:"80px"},500,function(){moreRunning = false;thisUL.toggleClass("borderBottom");});
		} else {
			linkElement.html("+").attr("title","Click here to show more");
			thisUL.toggleClass("borderBottom");
			thisUL.animate({height:"16px"},500,function(){moreRunning = false;});
		}
		
		moreExpanded = !moreExpanded;
	}
}

/*
	VIDEO/AUDIO/FLASH PLAYERS
*/

function loadGenericFlash(file,width,height,div) {
	div = defaultValue(div,"flashinfo");
	var fi = new FlashObject(file, "ca", width, height, "7", "#ffffff");
	fi.addParam("quality", "high");
	fi.addParam("wmode", "transparent");
	fi.addParam("salign", "t");
	fi.write("flashinfo");
}

function loadFlashInfo(file,lang,div) {
	div = defaultValue(div,"flashinfo");
	var fi = new FlashObject(file, "ca", "620", "500", "7", "#ffffff");
	fi.addParam("quality", "high");
	fi.addParam("wmode", "transparent");
	fi.addParam("salign", "t");
	fi.addVariable("lg", lang);
	fi.write("flashinfo");
}

function loadAudio(id,path) {
	var so_audio = new FlashObject("/images/flash/minimp3.swf?textcolor=e32d28&lang=en&soundurl="+path, "ca", "135", "45", "7", "#ffffff");
	so_audio.addParam("quality", "high");
	so_audio.addParam("wmode", "transparent");
	so_audio.addParam("salign", "t");
	so_audio.write(id);	
}

function loadVideo(id,playerID,div,width,height) {
	//default values
	div = defaultValue(div,"videoPlayer");
	width = defaultValue(width,406);
	height = defaultValue(height,353);

	var so = new FlashObject("http://c.brightcove.com/services/viewer/federated_f9?isVid=true&isUI=true", "ca", width, height, "9", "#ffffff");
	so.addParam("allowFullScreen","true");
	so.addParam("allowScriptAccess","always");
	so.addParam("seamlessTabbing","false");
	so.addParam("wmode", "transparent");
	
	so.addVariable("publisherID","1749345207");
	so.addVariable("playerID",playerID);
	if(id != false) //set to false if the player does not take in single video ids
		so.addVariable("@videoPlayer",id);

	so.write(div);
	
}

function loadVideoAdRefresh(id,playerID,div,width,height) {
	CanoeVideoStandalone.Init(1749345207,playerID,id);
	
	CanoeVideoStandalone.SetExperienceId('canoePlayer');
	CanoeVideoStandalone.SetStyle({ bgcolor: '#f3f3f3', width: width, height: height });
	CanoeVideoStandalone.SetPlayerContainer('#' + div);
	CanoeVideoStandalone.SetAdContainer('#bigbox');
	CanoeVideoStandalone.SetAdServer(AdServer2000x2000URL);
	CanoeVideoStandalone.SetAdTag(bigboxURL);
	
	CanoeVideoStandalone.GeneratePlayer();
	
	/* If the bigbox has already loaded load the video immediately.
	   If not wait for the dom to be ready and then store the bigboxes default ad tag.
	     The brightcove will load the video when the dom is ready if it hasn't been forced already */
	if($('#bigbox').size()>0) {
		brightcove.createExperiences();
	} else {
		$(document).ready(function(){
			var theBigBox = $("#bigbox").eq(0);
			if(theBigBox.data("adtag") == undefined)
				theBigBox.data("adtag", theBigBox.children("script").eq(1).attr("src"));
		});
	}
}

/*
	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);
	}
}


/*
	BIND OVERLAY
*/
function bindOverlay() {
	$('a[rel$="overlay"]').unbind("click").click(function(){
		overlay($(this).attr("href"),397);
		return false;
	});
}


/*
	LAVALIFE
*/
function setInterruptPage(n) {
   styleChange(ss_picture).innerHTML = interruptPage;
   styleChange(ss_name).innerHTML = '<img src="http://www.lavalife.com/images/xxxx-pixel.gif" width="1" height="14" border=0>';
   styleChange('ss_text').innerHTML = '<img src="http://www.lavalife.com/images/xxxx-pixel.gif" width="1" height="15" border=0>';
}

function go(dir, gender) {
   ss_picture = 'ss_picture_both';
   ss_name    = 'ss_name_both';

   if (intrpCount == 0 || intrpCountM == 0 || intrpCountF == 0) {
      if (dir != 0) {
         if (gender == 1) {
            intrpCountF = intervalInterruptPage;
         }
         else if (gender == 2) {
            intrpCountM = intervalInterruptPage ;
         }
         else {
            intrpCount = intervalInterruptPage ;
         }

         setInterruptPage(1);
      }
   } else {
      if (dir != 0) {
         if (gender == 1) {
            intrpCountF--;
         }
         else if (gender == 2) {
            intrpCountM--
         }
         else {
            intrpCount--
         }
      }

      if (gender == 1) {
         count  = countF + dir;
         if (count > maxPicF) count = 1;
         if (count < 1) count = maxPicF;

         countF = count;
         currGender = 1;
      } else if (gender == 2) {
         count  = countM + dir;
         if (count > maxPicM) count = 1;
         if (count < 1) count = maxPicM;

         countM = count;
         currGender = 2;
      } else {
         if ((currGender == 2 && dir == 1) || (currGender == 1 && dir == -1)) {
            count  = countBoth + dir;
         }

         if (count > maxPicBoth && currGender == 2) {
            count = 1;
         }

         if (count < 1 && currGender == 1) {
            count = maxPicBoth;
         }

         countBoth = count;
         if (currGender == 1) {
            currGender = 2 ;
         } else {
            currGender = 1 ;
         }
      }

	  styleChange(ss_picture).innerHTML = getSSPicture(gender);
      styleChange(ss_name).innerHTML = getSSId(gender);
      styleChange('ss_text').innerHTML = getSSText();
   }
}

function getViewLink(gender) {
   var seeking = '?i_am=F&seeking=M';

   if (gender == 1) {
      seeking = '?i_am=M&seeking=F';
   }

   var memberLink = 'http://www.lavalife.com/clickthru/clickthru.act?' +  seeking + '&idname=' + escape(slideShowIds[currGender][count]) + '&id=externalSlideshow&context=ad77';

   return memberLink;
}

function getSSPicture(gender) {
   var memberLink = getViewLink(gender);
   var tmp = '<a href="' + memberLink + '" target="_new"><img src="' + photo_directory + slideShowPics[currGender][count] + suffix +  '" border="0" class="vertAlign"></a>';
   return tmp;
}

function getSSId(gender) {
   var memberLink = getViewLink(gender);
   return '<a href="' + memberLink + '">'+ slideShowIds[currGender][count] + '</a>';
}

function getSSText() {
   return '<img src="images/lavalife/messenger_actualMember.gif" alt="" width="148" height="15" border="0" style="margin-left: 2px;">';
}

/*
	WIDGETS
*/
function loadVerticalsWidget(config,vars,div) {
	div = defaultValue(div,"widgets");

	var so = new FlashObject("/images/widgets/widget_v3.1.swf", "ca", "572", "205", "7", "#ffffff");
	so.addParam("quality", "high");
	so.addParam("salign", "t");
	so.addParam("wmode", "transparent");

	$.each(vars, function(key,value) {
		so.addVariable(key, value);
	});
	so.addVariable("config", config);
	so.addVariable("subDomain", thisWebsite());
	so.write(div);
}

//Returns a unique ID representing the website currently being viewed.
function thisWebsite() {
	var href = document.location.href;
	
	if (href.indexOf('calgarysun') != -1) {
		return 'calgarysun';
	} else if (href.indexOf('edmontonsun') != -1) {
		return 'edmontonsun';
	} else if (href.indexOf('lfpress') != -1) {
		return 'lfpress';
	} else if (href.indexOf('ottawasun') != -1) {
		return 'ottawasun';
	} else if (href.indexOf('torontosun') != -1) {
		return 'torontosun';
	} else if (href.indexOf('winnipegsun') != -1) {
		return 'winnipegsun';
	}
	
	return '';
}

/*
	YOUR SCOOP
*/
function form_submitter(){
	document.uploadform.action = "http://rapids.canoe.ca/cgi-bin/reg/NR-register.pl?";
	document.uploadform.submit();
	return true;
}

//Assigns a default value for functions
function defaultValue(value,defaultV) {
	return typeof(value) != 'undefined' ? value : defaultV;
}




/*
	CODE THAT RUNS ON PAGE LOAD
*/
var firstPageLoad = true;
function pageInit() {
	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,false);
		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;
	});
	
	$("#commentForm #comment").charCounter(750, {
		container: "#textCounter",
		delay: 50
	});
	
	//Ajax form submit for surveys in story enviroments
	bindSurveyStory();

	$("a.moreSocial").bind("click", function(){
		moreSocial($(this));
		return false;
	});
	
	bindOverlay(); //sets links with a rel of "overlay" to open in an overlay window.
	
	$('p.captchaContainer a').bind("click",function(){refreshCaptcha();return false;});
	
	if(firstPageLoad) {
		
		fixIE6Head();
		
		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("/html/widget_flash.html", "ca", "572", "205", "7", "#ffffff");
			so.addVariable("config", "/html/widget_xml.html");
			so.addParam("quality", "high");
			so.addParam("salign", "t");
			so.addParam("wmode", "transparent");
			so.write("widgets");
		}*/
		
		//Alternate colors on some lists
		$("ul.altColors").each(function(){
			var isAltColor = false;
			$(this).children("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:nth-child(odd)").addClass("altBG");
		
		
		//Binds the buttons for scrolling ajax boxes
		$(".scrollingBox .scroll").bind("click", function(){
			ajaxScroll($(this).attr("href").substring(1),$(this).parent());
			return false;
		});
		
		//Assign a CSS 'clip' property to content package tabs whenever those tabs occupy too much horizontal space.
		//This discourages the addition of too many tabs, by cutting off the left side of the tabs in an ugly way.
		var cpTabs = $('div#content ul.tabs');					//A temporary handle for our content package tabs.
		var cpTabsClip;											//Stores the new CSS clip rule to be assigned to the tabs.
		var cpTabsDifference;									//Stores the difference in width between the content package tabs, and their maximum allowed width.		
		var cpTabsMaxWidth = 390;								//The maximum width, in pixels, that the content package tabs are allowed to occupy.

		if (cpTabs.width() > cpTabsMaxWidth) {
			cpTabsDifference = cpTabs.width() - cpTabsMaxWidth;
			cpTabsClip = 'rect(0px, ' + cpTabs.width() + 'px, 25px, ' + cpTabsDifference + 'px)';
			cpTabs.css('clip', cpTabsClip);
		}

		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");
	}

}

$(document).ready(function(){
	pageInit();
});

//Set any link with a rel of "blank", when clicked, to open in a new window.
//We are using jQuery.live() to modify these links as the DOM loads. Otherwise,
//if the page takes a long time to load, jQuery(document).ready() will be delayed
//and when the user clicks on a rel="blank" link, it will open in the SAME window!
$('a[rel$="blank"]').live('click', function() {
	$(this).attr("target","_blank");
});

//Initialize the DL tabs as soon as possible, so that they user may change tabs while ads are still loading.
CanoeUtils.asap('.rotateBox', function() {
	//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;
			});
		}
	}
});

//Initialize the DL nav and speed slider as soon as possible, so that they user may change tabs while ads are still loading.
//Also initializes controls for photo galleries, which depend upon the same JavaScript widgets.
CanoeUtils.asap('.rotateNav', function() {
	bindRotateNav();
});


/*-------------------------------------------*\
         jQuery Plugins
\*-------------------------------------------*/

/**
 *
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
(function($) {
	/**
	 * attaches a character counter to each textarea element in the jQuery object
	 * usage: $("#myTextArea").charCounter(max, settings);
	 */
	
	$.fn.charCounter = function (max, settings) {
		max = max || 100;
		settings = $.extend({
			container: "<span></span>",
			classname: "charcounter",
			format: "(%1 characters remaining)",
			pulse: true,
			delay: 0
		}, settings);
		var p, timeout;
		
		function count(el, container) {
			el = $(el);
			if (el.val().length > max) {
			    el.val(el.val().substring(0, max));
			    if (settings.pulse && !p) {
			    	pulse(container, true);
			    };
			};
			if (settings.delay > 0) {
				if (timeout) {
					window.clearTimeout(timeout);
				}
				timeout = window.setTimeout(function () {
					container.html(settings.format.replace(/%1/, (max - el.val().length)));
				}, settings.delay);
			} else {
				container.html(settings.format.replace(/%1/, (max - el.val().length)));
			}
		};
		
		function pulse(el, again) {
			if (p) {
				window.clearTimeout(p);
				p = null;
			};
			el.animate({ opacity: 0.1 }, 100, function () {
				$(this).animate({ opacity: 1.0 }, 100);
			});
			if (again) {
				p = window.setTimeout(function () { pulse(el) }, 200);
			};
		};
		
		return this.each(function () {
			var container = (!settings.container.match(/^<.+>$/)) 
				? $(settings.container) 
				: $(settings.container)
					.insertAfter(this)
					.addClass(settings.classname);
			$(this)
				.bind("keydown", function () { count(this, container); })
				.bind("keypress", function () { count(this, container); })
				.bind("keyup", function () { count(this, container); })
				.bind("focus", function () { count(this, container); })
				.bind("mouseover", function () { count(this, container); })
				.bind("mouseout", function () { count(this, container); })
				.bind("paste", function () { 
					var me = this;
					setTimeout(function () { count(me, container); }, 10);
				});
			if (this.addEventListener) {
				this.addEventListener('input', function () { count(this, container); }, false);
			};
			count(this, container);
		});
	};

})(jQuery);
