// *************************** jQuery Initialisation **************************** //


$(document).ready(function() {

	$('#toolbarcontrolsInner > a').click(function(){
		var thisIndex = $('#toolbarcontrolsInner > a').index( $(this) );
		var thisBar = $("#topBars > .bar:eq(" + thisIndex + ")");
		if( thisBar.is(":visible") ) {
			thisBar.slideUp("slow");
		} else {
			$("#topBars > .bar:visible").slideUp();
			thisBar.slideDown("slow");
		}
		return false;
	});

	// add the drop down menus to the DOM
	for(key in menu) {
		var str = '<div class="subMenu"><div class="subMenuInner">';
		var subMenu = menu[key];
		for(subKey in subMenu) {
			str += '<a href="' + subMenu[subKey] + '">' + subKey + '</a>';
		}
		str += '</div></div>';
		$("#" + key).append(str);
	}
	// show and hide the sub-menus on hover 
	$("#priNav .menu").hover( function () {
		$(this).find(".subMenu").show();
		t = $(this).find("img").attr("title"); // hide the images title as was
		$(this).find("img").attr("title", ""); // causing mouseout probs in safari
	}, function () {
		$(this).find(".subMenu").hide();
		$(this).find("img").attr("title", t); // restore the image title
	} );
	// add a hover class - because ie doesn't support 
	// css :hover styles on anything other than an anchor
	$("#priNav .menu .subMenu .subMenuInner a").hover( function () {
		$(this).addClass("hover");
	}, function () {
		$(this).removeClass("hover");
	} );
	// trigger the image hover on the parent menu image
	/* disabled - casuses flickering of sub-menu
	*/
	$("#priNav .menu .subMenu").hover( function () {
		$(this).prev("a").find("img").trigger('mouseover');
	}, function () {
		$(this).prev("a").find("img").trigger('mouseout');
	} );

	/* image hovers + preloading */
	$('#priNav img:not(.current)').imghover();
	$(".imghover").imghover();
	$("#changeCurrency img").imghover();
	$("#search_btn").imghover();
	$('.mailtoLink img').imghover();
	$('.viewNow img').imghover();
	$('.addToWishlist').imghover();

	// standard usage
	$('.mailto').mailtoObsfucator();
	$('.mailtoLink').mailtoObsfucator();

	/* homepage Top 5 */
	$('#homepageTopFive .top5:not(:first)').addClass('closed');
	$('#homepageTopFive .top5.open').click(function(){
		$('#homepageTopFive .top5.open').addClass('closed');
		$(this).toggleClass('closed', 'open');
	});

	/* product image thumbnails */
	$('#productPic #thumbs a').mouseover(function(){
		$('#productPic #thumbs a').removeClass('active');
		$('#mainPic').attr('src', $(this).attr('href') );
		$(this).addClass('active');
	});
	$('#mainPic').click(function() {
		$('#productPic #thumbs a.active').trigger('click');
	});
	

	/* product page tabbed panels */
	$("#productTabContainer > .tabContent:not(:first)").hide();
	$("#productTabContainer > .tabContent h3").hide();
	$("#productTabNav > a").click(function(){
		$("#productTabNav > a").removeClass('active');
		$(this).addClass('active');
		var thisIndex = $('#productTabNav > a').index( $(this) );
		var thisBar = $("#productTabContainer > .tabContent:eq(" + thisIndex + ")");
		if( thisBar.is(":visible") ) {
			thisBar.slideUp("slow");
		} else {
			$("#productTabContainer > .tabContent:visible").slideUp();
			thisBar.slideDown("slow");
		}
		return false;
	});
	$(".faqItem > a.question").click(function(){
		$(this).siblings(".answer").toggle();
		return false;
	});
	$("#atob_review").click(function(){
		$("#productTabNav > a:eq(1)").click();
		return true;
	});
	$("#atob_question").click(function(){
		$("#productTabNav > a:eq(2)").click();
		return true;
	});
	$("#atob_acessories").click(function(){
		$("#productTabNav > a:eq(0)").click();
		return true;
	});


	/* site search & google search */
	var searchType = "K";
	$("#search_ipt").focus(function(){
		$("#searchOptions").slideToggle();
		var v = $("#search_ipt").val();
		if( v == "keyword search..." || v == "enter product code..."){
			$("#search_ipt").val("");
		}
	});
	$("#search_ipt").blur(function(){
		$("#searchOptions").slideToggle(1150);
		var v = $("#search_ipt").val();
		if( v == ""){
			if(searchType == "K"){
				$("#search_ipt").val("keyword search...");
			} else if(searchType == "P"){ 
				$("#search_ipt").val("enter product code...");
			}else { 
				$("#search_ipt").val("");
			}
		}
	});
	$("#searchOptions a").click(function(){
		$("#searchOptions a").removeClass("active");
		$(this).addClass("active");
		return false;
	});
	$("#searchKeywords").click(function(){
		var v = $("#search_ipt").val();
		if( v == "" || v == "enter product code..." ){
			$("#search_ipt").val("keyword search...");
		}
		searchType = "K";
		$("#search").attr("action",relPath + "scripts/search.asp");
		$("#searchOptions").toggle();
	});
	$("#searchProductCode").click(function(){
		var v = $("#search_ipt").val();
		if( v == "" || v == "keyword search..." ){
			$("#search_ipt").val("enter product code...");
		}
		searchType = "P";
		$("#search").attr("action",relPath + "scripts/search_prod.asp");
		$("#searchOptions").toggle();
	});


	$('#navigation').fadeOut();
	$('#product').hover(function(){
		$('#navigation').fadeIn("slow");
	},function(){
		$('#navigation').fadeOut("slow");
	});

	jQuery(function($) {
		$("img[src$=png]").pngfix();
	});

	$(".snippet").hover(
		function(){ $(this).addClass("hover"); },
		function(){ $(this).removeClass("hover"); }
	);
	/*
	$(".snippet").click(function() { 
		window.location = $(this).find("h3 > a").attr("href"); 
		return false;
	});
	*/

	$(".listItem").hover(
		function(){ $(this).addClass("hover"); },
		function(){ $(this).removeClass("hover"); }
	);
	$(".listItem").click(function() { 
		window.location = $(this).find("h3 > a").attr("href"); 
		return false;
	});

	//Review Panel Display
	//References
	var linksToUse = $(".reviewLinks span");
	//Underline review action click links
	linksToUse.hover( function () {
		$(this).addClass("underline");
	}, function () {
		$(this).removeClass("underline");
	} );
	

	//Manage click events
	linksToUse.click(function(){
		var productId = document.getElementById("productReference").value;
		//load selected links
		switch(this.id){
			case "show3Reviews":
				var contentToReplace = $("#moreReviewsPanel");
				contentToReplace.slideUp();
				contentToReplace.load("../include/ajaxLoadReviews.asp", toggleReviews("Top3"));
				contentToReplace.slideDown();
				break;
			case "showAllReviews":
				var contentToReplace = $("#moreReviewsPanel");
				contentToReplace.slideUp();
				contentToReplace.load("../include/ajaxLoadReviews.asp?productId=" + productId, toggleReviews("All"));
				contentToReplace.slideDown();
				break;
			case "writeReview":
				var contentToReplace = $("#writeReviewPanel"); 
				contentToReplace.slideUp();
				contentToReplace.load("../include/ajaxWriteReview.asp?productId=" + productId + "&sectionId=" + document.getElementById("relationId").value + "&sectionType=" + document.getElementById("sectionType").value);
				contentToReplace.slideDown();
				break;
			default:
				break;
		}
	});

	// commented out until the affiliate scheme data is stored into the database 07/09/2010
	// setTimeout('toggleBetweenTheMailingListAndTheAffiliateSchemeBanner()', 4000);

	// Recently Viewed Products
	initQtip();


	$("#supportWidget div.title span").click(function(){
		// set a cookie to keep it hidden
		$.cookie('hideSupportWidget', 'TRUE');
		$("#supportWidget").remove();
	});


});




/* XMAS 2011 fake media queries */
function adjustStyle(width) {
	width = parseInt(width);
	var items = $("#xmasTL, #xmasTR");
	if (width > 1160) {
		items.show();
	} else {
		items.hide();
	}
}
$(function() {
	adjustStyle($(this).width());
	$(window).resize(function() {
		adjustStyle($(this).width());
	});
});
/* XMAS 2011 - END */




function toggleBetweenTheMailingListAndTheAffiliateSchemeBanner(){
	$('#mailinglistBanner').add('#affiliateSchemeBanner').toggle();
	setTimeout('toggleBetweenTheMailingListAndTheAffiliateSchemeBanner()', 4000);
}



// *************************** KP GALLERY SLIDESHOW v1.1 [START BLOCK] **************************** //

// NOTE this needs to be done on LOAD to ensure images are loaded last
$(window).load(function() {

	/* 
	 * Setup
	 * -----------------------
	 */
	// load images from the href's of the navigation
	$('#mainPicNav > div:not(:first)').each(function(){
		// extract the data we need to build the other headers
		var linkHref = $(this).children('a.link').attr('href');
		var imgSrc = $(this).children('a.pic').attr('href') + '?cb=050112';
		var imgAlt = $(this).children('a.pic').text();
		// clone the current header and change the relevant details
		$('#mainPicImg > a:first')
			.clone()
			.attr('href',linkHref)
			.children('img').attr({
				src: imgSrc,
				alt: imgAlt,
				title: imgAlt
			})
			.end()
			.removeClass("active")
			.appendTo('#mainPicImg');
	});
	// if there isn't an active class, add one onto the first item
	if ( $('#mainPicNav > div.active').length == 0 ) {
		$('#mainPicNav > div:first').addClass('active');
	}
	if ( $('#mainPicImg > a.active').length == 0 ) {
		$('#mainPicImg > a:first').addClass('active');
	}
	// bind click events to nav
	$('#mainPicNav > div > a.link').click(function() {
		thumbAction( $(this).parent('div') );
		return false;
	});

});


function thumbAction(jQ){
	// cancel timer and stop the auto rotation
	window.clearInterval(kpGalTimer);
	// find the position/order of the clicked nav-item
	var clickedIndex = $('#mainPicNav > div').index( jQ );
	// show the main item (also adds class to current nav)
	showImg( clickedIndex , 200);
	// prevent the link from working
	//return false;
}

/* 
 * findIndex()
 * ---------------------
 * returns the index of the main image with the class of current
 */
function findIndex() {
	// find the current active main image
	var currentNav = $('#mainPicImg > a.active');
	// find its position
	var currentIndex = $('#mainPicImg a').index( currentNav );
	return currentIndex;
}
/* 
 * nextImg()
 * ---------------------
 * finds the next image, and passes its index to showImg()
 */
function nextImg() {
	// find the current tab
	var currentIndex = findIndex();
	// find the next tab
	var nextIndex = currentIndex + 1;
	// if its passed the end, restart at the first one
	if(nextIndex >= $('#mainPicImg > a').length) {
		nextIndex = 0;
	}
	if(nextIndex == currentIndex) {
		// console.log('only 1 image found-killing rotation');
		window.clearInterval(kpGalTimer);
		return false;
	}
	// show the correct image
	showImg(nextIndex, 1000);
}
/* 
 * showImg(imgIndex)
 * ---------------------
 * displays the image and higlights the navigation at the position imgIndex
 */
function showImg(imgIndex, fadeSpeed) {
	// check if its already showing
	if( imgIndex == findIndex() ){
		// console.log('skipped showImg as this is already current');
		return false;
	}
	// un-hilight current nav
	$('#mainPicNav > div').removeClass('active');
	// hilight the current nav
	$('#mainPicNav > div:eq('+imgIndex+')').addClass('active');
	// grab references to the active and next-active images
	var $activeImg = $('#mainPicImg > a.active');
	var $nextImg = $('#mainPicImg > a:eq('+ imgIndex +')');
	// drop the active image to 2nd position in pile (nothing in top position)
	$activeImg.removeClass('active').addClass('last-active');
	// make the next image transparent
	// make it top of the pile
	// fade it up
	// remove the last active class
	$nextImg.css({opacity: 0.0})
		.addClass('active')
		.animate({opacity: 1.0}, fadeSpeed, function() {
			$activeImg.removeClass('last-active');
		});
}
// start the timer running
var kpGalTimer = setInterval("nextImg()",7500);

// *************************** KP GALLERY SLIDESHOW [END BLOCK] **************************** //

function initQtip() {

	$('#recentlyViewedProducts .recentlyViewedProduct').each( function() {

		// always apply the tooltip to the dd that is on top
		var content = $(this).find(".content").html();
		$(this).find("img").attr({"alt":"", "title":""});

		$(this).qtip({
			content: content,
			style: {
				name: 'dark',
				tip: true,
				width: 280
			},
			hide: {
				fixed: true // Make it fixed so it can be hovered over
			},
			position: {
				corner: {
					target: 'topMiddle',
					tooltip: 'bottomLeft'
				}
			}
		});
	});
}
