var IE = $.browser.msie, IEv = $.browser.version;
if (IE) var IE7 = parseInt(IEv) == 7, IE8 = parseInt(IEv) == 8, IE9 = parseInt(IEv) == 9;

$(document).ready(function () {
	$("a[rel^='prettyPhoto']").prettyPhoto();
	analyticsTracking();
});

homePage = function () {
	rangeHighlights();
	headerRotator();
	homeTyreHighlights();
};

rangeHighlights = function () {
	var panel = ".range-highlights .frame",
		item = ".range-highlights .nav li a";
	$(panel).hide();
	$(panel).eq(0).show();
	$(item).eq(0).parent("li").addClass("active");
	$("body").append('<div id="video"></div><div id="video-bg"></div>');

	$(item).hover(
		function () {
			$(item).parent("li").removeClass("active");
			$(this).parent("li").addClass("active");
			$(panel).hide();
			var href = $(this).attr("href");
			$(href).show();
		},
		function () {
			//
		});
};

analyticsTracking = function () {

	$("body.homepage .tyre-search.form .input-button.submit").click(function () {
		_gaq.push(['_trackEvent', 'Form', 'Submit', 'Find-Tyres-Homepage']);
	});
	$("body.homepage .stockist-search.form a.input-button.submit").click(function () {
		_gaq.push(['_trackEvent', 'Form', 'Submit', 'Find-Stockist-Homepage']);
	});
	$("body.homepage a.facebook").click(function () {
		_gaq.push(['_trackEvent', 'External-link', 'Click', 'Facebook']);
	});
	$("body.homepage .article.newsletter .input-button.submit").click(function () {
		_gaq.push(['_trackEvent', 'Form', 'Submit', 'Newsletter']);
	});
	$("body.stockists.landing .stockist-search.form .input-button.submit").click(function () {
		_gaq.push(['_trackEvent', 'Form', 'Submit', 'Find-Stockist-Stockist-Page']);
	});
	$("body.tyrelanding .tyre-search.form .input-button.submit").click(function () {
		_gaq.push(['_trackEvent', 'Form', 'Submit', 'Find-Tyres-Tyre-Pages']);
	});
	$("body.tyrelanding .stockist-search.form a.input-button.submit").click(function () {
		_gaq.push(['_trackEvent', 'Form', 'Submit', 'Find-Stockist-Tyre-Pages']);
	});
	$("body.contact-us fieldset .input-button").click(function () {
		_gaq.push(['_trackEvent', 'Form', 'Submit', 'Contact-Form']);
	});
	$("a[href$=pdf]").click(function () {
		var name = $(this).attr("title");
		_gaq.push(['_trackEvent', 'PDF', 'Download', name]);
    });
    //Apps
    $("body.app .maxxis-app a.iphone[href]").click(function () {
        _gaq.push(['_trackEvent', 'App', 'Download', 'Apple iOS']);
    });
    $("body.app .maxxis-app a.android[href]").click(function () {
        _gaq.push(['_trackEvent', 'App', 'Download', 'Android']);
    });
    $("body.app .maxxis-app a.blackberry[href]").click(function () {
        _gaq.push(['_trackEvent', 'App', 'Download', 'Blackberry']);
    });
    $("body.app .maxxis-app a.wp7[href]").click(function () {
        _gaq.push(['_trackEvent', 'App', 'Download', 'WindowsPhone']);
    });


};

headerRotator = function () {

	var header = '#h .background',
	overlayVideo = '#video';

	$('#h .overlay .title').html($(header + ' a:eq(0)').attr('title'));
	$('#h .overlay').show();

	$('#h .section.h').append('<div class="video-trigger"></div>');

	if (IE7 || IE8) {
		$('#h .video-trigger').hover(function () { $(this).toggleClass('hover');}

		/*function () {
		$(this).addClass('hover');
		},
		function () {
		$(this).removeClass('hover');
		}*/
		);
	}

	$(header).tabs('#h .background > a', {
		effect: 'fade',
		fadeInSpeed: 300,
		fadeOutSpeed: 'slow',
		rotate: true,
		onBeforeClick: function (event, tabIndex) {
			title = $(header + ' a:eq(' + tabIndex + ')').attr('title');
			$('#h .overlay .title').html(title);
			//Google Event tracking
			$('#h .overlay .play-big, .video-trigger').attr('onclick', "_gaq.push(['_trackEvent', 'Video', 'Play', '" + title + "']);");
		}
	}).slideshow({
		autoplay: true,
		autopause: true,
		interval: 8000,
		next: '.bg-next',
		prev: '.bg-prev'
	});

	$("#h .overlay .button.play-big, #h .video-trigger").click(function () {
		$(header).data("slideshow").stop();
		videoBase = $(header + ' a.current').attr('rel');
		$(overlayVideo).html(createVideo(videoBase, "640", "400", "true", "false")).show();
		$("#video, #video-bg").fadeIn();

		hideVid = function () {
			$(overlayVideo).html("").removeAttr("style");
			$(header).data("slideshow").play();
			$("#video, #video-bg").fadeOut();
		};

		$("#close-video, #video").click(function () {
			hideVid();
		});

		$('#video .content').click(function (event) {
			event.stopPropagation();
		});

	});
};

homeTyreHighlights = function () {
	var t = 0;
	$('#c .mid-banner').tabs('.tyre-spotlight > .item', {
		effect: 'fade',
		fadeInSpeed: t,
		fadeOutSpeed: t,
		rotate: true,
		onBeforeClick: function (event, tabIndex) {
			$('#c .mid-banner a').fadeOut(0).hide();
			$('#c .mid-banner a:eq(' + tabIndex + ')').fadeIn(0);
		}
	}).slideshow({
		autoplay: true,
		autopause: true,
		interval: 7000
	});
	$('#c .mid-banner > a').click(function () {
		document.location.assign($(this).attr("href")); //quick fix
	});
};

createVideo = function (videoBase, videoWidth, videoHeight, videoAutoplay, videoAutoBuffer) {
	var fileUrls = videoBase.split('|');
	var videoPoster = fileUrls[3],
		videoMP4 = fileUrls[0],
		videoOGG = fileUrls[1],
		videoWEBM = fileUrls[2],
		videoPath = '',
		videoFlashURL = '/_assets/js/video-js/player.swf',
		videoAllowFullscreen = 'true';

	var video = [];
	video.push(
		'<div class="content">',
		'<video id="header-video" width="' + videoWidth + '" height="' + videoHeight + '" poster="' + videoPath + videoPoster + '" controls preload autoplay>',
		'<source src="' + videoPath + videoMP4 + '" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\'>',
		'<source src="' + videoPath + videoWEBM + '" type=\'video/webm; codecs="vp8, vorbis"\'>',
		'<source src="' + videoPath + videoOGG + '" type=\'video/ogg; codecs="theora, vorbis"\'>',
		'<object id="player" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" name="player" width="' + videoWidth + '" height="' + videoHeight + '">',
		'<param name="movie" value="' + videoFlashURL + '" />',
		'<param name="allowfullscreen" value="true" />',
		'<param name="wmode" value="transparent" />',
		'<param name="allowscriptaccess" value="always" />',
		'<param name="flashvars" value="file=' + videoPath + videoMP4 + '&image=' + videoPath + videoPoster + '" />',
		'<embed type="application/x-shockwave-flash" id="header-video-flash" name="player2" src="' + videoFlashURL + '" width="' + videoWidth + '" height="' + videoHeight + '" allowscriptaccess="always" allowfullscreen="true"	flashvars="file=' + videoPath + videoMP4 + '&image=' + videoPath + videoPoster + '" wmode="transparent" />',
		'<p class="no-video">',
		'<strong>Download Video:</strong> ',
		'<a href="' + videoPath + videoMP4 + '">MP4</a> | ',
		'<a href="' + videoPath + videoWEBM + '">WebM</a> | ',
		'<a href="' + videoPath + videoOGG + '">Ogg</a>',
		'</p>',
		'</object>',
		'</video>',
		'<a id="close-video"></a>',
		'</div>'
	);
	return video.join('');
};

tyreCategorySelector = function () {

	var c = $('div.tyre-category-selector'),
		i = $('div.tyre-category-selector p'),
		iPadding = 15;

	var cWidth = c.width();
	c.css({ overflow: 'hidden' });
	var lasti = i.find('a:last-child');
	c.mousemove(function (e) {
		var iWidth = lasti[0].offsetLeft + lasti.outerWidth() + iPadding;
		var left = (e.pageX - c.offset().left) * (iWidth - cWidth) / cWidth;
		c.scrollLeft(left);
	});

	var detailItem = '.group.tyre-category-details .item',
		tyreItem = '.group.tyre-category-selector a.item';

	$(detailItem).hide().eq(0).show();

	$(tyreItem).hover(
		function () {
			$(detailItem).hide();
			var no = $(this).index();
			$(detailItem).eq(no).show();
		},
		function () {
			var no = $(this).index();
			$(detailItem).eq(no).show();
		}
	);

	var currentCat = $('h1 .category').html();
	$(tyreItem + " .title").each(function () {
		if ($(this).html() == currentCat) {
			$(this).parent(".item").addClass("current");
		}
	});

	if (IE) {
		$(tyreItem + " span.image").click(function () {
			url = $(this).parent("a").attr("href");
			document.location.assign(url);
		});
	}

};

highlightNav = function (id) {
	$("#nav li a:contains('"+id+"')").parent("li").addClass("current").append('<span class="r"></span>');
};

tyreCategory = function () {

	if ($("#tyre-tabs .default").length !== 0) {
		$(".tyre-tab").hide();
		$(".tyre-tab.default").show();
		$("#tyre-tabs .default").addClass("current");
	}
	else {
		$(".tyre-tab").show();
		$("#tyre-tabs li").eq(0).addClass("current");
	}
	if ($("#tyre-tabs li").length == 1) {
		$("#tyre-tabs li").addClass("single");
	}

	$("#tyre-tabs li").click(function () {
		var q = $(this).index();
		$(".tyre-tab").hide().eq(q).show();
		$("#tyre-tabs li").removeClass("current");
		$(this).addClass("current");
	});

};

maxxisSport = function () {

	//Carousel
	$("#carousel").waterwheelCarousel("horizontal", {
		startingItem: 7,
		itemDecreaseFactor: 0.60,
		itemSeperationFactor: 0.8,
		waveSeparationFactor: 0.2,
		centerOffset: 120,
		flankingItems: 2,
		speed: 320,
		animationEasing: 'easeOutCirc',
		opacityDecreaseFactor: 1,
		clickedCenter: function () {
			var centerElem = ".maxxis-sport #carousel img[~z-index=4]";
			if ($(centerElem).attr("rel")) {
				window.open($(centerElem).attr("rel"));
			}
			else {
				//No link
			}
		},
		movedToCenter: function () {
			/* FUTURE::

			$(".maxxis-sport #carousel img[~z-index=4]").hover(
				function () {
					$(this).css("cursor", "pointer");
				},
				function () {
					$(this).css("cursor", "default");
				}
			);
			*/
		}
	});

};


maxxisBabesOTR = function () {

	//Carousel
	var elems = ".maxxis-babes #carousel img",
		centerElem = elems + "[~z-index=4]";

	$("#carousel").waterwheelCarousel("horizontal", {
		startingItem: 4,
		itemDecreaseFactor: 0.60,
		itemSeperationFactor: 0.8,
		waveSeparationFactor: 0.2,
		centerOffset: 120,
		flankingItems: 2,
		speed: 320,
		animationEasing: 'easeOutCirc',
		opacityDecreaseFactor: 3,
		clickedCenter: function () {
			if ($(centerElem).attr("rel")) {
				window.open($(centerElem).attr("rel"));
			}
		},
		movedToCenter: function () {
		/*
			var i = $(centerElem).index(elems);
			if (i == 0 || i != $(elems).length - 1) {
				$(".nav-l,.nav-r").fadeIn("fast");
			}
			if (i == $(elems).length - 1) {
				$(".nav-r").fadeOut("fast");
			}
			if (i == 0) {
				$(".nav-l").fadeOut("fast");
			}
		*/
		}
	});

	//Carousel buttons
	/*
	$(".maxxis-babes").append('<div class="nav-l"/>');
	$(".maxxis-babes").append('<div class="nav-r"/>');
	$(".nav-l, .nav-r").show();
	*/
};


