/* Globals */
var didResize 				= false,
	$browserWindow 			= false,
	$contentWrapper			= false,
	$galleryLoader			= false,
	$recentlyViewedTarget 	= null,
	recentlyViewed			= false,
	homeHeroIndex			= 0,
	aboutIndex				= false;


/**
 * DOM Load
 */

$(document).ready(function() {
	
	Stockists()
	
	// Preload some important images
	var core = [];
		core.push(templateDir+"/i/x.gif");
		core.push(templateDir+"/i/prevnext2.png");
		core.push(templateDir+"/iprevnext.gif");
		core.push(templateDir+"/ibrochures.jpg");
		core.push(templateDir+"/ilogo.png");
		core.push(templateDir+"/isearchBtnBG.png");
		core.push(templateDir+"/iloader1.gif");
		core.push(templateDir+"/ii_reader.png");
		core.push(templateDir+"/ii/cross.png");
		core.push(templateDir+"/i/marker.png");
	$.imgpreload(core,{});
	
	$contentWrapper = $("#wrapper");
	$(window).mousemove(function(e){
		cursorPositionX = e.pageX;
		cursorPositionY = e.pageY;
	}).resize(function(){
		didResize = true;
	})
	layout();
	setInterval(function() {	
		if(didResize) {
	        didResize 			= false;	
			layout();
	    }
	}, 15);
	
	// Search form
	$("#searchForm").hover(function(){
		$(this).dequeue().stop().animate({width:"300px"},600,"easeOutCirc")
		$("#searchForm input").focus().select()
	},function(){
		$(this).delay(500).animate({width:"31px"},1000,"easeOutCirc")
	});
	
	

	// Gallery	
	$galleryWrapper = $("#largeImageWrapper");
	
	if($galleryWrapper.size()>0) {
		$productZoom 			= $("#productZoom")
		$galleryLoader = $('<img src="" alt="" style="display:none" id="galleryLoaderImage" />');
		$galleryWrapper.append($galleryLoader).hover(function(){ $productZoom.stop(true,true).show(); }, function(){ $productZoom.delay(500).fadeOut(500); })
		$('#galleryNav li:not(.videoThumb) a').live("click",function(){
			
			$("#videoHolder").empty().hide();
			
			
			$galleryLoader.stop(true,true);
			var href 	= $(this).attr("href");
			var zoom 	= $(this).attr("data-zoom");
			
			$('#galleryNav a').removeClass("selected");
			$(this).addClass("selected");
			$.imgpreload([href,zoom],{
				all: function() {
					$productZoom.css({"background-image":"url("+zoom+")"})
					$galleryLoader.attr("src",href).fadeIn(500,function(){
						$("#largeImage").attr("src",href);
						$galleryLoader.fadeOut(200)
					})		
				}
			});
			return false
		})
		
		$('#galleryNav li.videoThumb a').live("click",function(){
			$('#galleryNav a').removeClass("selected");
			$(this).addClass("selected");
			var vimeoID 	= $(this).attr("data-vimeo");
			$("#videoHolder").html('<iframe src="http://player.vimeo.com/video/'+vimeoID+'?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1" width="100%" height="100%" frameborder="0"></iframe>').show();		
			return false
		})
		
		
		$productZoom.mousemove(function(e){				
			cursorPositionX = e.pageX;
				cursorPositionY = e.pageY;
			var zoomOffset		= $productZoom.offset();
			var realX = cursorPositionX-zoomOffset.left;
			var realY = cursorPositionY-zoomOffset.top;			
			var realXPercentage = (realX/722)*100;
			var realYPercentage = (realY/511)*100;
			$productZoom.stop().animate({"background-position":  realXPercentage + "% " + realYPercentage + "%"},{duration: 600, easing: "easeOutCirc"});
		})
	}
	
	// Load .ldr images
	$(".ldr img").imgpreload({
		each: function() {				
			$(this).fadeIn(400);
			$(this).closest(".ldr").addClass("loaded");				
		}	
	});
	
	
	// Be inspired
	if($('.beInspired').size()>0) {
		var url = window.location.toString();
		if(/[#]/g.test(url)) {
			var hash = url.split("#show-")[1];
			$show = $("#"+hash);
			if(!$("#"+hash).size()>0) {
				$show = $(".beInspired:eq(0)");
			} 
		} else {
			$show = $(".beInspired:eq(0)");
		}
		$show.show();
		showCrosses($show.find(".points li"));
	}
	$('.beInspired').click(function(event){		
	     $(this).find(".points .info").hide();
			$(this).find(".cross").each(function(){
				$(this).closest("li").removeClass("active")
				circle($(this).find("span"),51)
			}).removeClass("active");
	 });
	$(".cross").hover(
		function() {			
			var span = $(this).find("span");			
			span.css({opacity:"1"}).animate({opacity:".7"},500)
			setTimeout(function(){
				circle(span,25.5)	
			},300)
			
		},
		function() {
			var span = $(this).find("span");
			span.css({opacity:".7"})
			if(!$(this).hasClass("active")) {
				circle(span,51)
			}			
		}
	).click(function(event){
		event.stopPropagation();
		if($(this).hasClass("active")) {
			$(this).closest("li").removeClass("active")
			var span = $(this).find("span");
			$(this).removeClass("active").closest("li").find(".info").fadeOut()
			circle(span,51)
		} else {
			$(this).closest("li").addClass("active")
			$(".cross").not($(this)).each(function(){
				$(this).closest("li").removeClass("active")				
				circle($(this).find("span"),51)
			}).removeClass("active");
			$(".points .info").hide();
			$(this).addClass("active").closest("li").find(".info").fadeIn()
		}
		
	})

	$(".beInspired .points .more").click(function(event){
		event.stopPropagation();
		var targ 	= $(this).attr("href"),
			parent	= $(this).closest(".beInspired");
		
			parent.find(".panel.open").animate({top:"400px"}).removeClass("open");
			$(targ).addClass("open").animate({top:"154px"});			
			parent.find(".cross").each(function(){
				$(this).closest("li").removeClass("active")
				circle($(this).find("span"),51);
			}).removeClass("active");
			parent.find(".points .info").hide();
			
		return false;
	})
	$(".beInspired .close").click(function(){
		var parent	= $(this).closest(".beInspired");
			parent.find(".panel.open").animate({top:"400px"}).removeClass("open")
	})
	$("#beInspiredNav a").click(function(){
		var targ 	= $($(this).attr("href")),
			current = $(".beInspired:visible");
			targ.find(".panel").css({top:"400px"})
		current.find(".points li").fadeOut();	
		current.fadeOut(1000);
		targ.fadeIn(1000,function(){
			showCrosses($(targ).find(".points li"));
		});
		return false;
	})
	
	$homeHero = $("#homeHero");
	if($homeHero.size()>0) {		
		$homeHero.find("h1").delay(500).fadeIn();
		$homeHero.find(".homeHeroPanel:eq(0)").delay(500).fadeIn(500)
		if($(".homeHeroPanel").size()>1) {
			$prev = $('<div id="homeHeroPrev" />');
			$prev.click(function(){
				prev = homeHeroIndex-1;
				if(prev<0) {
					prev = $homeHero.find(".homeHeroPanel").size()-1;
				}
				homeHeroIndex = prev;
				$homeHero.find(".homeHeroPanel:visible").stop(true,true).fadeOut();
				$homeHero.find(".homeHeroPanel:eq("+prev+")").fadeIn();
			});
			$next = $('<div id="homeHeroNext" />');
			$next.click(function(){
				next = homeHeroIndex+1;
				if(next>$homeHero.find(".homeHeroPanel").size()-1) {
					next = 0;
				}
				homeHeroIndex = next;
				$homeHero.find(".homeHeroPanel:visible").stop(true,true).fadeOut();
				$homeHero.find(".homeHeroPanel:eq("+next+")").fadeIn();
			});
			$homeHero.append($prev).append($next);
		}
	}
	
	
	if($("#aboutUsSlideshow li").size()>1) {
		if(!aboutIndex) {
			$("#aboutUsSlideshow li:eq(0)").delay(500).fadeIn(500);
			aboutIndex = 0;
		}
		setInterval(function(){
			next = aboutIndex+1;
			if(next>$("#aboutUsSlideshow li").size()-1) {
				next = 0;
			}			
			$("#aboutUsSlideshow li:visible").stop(true,true).fadeOut(1500);
			$("#aboutUsSlideshow li:eq("+next+")").fadeIn(1500);
			aboutIndex = next;
		},5000)
	} else {
		$("#aboutUsSlideshow li:eq(0)").fadeIn(1500);
	}
	
	
	recentlyViewedInit();
	
	$("#certificates img,#productFinishes img").tipTip({defaultPosition:"top"});
	
	$('a[rel=external]').live("click",function(){
		window.open($(this).attr('href'));
		return false;
	});
	
	if(Modernizr.rgba) {	
		$('#evilcredit').hover(function(){
			$(this).addClass("hover");
			spectrum();
		},function() {
			$(this).removeClass("hover");
			$('#evilcredit strong').stop().animate( { color: "#464a4a" }, {
				duration: 1000
			});
		})
	}
	
	
});


function showCrosses($crosses) {
	$crosses.each(function(i){
		$(this).stop().hide().delay(400*i).fadeIn(500);
	})
}


/**	
 * Set up recnetly viewed
 */
function recentlyViewedInit() {
	$recentlyViewedTarget 	= $("#recentlyViewed");
	
	if (Modernizr.localstorage) {
		
		var recentlyViewedState = localStorage.getItem("RecentlyViewedState");
			recentlyViewed 		= localStorage.getItem("RecentlyViewed");
		 		
		// Show recent history			
		if(recentlyViewed != null) {
			
			recentlyViewedState 	 	= recentlyViewedState==null ? "show" : recentlyViewedState;
			recentlyViewedButtonText  	= recentlyViewedState=="show" ? "Hide" : "Show";
			
			$recentlyViewedTarget.addClass(recentlyViewedState).html('<aside><div class="inner cfx"><h1>Recently Viewed</h1>'+recentlyViewed+'<div id="recentlyViewedButtons"><a href="#" class="btn" id="clearRecentlyViewed">Clear</a><a href="#" id="hideShowRecentlyViewed" class="btn">'+recentlyViewedButtonText+'</a></div></div></aside>');			
		} else {		
			$recentlyViewedTarget.remove();
			recentlyViewed = '<ol id="recentlyViewedList"></ol>';
		}
		
		$recentlyViewedTarget.show();
		
		layout();
		
		// Button events
		$("#clearRecentlyViewed").click(function(){
			localStorage.clear();
			$recentlyViewedTarget.animate({height:"0px"},{
				"duration":500,
				"step": function() {
					layout();
					},
				"complete": function() {
					$(this).empty();
					layout();
				}
			})
			return false;
		});	
	
		/* Show/Hide Recently viewed footer*/
		$("#hideShowRecentlyViewed").click(function() {
			if($recentlyViewedTarget.hasClass("show")) {
				$(this).text("Show");
				localStorage.setItem("RecentlyViewedState","hide");
				$recentlyViewedTarget.animate({height:"56px"},{
					"duration": 1000,
					"easing": "easeOutCirc",
					"step": function() {
						layout();
						},
					"complete": function() {					
						$recentlyViewedTarget.removeClass("show").addClass("hide");
						layout();
						}
				})				
			} else {
				$(this).text("Hide");
				localStorage.setItem("RecentlyViewedState","show");
				$recentlyViewedTarget.animate({height:"253px"},{
					"duration": 1000,
					"easing": "easeOutCirc",
					"step": function() {
						layout();
						},
					"complete": function() {
						$recentlyViewedTarget.removeClass("hide").addClass("show");
						layout();
					}
				})
				
			}
			return false;			
		});
		
		$("#recentlyViewed .ldr img").imgpreload({
			each: function() {
				$(this).fadeIn();
			}
		});	
	}
}



/**	
 * Target new windows
 */	
function addToRecentlyViewed(productData) {
	if (Modernizr.localstorage && recentlyViewed!=null) {		

		// Add this product to recent history		
		$recentlyViewedHTML = $(recentlyViewed)	;
		
		if($recentlyViewedHTML.find("li#product"+productData.id).size()==0) { // Don't add duplicates
			
			// Assemble HTML
			var newItemHTML = '<li id="product' + productData.id + '" class="recentItem'+(productData.fitted ? " fitted" : " standard")+'"><a href="' +productData.permalink+'"><span class="ldr"><img src="'+productData.thumb+'" alt="" /></span><ul><li>'+productData.price+'</li><li>'+productData.product_code+'</li><li>'+productData.title+'</li></ul></a></li>';	
						
			$recentlyViewedHTML.prepend($(newItemHTML));	
			
		}
		
		if($recentlyViewedHTML.find(".recentItem").size()>8) { // Max 8 items, delete last one	so we have room	
			$recentlyViewedHTML.find(".recentItem:last").remove();
		}
		
		localStorage.setItem("RecentlyViewed", "<ol id=\"recentlyViewedList\">" + $recentlyViewedHTML.html() + "</ol>")
			
	}
}
	



/**	
 * Target new windows
 */
function newWindowLinks(){
	$('a[rel=external],area[rel=external]').live("click",function(){
		window.open($(this).attr('href'));
		return false;
	});
}

// Main layout and resizing
function layout() {	
	var windowHeight	= $(window).height(),
		headerHeight 	= $("#header").height(),
		bottomHeight	= $("#bottom").height(),
		contentHeight	= $("#contentInner").outerHeight(),
		siteHeight 		= headerHeight+bottomHeight+contentHeight,	
		diff 			= windowHeight-headerHeight-bottomHeight;

	if(siteHeight<windowHeight) {
		$contentWrapper.css({"height":diff+"px"});
	} else {
		$contentWrapper.css({"height":"auto"});
	}
}


// Hide and show circle animations
function circle(obj,size) {
	pHeight = obj.height();
	obj.stop().animate({
			width:size+"px",
			height:size+"px"
			},{
			duration: 500,
			easing: "easeOutCirc",
		  	step: function(now, fx) {
				var adjustedMargin = now/2; 
				$(this).css({margin:"-"+adjustedMargin+"px"})
		  	}
	});	
}

/* Un-obfuscate email */
function fnE(inarr,text) {
	inarr = inarr.split(",");
	var out = "";
	for(i=inarr.length-1;i>=0;i--) {
		out += inarr[i];
	}
	if(text==false || text=="" || text==undefined) {
		text = out;
	}
	document.write('<a href="mailto:'+out+'" class="email">'+text+'</a>');
}


function jsdebug(message) {
	try {
		if(window.console) {
			console.log(message);			
		}
	} catch(e) {}	
}


function spectrum(){  
    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';  
	if($("#evilcredit").hasClass("hover")) {
	 	$('#evilcredit strong').animate( { color: hue }, {
			duration: 1000,
			complete: function() {
				spectrum();
			}
		});
	}      
}


function Stockists() {
	$("#stockistsForm,#stockistsBlock").submit(function(){
		var v = $("input[name='searchForStockists']").val();
		var ff	= $("#ff:checked").size();
		
		geocoder = new google.maps.Geocoder();		
		geocoder.geocode( { 'address': v + ", UK"}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var result = results[0].geometry.location;						 
		    	window.location = '/stockists?geocode='	+ result + '&ff=' + (ff==0 ? 'no':'yes') + "&searchstring=" + v;	
		  	} else {
				alert('We\'re sorry but we couldn\'t locate that address. Please try again.');
			}
		});
		
		/* if($('#latlng').size()>0) {
			$("#latlng").val(v)
		} else {
			$(this).append('<input type="text" value="'+v+'" name="latlng"  id="latlng" />')
		} */
		
		return false;
	})
}



