var fadeDuration=1000;
var slideDuration=4000;
var currentIndex=1;
var nextIndex=1;

function nextSlide(){
	nextIndex =currentIndex+1;
	if(nextIndex> $('.imageFader a').length){
		nextIndex =1;
	}
	$("'.imageFader a:nth-child("+nextIndex+")'").addClass('show').animate({opacity: 1.0}, fadeDuration);
	$("'.imageFader a:nth-child("+currentIndex+")'").animate({opacity: 0.0}, fadeDuration).removeClass('show');
	currentIndex = nextIndex;
}
	
$(document).ready(function(){
	
	$("body").addClass("js");
	
	// Image loader
	$('img.lazy').jail({
		event: 'load'
		//timeout:3000
	});
	
	/*
	 * Jquery Tabs with Cookie
	 * @Author Ben Johnson
	*/
	var tab_cookie = window.location.hostname+"-tabs";
	var Cookie = $.cookie(tab_cookie); 
	var activeTab = '';
	var navIndex = '';
	$('.tab_content').children("div.tabs").hide();
	if (Cookie != "" && $('div'+ Cookie).length) {
		$('.tabs_nav a[href$="'+ Cookie+'"]').parent().addClass('active');
		$('.tab_content div'+ Cookie).fadeIn(100);
	}else {
		$(".tabs_nav li:first").addClass("active").show();
		$(".tab_content div:first").show();
	}
	$(".tabs_nav a, .tab_btn").click(function() {
		$(".tabs_nav li").removeClass("active");
		$(this).parent().addClass("active");
		$.cookie(tab_cookie, $(this).attr("href"));
		$('.tab_content').children("div").hide();
		$($(this).attr("href")).fadeIn(300);
		return false;
	});

	if ($('.imageFader a').length > 1) {
		$('.imageFader a').css({
			opacity: 0.0
		});
		$("'.imageFader a:nth-child(" + nextIndex + ")'").addClass('show').animate({
			opacity: 1.0
		}, fadeDuration);
		var timer = setInterval('nextSlide()', slideDuration);
	}
	
	$("a.fancy, a[rel=fancy]").fancybox({
		'transitionIn' : 'elastic',
		'transitionOut' : 'elastic'
	});
	$("a.fancy, a[rel=fancy]").append('<span class="enlarge_icon">&nbsp;</span>').hide().fadeIn('slow');
	
	$("a.termsPop").fancybox({
		scrolling: 'auto',
		height: 500
	});
	
	if($("#product_carousel ul").length > 0){
		$('#product_carousel ul').carouFredSel({
			direction	: "left",
			padding     : "0 33",
			scroll : {
				items			: 3,
				easing			: "easeOutQuart",
				duration		: 2000,
				pauseOnHover	: true
			},
			auto : {
				pauseDuration	: 6000,
				pauseOnHover	: true
			},
			prev : {
				button : "#feature_prev",
				key : "left"
			},
			next : {
				button : "#feature_next",
				key : "right"
			} 
		});
	}
	//Verticall Align Images inside of parent using margin-top
	//$("#product_carousel .image").vAlign();
	
	
	$(".brand_shop ul").liScroll();

	// Disable Right Click
	/* 
	 $(document).bind("contextmenu",function(e){
        return false;
    });
    */
	
	$(".btn_confirmorder, .sage, .paypal").click(function(e){
		var checked = $("#itermsandcondition").attr("checked");
		if(checked == false){
			e.preventDefault();
			alert("Please click to accept our Terms and Conditions");
		}
	});
	
	$(".openPopup").click(function(e){
		e.preventDefault();
		var url = $(this).attr("href");
		popUp(url);
	});
	
	// fix for target='_blank'
	$('a[href^="http://"], a[href^="https://"], .external').attr({
		target: "_blank"
	});	
	
	
	/**
	 *  Refresh Product Price based on Option 
	 */	
	var actual_taxrate = $("#taxrate").attr("value");
	
	$(".productOptions select").change(function(){		 
		var value = $(this).val();
		var price = $(this).find('option:selected').attr("rel") * ((actual_taxrate/100) + 1);		
		price = round(price, 2);
		

		// if "-- Select --"  then reset all productOptions and defaultPrice
		if (value == "") {					
			$(".productOptions select").each(function() {
				$(this).val( $('options:first', $(this)).val() );
			});
			
			price = $('#defaultPrice').attr("value");
			
			$("#rrp").show();
			$("#saving").show();
		} else {
			// do nothing
		}
		
		
		// Only apply if a price exists
		if (price > 0) {	
			$(".priceInfo span.price").html("&#163;" + price);	

			if (value != ""){
				$("#rrp").hide();
				$("#saving").hide();
			}
		}
	});
	
	
	/**
	 * Validate that ProductOption exists, check a selection has been made before Submit()
	 */ 
	$(".btn_orderthis").click(function(e) { 
		e.preventDefault();
		var options = $("#productOption_size").attr('value');
		if (options > 0) {
			var error = 0;
			$(".productOptions select").each(function() {
				if ($(this).val() == "") error = 1;
			});
		}
		
		if (error == 1) {
			alert("Please select an Option before adding this Product to basket");
		} else {
			$("#product").submit();
		}		
	});

	
	
	//img hover
	$(".hover").hover(function () {
		var filePath = $(this).attr("src");
		var dotPos = filePath.lastIndexOf(".") ;
		var extension = filePath.substr(dotPos,filePath.length);
		var newPath = filePath.replace(extension,"_on"+extension);
		$(this).attr("src",newPath);
	},function () {
		$(this).stop(true,false);
		$(this).attr("src", $(this).attr("src").split("_on.").join("."));
	});
	
		
	//product-pod hover
	/*$(".product-pod").hover(function () {
		$(this).addClass("hover");
	},function () {
		$(this).removeClass("hover");
	});*/

	$("input#copyaddress").click(function(){ 
        if ($("input#copyaddress").is(':checked')) 
        { 
            // Checked, copy values 
        	var name = $("input#Firstname").val() + ' ' + $("input#Surname").val();
            $("input#shipping-Name").val(name); 
            $("input#shipping-Telephone").val($("input#DaytimePhone").val()); 
            $("input#shipping-Address1").val($("input#Address1").val()); 
            $("input#shipping-Address2").val($("input#Address2").val()); 
            $("input#shipping-Town").val($("input#Town").val()); 
            $("input#shipping-County").val($("input#County").val()); 
            $("input#shipping-PostCode").val($("input#PostCode").val()); 
            //won't work on drop downs, so get those values
            var country = $("select#Country").val();
            $('select#shipping-Country option[value=' + country + ']').attr('selected', 'selected');
        } 
        else 
        { 
            // Clear on uncheck 
        	$("input#shipping-Name").val(""); 
        	$("input#shipping-Telephone").val(""); 
        	$("input#shipping-Address1").val(""); 
            $("input#shipping-Address2").val(""); 
            $("input#shipping-Town").val(""); 
            $("input#shipping-County").val(""); 
            $("input#shipping-PostCode").val(""); 
            // special for the select
            $('select#shipping-Country option[value=""]').attr('selected', 'selected');
        } 
    }); 

	if($(".validate").length) {
		$(".validate").validate({
			rules: {
				'clients.client_password.mirror': {
					minlength: 5,
					equalTo: "#password"
				},
				customerAgreements: "required"
			},
			messages: {
				'clients.client_password.mirror': {
					minlength: "Your password must be at least 5 characters long",
					equalTo: "Your password does not match"
				},
				customerAgreements: "Please accept our Terms and Conditions"
			}
		});
	}
	
	function navHoverOver(){
		var li = $(this);
		if($(li).find(".subNav").length > 0){
			$(li).addClass('over');
			$(li).find(".subNav").stop().fadeIn('fast').show();
		}
	}
	function navHoverOut(){ 
		$(this).removeClass('over');
		$(this).find(".subNav").stop().fadeOut(function() {
			$(this).hide(); 
		});
	}
	var config = {    
			sensitivity: 2,
			interval: 100,
			over: navHoverOver,   
			timeout: 500, 
			out: navHoverOut  
	};
	$("#mainav li").hoverIntent(config);
	
	$('.changeWin').change(function() {
		window.location = $(this).attr("value");
	});
	
	$('.cat-pod .image').each(function() {
		var oheight = $(this).children(0).height();
		var owidth = $(this).children(0).width();
		var nheight = (oheight + (oheight * 0.15));
		var nwidth = (owidth + (owidth * 0.15));
		var top = ((oheight - nheight) / 4);
		var left = ((owidth - nwidth) / 4);
		
		if($(this).children(0).height() > 0){
			$(this).mouseenter(function() {
				$(this).css('z-index', '10').children(0).stop().animate({
						'height' : nheight+'px',
						'width' : nwidth+'px',
						'left' : top+'px',
						'top' : left+'px'}, 210);
			});
	
			$(this).mouseleave(function() {
				$(this).children(0).stop().animate({
						'left' : '0px',
						'top' : '0px',
						'height' : oheight+'px',
						'width' : owidth+'px'}, 150, function() {
							$(this).css('height', oheight+'px').parent().css('z-index', '1');
						});
			});
		}
	});
		
		
	$("#submit_review").click(function(e) { 
		e.preventDefault();
		$("#add").attr('name', 'submit_review');   // Relabel "add" so Ecom/Frontend.php does not catch the Http_Request response
		$("#product").attr('action', document.URL);
		
		document.productFrm.submit();		
	});	
});


function popupWin (name, url, title, width, height, closemsg) {
	var popupwin = dhtmlwindow.open(name, "iframe", url, title, "width="+width+"px,height="+height+"px,resize=1,scrolling=1,center=1", "recal")
	
	var winname = eval('window.'+name);
	winname = popupwin;
	
	popupwin.onclose=function(){return window;}
}


/**
 * function to return rounded number by given decimal places
 * 
 * @param double n
 * @param integer dec
 */

function round(n, dec) {
	n = parseFloat(n);
	if(!isNaN(n)){
		if(!dec) var dec= 0;
		var factor= Math.pow(10,dec);
		return Math.floor(n*factor+((n*factor*10)%10>=5?1:0))/factor;
	}else{
		return n;
	}
}
