$(document).ready(function() {
	
	// show banner once per session based on cookies
	if($("#flashBanner").length > 0) { 
		if($.cookie("flashBanner") != null) { } else {
			$('#flashBanner img').css({'display':'none'});
			$.cookie("flashBanner", true);
			var flashvars = {}, params = { wmode:"transparent" }, attributes = {};
			swfobject.embedSWF("/flash/banner.swf", "flashBanner", "960", "164", "9.0.0", false, flashvars, params, attributes);
		}
	}

	navArrowStyler.init();
	lightBoxEnable.init();
	lightBoxDefaultPlay.init();
	newsCollationPaging.init();
	preserveForwardURL.init();
	
	$('form.regForm select, form.regForm input[type=checkbox]').uniform();
	
	/* IE fixes */
	if(typeof(isIEVersion) != "undefined") { 
		if(isIEVersion == 6) { ie6Fixes.init(); } // ie6 specific fixes
	}
});


// any IE6 specific fixes that are required can be placed here
var ie6Fixes = {
	init: function() {
		$('div.homeNewsLinks div.homeNewsLink.main a img').attr({src: '/static-images/home-newslink-main-button.gif'});
	}
}


var preserveForwardURL = {
	init:function() {
		if($('#headerForm').legnth < 1) { return; }
		if($('#forward-to-url').length > 0 && $('#forward-to-url').attr('value') != '') {
			$('#headerForm #headerFormURL').attr({'value':$('#forward-to-url').attr('value')});
		}
	}
}


var lightBoxDefaultPlay = {

	init:function() {
		if($('div.homeGalleryBody').length > 0) {
			this.attachHomeClickEvents();
		} else {
			return;
		}
	},
	
	attachHomeClickEvents:function() {
		$('div.homeGalleryBody li a').each(function(s, e) {
			if($(e).find('img').length > 0) {
				var link = $(e).attr('href') + '?dimg=' + $(e).find('img').eq(0).attr('src');
				$(e).attr({'href':link});
			}
		});
	}
}


var panelNorm = {
	init:function() {
		if($('div.panel').length < 1) { return; }
		var h = 0;
		$('div.panel').each(function(s, e) {
			if(parseInt($(e).height(), 10) > h) {
				h = parseInt($(e).height(), 10);
			}
		});
		if(h > 0) { $('div.panel').css({'height':h}); }
	}
}


var navArrowStyler = {
	url: {
		news: { str: '/latest-news/', css: 'themeNews' },
		reports: { str: '/race-reports/', css: 'themeReports' },
		dates: { str: '/key-dates/', css: 'themeDates' },
		gallery: { str: '/gallery/', css: 'themeGallery' },
		comp: { str: '/pit-lane/', css: 'themeComp' }
	},
	
	init:function() {
		var obj = this;
		//list of all items that require styling
		// home page big panel style links
		
		$('div.homeLinkPanel').each(function(s, e) {
			$.each(obj.url, function(objKey, objVal) {
				if($(e).find('div.top a').eq(0).attr('href').beginsWith(objVal.str)) { $(e).find('div').eq(0).addClass(objVal.css); }
			});
		});
		
		$('div.bodyPanel div.bodyPanelHeaderTopTall .link').each(function(s, e) {
			$.each(obj.url, function(objKey, objVal) {
				if($(e).find('a').eq(0).attr('href').beginsWith(objVal.str)) { $(e).addClass(objVal.css); }
			});
		});	
		
		$('div.newsPanel div.text h2 a').each(function(s, e) {
			$.each(obj.url, function(objKey, objVal) {
				if($(e).attr('href').beginsWith(objVal.str)) { $(e).parent().addClass(objVal.css); }
			});
		});	
		
		$('div.articleModule ul.related li').each(function(s, e) {
			$.each(obj.url, function(objKey, objVal) {
				if($(e).find('a').eq(0).attr('href').beginsWith(objVal.str)) { $(e).addClass(objVal.css); }
			});
		});
		
		$('div.sidePanelHeadTop h2.link').each(function(s, e) {
			$.each(obj.url, function(objKey, objVal) {
				if($(e).find('a').eq(0).attr('href').beginsWith(objVal.str)) { $(e).addClass(objVal.css); }
			});
		});
		
		$('div.sidePanelBodyTop ul.linkList li').each(function(s, e) {
			$.each(obj.url, function(objKey, objVal) {
				if($(e).find('a').eq(0).attr('href').beginsWith(objVal.str)) { $(e).addClass(objVal.css); }
			});
		});
	}
}


String.prototype.beginsWith = function(s) {
	return (s == this.substring(0, s.length));
};


var lightBoxEnable = {
	grouping:'.lbox',
	item:'a[rel="imageshow"]',
	initCheck:false, // set to true after initial page load url check
	
	qsParam: 'dimg',
	itemPos:null, // if there is a default image to open, this is the position
	panelWidth:638,
	scrolling: false,	// is the object currently scrolling
	scrollSpeed: 1000,  // speed of scroll
	scrollInt: 3500,	// interval between auto scroll
	scrollSelf: true,	// set auto scroll on or off
	twoPanelEndlessScroll: true, // set to false when only two panels and the scroll effect goes left, right, left instead of forever left	
	elems: Array('#galleryImages','#galleryVideo'),

	init:function() {
		var obj = this;
		var qStr = ''+location.search; // turn querystring into a text string
		$('a[rel="imageshow"]').each(function(s, e) {
			if(qStr.indexOf(obj.qsParam + "=" + $(this).find('img').eq(0).attr('src')) > -1 && obj.itemPos == null) { obj.itemPos = s; }
			$(e).colorbox({ transition:'elastic',  speed:500,  current:'' });
		});
		if(obj.itemPos != null) {  $('a[rel="imageshow"]').eq(obj.itemPos).trigger('click'); }
		
		if($('#colorbox_target').length < 1) {
			$('body').append('<div style="display: none"><div id="colorbox_target" style="width: 640px; padding-top: 5px; padding-left: 6px; padding-right: 6px;height: 386px;"><div id="colorbox_target_video"></div></div></div>'); // originally "580", "400"
		}
		
		$('a[rel="videoshow"]').colorbox({
			current:'',
			inline:true, 
			href: "#colorbox_target",
			onComplete:function(){ 
				var flashvars = { 
					file:$(this).attr('href'), 
					autostart:true, 
					'plugins':'googlytics-1',
					skin: '/flash/vpstyle/vpstyle.xml'
				}
				var params = { wmode:'transparent', allowfullscreen:'true', allowscriptaccess:'always' }, attributes = {};
				swfobject.embedSWF("/javascript/player.swf", 'colorbox_target_video', "640", "386", "9.0.0", false, flashvars, params, attributes);	
			}
		});	
		
		// for normal pages, return now, gallery requires more controls, below:
		if($('#galleryImages').length < 1) { return; }
		
		// set up scrolling
		$.each(obj.elems, function(index, elem) {
			if($(elem + ' div.galleryBody ul').length > 1) { // check there are multiple panels required to scroll
				
				// create next/previous links
				var html = '<ul><li class="next"><a href="#">Next</a></li><li class="prev"><a href="#">Previous</a></li></ul>';
				$(elem + ' div.bodyPanelFooterTop').append(html);
				
				// set width of slider
				$(elem).data("panelNum", $(elem + ' div.slider ul').length); // assign number of panels as data to the container element
				$(elem + ' div.slider').css({'width':parseInt(obj.panelWidth, 10) * parseInt($(elem).data("panelNum"), 10)});
			
				$(elem + ' li.next').click(function(ev) {
					ev.preventDefault();
					obj.scroll(obj.returnNext(elem), ev, elem, 'next');
				});
				$(elem + ' li.prev').click(function(ev) {
					ev.preventDefault();
					obj.scroll(obj.returnPrev(elem), ev, elem, 'prev');
				});
				
				$(elem).data("visibleSet", 0); // set initial visible set to 0
				$(elem).data("scrolling", false);
			}
		});
	},

	// find the next/previous item in the set and return the number indicator for that item
	returnNext:function(elem) {
		return (parseInt($(elem).data("visibleSet"), 10)+1) > (parseInt($(elem).data("panelNum"), 10)-1) ? 0 : parseInt($(elem).data("visibleSet"), 10)+1; // +1 to account for zero indexing, +1 to get the next increment
	},	
	returnPrev:function(elem) {
		return (parseInt($(elem).data("visibleSet"), 10)-1) < 0 ? (parseInt($(elem).data("panelNum"), 10)-1) : (parseInt($(elem).data("visibleSet"), 10)-1);
	},
	
	scroll:function(set, event, elem, action) {
		var obj = this;
		
		event = (!event ? null : event);
		elem = (!elem ? null : elem);
		if(event != null) { event.preventDefault(); }
		
		if(set == $(elem).data("visibleSet")) { return; }

		if($(elem).data("scrolling") == false) {
			// handles special scroll scenarios, i.e. going from first to last or last to first
			if((parseInt($(elem).data("visibleSet"), 10)+1 == parseInt($(elem).data("panelNum"), 10) && set == 0 && action == 'next') || (parseInt($(elem).data("visibleSet"), 10) == 0 && set+1 == parseInt($(elem).data("panelNum"), 10)) || (parseInt($(elem).data("visibleSet"), 10) === 0 && action == 'prev')) {
				if((parseInt($(elem).data("visibleSet"), 10) == 1 && $(elem).data("panelNum") == 2 && obj.twoPanelEndlessScroll == true) || ($(elem).data("panelNum") > 2) ) {
					obj.specialScroll(set, event, elem);
					return;
				}
			}
			
			// handles special scroll of going from item zero to item 1 in a 2 panel scenario
			if(parseInt($(elem).data("visibleSet"), 10) === 0 && action == 'prev') { 
				obj.specialScroll(set, event, elem);
				return;
			}
			
			var obj = obj;
			var s = $(elem + ' div.slider').eq(0);
			var newPos = ( 0 - (parseInt(set, 10) * obj.panelWidth) );
			
			$(elem).data("visibleSet", set);
			$(elem).data("scrolling", true);
			s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(elem); });
		}
	},

	specialScroll:function(set, event, elem) {
		var obj = this;
		var s = $(elem + ' div.slider').eq(0);
		var start = 'last'; // default is going from last to first as this occurs naturally in the auto-scrolling action

		if(parseInt($(elem).data("visibleSet"), 10)+1 == 1) { start = 'first'; }

		// clone the last item before the first or the first item after the last depending on start
		if(start == 'last') {
			$(elem + ' div.slider').append($(elem + ' div.slider ul').eq(set).clone());
		} else {
			s.css({'left': (0-parseInt(obj.panelWidth, 10)) });
			$(elem + ' div.slider').prepend($(elem + ' div.slider ul').eq(set).clone());
		}
		$(elem + ' div.slider').eq(0).css({'width': parseInt($(elem + ' div.slider').eq(0).css('width'), 10) + parseInt(obj.panelWidth, 10)});
		
		var newPos = ( start == 'first' ? 0 : 0 - ((parseInt($(elem).data("visibleSet"), 10) * obj.panelWidth) + obj.panelWidth) );
		$(elem).data("visibleSet", set);
		$(elem).data("scrolling", true);
		s.stop().animate({ left:newPos }, obj.scrollSpeed, "swing", function() { obj.stopScroll(elem, start); });	
	},	
	
	stopScroll:function(elem, special){ 
		
		if(typeof(special) != 'undefined') {
			
			var obj = this;
			var s = $(elem + ' div.slider').eq(0);
			
			if(special == 'last') {
				s.css({'left':0});
				$(elem + ' div.slider ul').eq($(elem + ' div.slider ul').length-1).remove();
			} else if(special == 'first') {
				s.css({'left': (0 - (parseInt($(elem + ' div.slider ul').length, 10)-1) * this.panelWidth) + this.panelWidth  });
				$(elem + ' div.slider ul').eq(0).remove();
			}
			$(elem + ' div.slider').eq(0).css({'width': parseInt($(elem + ' div.slider').eq(0).css('width'), 10) - parseInt(this.panelWidth, 10)});
		}
		$(elem).data("scrolling", false); 
	}
	
}


var newsCollationPaging = {
	
	selected: 0,

	init:function() {
	
		if($('#newsCollation div.newsPanelSubGroup').length < 2) { 
			$('div.newsPanelSubGroup').eq(0).css({'display':'block'});
			return; 
		} // only create pagination if more than 1 section of news exists
		
		var obj = this;
		$('div.newsPanelSubGroup').css({'display':'none'});
		$('div.newsPanelSubGroup').eq(0).css({'display':'block'});
		
		var html = '<p id="newsPagination">Page:&nbsp;&nbsp;';
		for(var i=0; i < parseInt($('#newsCollation div.newsPanelSubGroup').length, 10); i++) {
			html += '<a href="#">' + (parseInt(i, 10) +1) + '</a>';
			if(i < (parseInt($('#newsCollation div.newsPanelSubGroup').length, 10)-1)) {
				html += '&nbsp;&nbsp;|&nbsp;&nbsp;';
			}
		}
		
		html = '<div class="bodyPanelFooterTop">' + html + '<ul id="newsPaginationNav"><li class="next"><a href="#">Next</a></li><li class="prev"><a href="#">Previous</a></li></ul></div><div class="bodyPanelFooterBottom">&nbsp;</div>';
		$('#newsCollation div.collationSection').find('div.bodyPanelFooterBottomShort').eq(0).after(html).remove();
		
		$('#newsCollation p#newsPagination a').eq(0).addClass('selected');
		
		$('#newsCollation p#newsPagination a').each(function(s, e) {
				$(e).click(function(ev) {
				ev.preventDefault();
				$(this).blur();
				if(!$(this).hasClass('selected')) {
					$('#newsCollation p#newsPagination a').removeClass('selected');
					$(this).addClass('selected');
					$('#newsCollation div.newsPanelSubGroup').css({'display':'none'});
					$('#newsCollation div.newsPanelSubGroup').eq(s).css({'display':'block'});
					obj.selected = s;
					
				}
			});
		});
		
		$('#newsCollation #newsPaginationNav li.next a').click(function(ev) {
			ev.preventDefault();
			$(this).blur();
			
			if($('#newsCollation p#newsPagination a').eq(parseInt(obj.selected, 10) +1).length > 0) {
				$('#newsCollation p#newsPagination a').removeClass('selected');
				$('#newsCollation p#newsPagination a').eq(parseInt(obj.selected, 10) +1).addClass('selected');
				obj.selected = obj.selected+1;
			} else {
				$('#newsCollation p#newsPagination a').removeClass('selected');
				$('#newsCollation p#newsPagination a').eq(0).addClass('selected');
				obj.selected = 0;
			}
			
			$('#newsCollation div.newsPanelSubGroup').css({'display':'none'});
			$('#newsCollation div.newsPanelSubGroup').eq(obj.selected).css({'display':'block'});
		});

		$('#newsCollation #newsPaginationNav li.prev a').click(function(ev) {
			ev.preventDefault();
			$(this).blur();
			
			if(obj.selected > 0 && $('#newsCollation p#newsPagination a').eq(parseInt(obj.selected, 10) -1).length > 0) {
				$('#newsCollation p#newsPagination a').removeClass('selected');
				$('#newsCollation p#newsPagination a').eq(parseInt(obj.selected, 10) -1).addClass('selected');
				obj.selected = obj.selected-1;
			} else {
				$('#newsCollation p#newsPagination a').removeClass('selected');
				$('#newsCollation p#newsPagination a').eq((parseInt($('#newsCollation p#newsPagination a').length, 10)-1)).addClass('selected');
				obj.selected = (parseInt($('#newsCollation p#newsPagination a').length, 10)-1);
			}
			
			$('#newsCollation div.newsPanelSubGroup').css({'display':'none'});
			$('#newsCollation div.newsPanelSubGroup').eq(obj.selected).css({'display':'block'});
		});

	}

}



