/* (c) 2011 Together London Limited */

$(function(){

	paypal_form = $("form#register_paypal");
	if(paypal_form.length)
	{
		$("body").addClass("scripted");
		paypal_form.submit();
		return;
	}

	collections_nav = $("<div></div>").attr({id: "collections_nav", 'class':"row"}).load("/collections_nav ul.print_list", function(responseText, textStatus, xhr){
		if(textStatus == "error")
			return;
		collections_nav = $(this).hide().wrapInner("<div></div>");
			
		$("div.bg_wrapper:first").after(collections_nav);		
		$("#navigation a[href='/collections']").click(function(){
			$(this).add("#navigation").toggleClass("highlighted");
			collections_nav.slideToggle("slow");			
			return false;
		});
		
	});
	$("#trolley_bar a").live("click", trolley_click);
	$("table.trolley input.remove").live("click", function(){
		$(this).closest("tr").find("input.quantity").attr({value:0});
		$(this.form).trigger("submit");		
	});
	$("#lightbox td.product a, #ajax_secondary ul.other_colours a").live("click", load_in_lightbox);	
	$("#ajax_wrapper form").live("submit", add_to_trolley);	
	$("#lightbox form a#add_more").live("click", close_lightbox);
	
	
	$(document).keyup(function(e) {
		if (e.keyCode == 27) { 
			// esc
			if($("#detail_overlay:visible").length)
				$("#detail_overlay").click();
			else
 				close_lightbox(e); 			
			}   
	})
	
	if ("pushState" in history)
	{
		$(window).bind("popstate", function(event){
			if(!event.originalEvent.state)
				return;
			if("collection" in event.originalEvent.state)
			{
				if ($("#lightbox:visible").length)
				{
					// hide lightbox
					$("#overlay,#lightbox").fadeOut(400, removeDiv);
					$("body").unbind("click", close_lightbox);
	
					$("ul.print_list li > a.selected").focus().removeClass("selected");					
				}
			}
			else if("anchor" in event.originalEvent.state)
			{				
				href = event.originalEvent.state.anchor + "?ajax=1 #ajax_wrapper > div";
				if ($("#lightbox:visible").length)
					$("#lightbox #ajax_wrapper").load(href, lightbox_load);
				else
				{
					lightbox = show_lightbox();
					lightbox.find("#ajax_wrapper").load(href, lightbox_load);
					lightbox.data("collection", {url: window.location.href, title:$("head title").text()});					
				}
					
			}
		});
		
	}
	
	if($("body#home").length)
	{		
		hero_load();
		collection_carousel_load();
	}		

	if($("body#about").length)
		hero_load();

	if($("body#checkout").length)
		checkout_init();
	
	if($("body#product_detail").length && ("pushState" in history))
		product_lightbox_load();
});


function trolley_click()
{
	lightbox = show_lightbox();
	
	lightbox.find("#ajax_wrapper").load($(this).attr("href") + "?ajax=1 #ajax_wrapper > div", trolley_load);
	return false;
}

function hero_load()
{
	carousel = $("ul#hero_list");
	autoplay = carousel.hasClass("autoplay");
	
	if (carousel.length)
	{
		width = 0;
		carousel.find("li > img").each(function(){
			width += $(this).width();
		});		
		
		carousel.css({width: width}).wrap($("<div><div></div></div>").attr({"class":"carousel_wrap"}));
		
		if(autoplay)
			carousel.data("intervalID", setInterval(hero_next, 5000));
		else carousel.closest("div.carousel_wrap").append($("<a><span>next</span></a>").attr({"class":"nextArrow", href:"#"}).click(hero_next))
			.append($("<a><span>previous</span></a>").attr({"class":"prevArrow disabled", href:"#"}).click(hero_prev));				

		carousel.data({current_item: carousel.find("li:first") });		
	}
}

function collection_carousel_load()
{
	carousel = $("ul#collections_carousel");
	if (carousel.length)
	{
		width = 0;
		carousel.find("li").each(function(){
			width += $(this).outerWidth();
		});		
		
		carousel.css({width: width}).wrap($("<div><div></div></div>").attr({"class":"carousel_wrap"}));
		
		carousel.closest("div.carousel_wrap").append($("<a><span>next</span></a>").attr({"class":"nextArrow", href:"#"}).click(collections_next))
			.append($("<a><span>previous</span></a>").attr({"class":"prevArrow disabled", href:"#"}).click(collections_prev));				

		carousel.data({current_item: carousel.find("li:first") });
	}
}

function collections_next(event)
{
	step = 415; // px
	
	list = $("ul#collections_carousel");
	last = list.find("li:last");
	
	if(-(list.position().left - step) < (last.position().left - last.width()))
		$("ul#collections_carousel").animate({left: "-="+ step + "px"}, 300, function(){
			if(-(list.position().left - step) > (last.position().left - last.width()))
				$("#collections a.nextArrow").addClass("disabled");			
		});	

	$("#collections a.prevArrow").removeClass("disabled");
	
	return false;
}


function collections_prev(event)
{
	step = 415; // px
	
	list = $("ul#collections_carousel");
	last = list.find("li:last");
	
	if(list.position().left == 0)
		return false;	
	if(list.position().left + step >= 0)
	{
		left = "0px";
		$("#collections a.prevArrow").addClass("disabled");		
	}
	else
		left = "+=" + step + "px";
	
	$("ul#collections_carousel").animate({left: left}, 300);

	$("#collections a.nextArrow").removeClass("disabled");

	return false;
}



function hero_next(event)
{
	carousel = $("ul#hero_list");
	autoplay = carousel.hasClass("autoplay");	
	current = carousel.data("current_item");
	image = current.find("img");
	
	if(current.is(":last-child"))
		return false;		

	dimensions = {width:image.width(), height:image.height()};
	step = current.width();
	
	current = current.next();
	
	carousel.animate({left: "-=" + step + "px"}, 500);	
	carousel.data({current_item: current, previous_dimensions: dimensions});
	
	$("#hero a.prevArrow").removeClass("disabled");
	if(current.is(":last-child"))
	{
		if(autoplay)
		{
			clearInterval(carousel.data("intervalID"));
			setTimeout(function(){
				carousel.animate({left: "0px"}, 1000, "swing", function(){					
					carousel.data({
						current_item: carousel.find("li:first"),
						intervalID: setInterval(hero_next, 5000)
					});					
				});
			}, 5000);
		}
		else $("#hero a.nextArrow").addClass("disabled");				
	}

	
	return false;	
}

function hero_prev(event)
{
	carousel = $("ul#hero_list");
	current = carousel.data("current_item");
	image = current.find("img");
	
	if(current.is(":first-child"))
		return false;
		
	dimensions = {width:image.width(), height:image.height()};			
	current = current.prev();

	step = current.width();
	
	carousel.animate({left: "+=" + step + "px"}, 500);	
	carousel.data({current_item: current, previous_dimensions: dimensions});
	
	$("#hero a.nextArrow").removeClass("disabled");	
	if (current.is(":first-child"))
		$("#hero a.prevArrow").addClass("disabled");			
	
	return false;	
}

function lightbox_next(event)
{
	carousel = $("#ajax_primary ul.carousel_list");
	current = carousel.data("current_item");
	image = current.find("img");
	
	if(current.is(":last-child"))
		return false;		

	dimensions = {width:image.width(), height:image.height()};
	step = current.width();

	delta_width = current.next().width() - dimensions.width;
	$("#lightbox").animate({width: "+=" + delta_width}, 500);

	carousel.animate({left: "-=" + step + "px"}, 500);	
	carousel.data({current_item: current.next(), previous_dimensions: dimensions});

	resize_lightbox();
		
		
	
	
	return false;	
}

function lightbox_prev(event)
{
	carousel = $("#ajax_primary ul.carousel_list");
	current = carousel.data("current_item");
	image = current.find("img");
	
	if(current.is(":first-child"))
		return false;
		
	dimensions = {width:image.width(), height:image.height()};			
	current = current.prev();

	step = current.width();
	delta_width = step - dimensions.width;
	$("#lightbox").animate({width: "+=" + delta_width}, 500);
	
	
	carousel.animate({left: "+=" + step + "px"}, 500);	
	carousel.data({current_item: current, previous_dimensions: dimensions});

	resize_lightbox();
	
	return false;	
}



function show_lightbox()
{
	if($("#lightbox").length)
		return $("#lightbox");

	deep_link = ($("body#product_detail").length > 0); // direct link to product
	
	body = $("body");
	overlay = $("<div></div>").attr("id", "overlay").css({height:$("body").height()}).hide();
	lightbox = $("<div></div>").attr("id", "lightbox").hide();

	offset = $(window).scrollTop();
	offset += 5;
	
	lightbox.css({top: offset + "px"});
	
	body.append(overlay);	

	if(!deep_link)
	{
		overlay.fadeIn(300, function(){
			lightbox.fadeIn(300);
		});
	}

	wrapper_div = $("<div></div>").attr({id: "ajax_wrapper", "class": "row"});
	lightbox.append(wrapper_div);

	// close button
	body.click(close_lightbox);
	
	close_link = $("<a><span>close</span></a>").attr({id: "lightbox_close", href:"#", title:"close"}).click(close_lightbox);
	lightbox.append(close_link);

	// progress indicator
	
	lightbox.ajaxStart(function(event){
		$(this).addClass("loading");
		$(this).append($("<div></div>").attr({id:"loading_indicator"}));
	}).ajaxStop(function(event){
		$(this).removeClass("loading");
		$(this).find("#loading_indicator").remove();
	});
	
	
	overlay.append(lightbox);	
	
	if(deep_link)
	{
		overlay.show();
		lightbox.show();
	}
	
	return lightbox;
}


function lightbox_load()
{	
	// carousel
	
	carousel = $("#ajax_primary ul.carousel_list");
	if (carousel.length)
	{
		width = 0;
		carousel.find("li img").each(function(){
			width += $(this).width();
		});
		
		carousel.css({width: width}).wrap($("<div><div></div></div>").attr({"class":"carousel_wrap"}));
		
		carousel.closest("div.carousel_wrap").append($("<a><span>next</span></a>").attr({"class":"nextArrow", href:"#"}).click(lightbox_next))
			.append($("<a><span>previous</span></a>").attr({"class":"prevArrow", href:"#"}).click(lightbox_prev));				

		carousel.data({current_item: carousel.find("li:first") });		
		resize_lightbox();
	}
	
	
			
	// detail view (magnifier)


	detail_links = $("#ajax_primary ul.detail_links");
	if(detail_links.length)
	{
		$("#ajax_primary ul.carousel_list img.product").click(load_detail_overlay);
		detail_links.hide();
	}
	
	$.getScript("http://platform.twitter.com/widgets.js");
}


function resize_lightbox()
{	
	lightbox = $("#lightbox");
	carousel = $("#ajax_primary ul.carousel_list");	
	image = carousel.data("current_item").find("img");


	image_width = parseInt(image.attr("width"));

	carousel.height(image.height()+20);


	// centering is complicated because of timing
	// but hoiriz. centring now handled in CSS
	
	viewport_height = $(window).height();
	window_offset = $(window).scrollTop();
		
	if(!carousel.data("previous_dimensions")) // first time
	{
		$("#ajax_primary").width(image_width);
		lightbox.width(image_width +  220 + 45);
	
		lightbox_height = lightbox.height();
		lightbox_width = lightbox.width();
	
		
	}
	else // transition
	{
		$("#ajax_primary").animate({width:image_width}, 500);

		previous_dimensions = carousel.data("previous_dimensions");
		delta_y = image.height() - previous_dimensions.height;		
		delta_x = image.width() - previous_dimensions.width;
		
		lightbox_height += delta_y;
	}
	

	if(lightbox_height >= viewport_height)
		lightbox_top_offset = window_offset + 5;
	else
		lightbox_top_offset = window_offset - 10  + parseInt((viewport_height - lightbox_height) / 2);


	lightbox.animate({top: lightbox_top_offset + "px"}, 500);
	
	prevArrow = $("#ajax_primary a.prevArrow");
	nextArrow = $("#ajax_primary a.nextArrow");
	current = carousel.data("current_item");
	
	if(current.is(":first-child"))
	{
		prevArrow.addClass("disabled");
		if(!current.is(":last-child"))
			nextArrow.removeClass("disabled");
		else
			nextArrow.addClass("disabled"); // single image
	}
	else if(current.is(":last-child"))
	{
		prevArrow.removeClass("disabled");
		nextArrow.addClass("disabled");		
	}
	else
	{
		nextArrow.removeClass("disabled");
		prevArrow.removeClass("disabled");		
	}

}

function load_in_lightbox(event)
{
	anchor = $(this);
	state = {anchor:anchor.attr("href")};
	history.pushState(state, $("#lightbox h1:first").text(), anchor.attr("href"));


	$("#lightbox #ajax_wrapper").load(anchor.attr("href") + "?ajax=1 #ajax_wrapper > div", lightbox_load);
	return false;
}

function close_lightbox(event)
{	
	if ("keycode" in event && event.keyCode == 27) // esc
	{
		if (!$("#lightbox:visible"))
			return true;		
	}
	else
	{
		// close lightbox if click came from outside the lightbox or from the close button
		target = $(event.target);

		if(target.attr("id") != "lightbox_close" && target.attr("id") != "add_more" && target.parents("div#lightbox").length)
			return true;		
	}

	collection = $("#lightbox").data("collection");

	$("#overlay,#lightbox").fadeOut(400, removeDiv);
	$("body").unbind("click", close_lightbox);
	
	$("ul.print_list li > a.selected").focus().removeClass("selected");
	
	if(collection)
		history.pushState({collection: collection}, collection.title, collection.url );
	
	return false;
}

function removeDiv()
{
	$(this).remove();
}

function add_to_trolley(event){
	event.preventDefault();
	
	form = $(this);
	lightbox = show_lightbox();

	$.post(form.attr("action")+"?ajax=1", form.serialize(), function(content){
		$("#lightbox #ajax_wrapper").replaceWith(content);
		trolley_load();
	});
	return false;	
}

function trolley_load()
{
	primary_width = $("#ajax_primary").width();
	if(primary_width == 0) // not yet loaded
	{
		lightbox.width(720);
		setTimeout(resize_trolley, 400);
	}
	else
		resize_trolley();

	trolley_link = $("#lightbox #ajax_wrapper div.trolley_link").remove();
	$("#trolley_bar a").replaceWith(trolley_link.find("a"));	
}

function resize_trolley()
{
	lightbox.animate({width: $("#ajax_primary").width() + 20}, 300);					
}

function thumbnail_click()
{
	if (!("pushState" in history))
		return true; // no ajax


	anchor = $(this);
	anchor.addClass("selected");
	lightbox = show_lightbox();
	
	lightbox.find("#ajax_wrapper").load(anchor.attr("href") + "?ajax=1 #ajax_wrapper > div", lightbox_load);
	
	lightbox.data("collection", {url: location.href, title:$("head title").text()});
	
	state = {anchor:anchor.attr("href")};
	history.pushState(state, anchor.closest("li").find("span.title").text(), anchor.attr("href"));
	
	return false;
}


function load_detail_overlay(event){
	image = $("<img>").attr({src:detail_links.find("a:first").attr("href")});
	detail_overlay = $("<div></div>").attr({id: "detail_overlay"}).append(image).click(kill_detail_overlay).hide();
	
	$("body").append(detail_overlay);
	
	image.draggable({snap: "#detail_overlay"});

	$("#overlay,#lightbox, #wrapper, #navigation, div.bg_wrapper").hide();
	$("html").addClass("detail_overlay");
	
	detail_overlay.fadeIn(function(){
		message = $("<div>Drag the image, or click anywhere to close.</div>").attr({id:"message"}).hide();
		$(this).append(message);
		message.fadeIn();
		setTimeout(function(){
			message.fadeOut();
		}, 4000);
		
	});
	return false;
	
}


function kill_detail_overlay()
{
	$("html").removeClass("detail_overlay");
	$("#overlay,#lightbox, #wrapper, #navigation, div.bg_wrapper").show();
	$(window).scrollTop(offset);
	$(this).fadeOut(removeDiv);
	return false; // don't bubble
}

function checkout_init()
{
	$("#primary table.trolley").wrap($("<div></div>").attr({id:"trolley_wrap"}).hide());
	
	show = $("<a>Show order details.</a>").attr({href:"#"}).click(function(){				
		wrap = $("#trolley_wrap");
		if(wrap.is(":visible"))
			$(this).text("Show order details.");	
		else
			$(this).text("Hide order details.");				
		wrap.slideToggle();				
		return false;
	});
			
	
	$("p.summary").append(show);
}

function product_lightbox_load()
{
	lightbox = show_lightbox();
	
	lightbox.find("#ajax_wrapper").append($("#primary").clone().attr({id: "ajax_primary"})).
			append($("#secondary").clone().attr({id: "ajax_secondary"}));
			
	// $("#primary,#secondary").empty();			
	lightbox_load();
	
	collection_link = $("#ajax_secondary #product_collections ul a:first"); 
	collection_url = collection_link.attr("href");
	collection_name = collection_link.text();
	
	$("#wrapper").load(collection_url + " #primary", collection_layout);
	
	
	lightbox.data("collection", {url: collection_url, title:collection_name});
	
	state = {anchor:location.href};	
	history.replaceState(state, $("#ajax_primary h1").text(), location.href);	
	$("body").attr({id: "collection_detail"});	
}



