$(document).ready(function() {
	
	$("a.calculator").click(function() {
		
		var position = $(this).parent().parent().attr("id");
		var div = "div.wallpaper-calculator" + position;
		var popupHeight = $(div).height();  
		var popupWidth = $(div).width();  
		
		
		$(div).fadeIn();
		$("div#background").css("opacity", "0.5");
		var top = $("#content").height()/2-popupHeight/2;
		$(div).css("top", top);
		var left = $("#content").width()/2-popupWidth/2;
		$(div).css("left", left);
		$("div#background").fadeIn();  
		return false;
	});
	
	$("a.close").click(function() {
		var div = $(this).parent().parent();
		$(div).fadeOut();		
		$("div#background").fadeOut();
		$("div.buy").empty();
		$("div.save-room").css("display","none");
		return false;
	});
	
	$("a.close-wallpaper-cal").click(function() {
		var div = $(this).parent();
		$(div).fadeOut();		
		$("div#background").fadeOut();
		$("div.buy").empty();
		$("div.save-room").css("display","none");
		return false;
	});
	
	$("a.calculate").click(function() {
		var productId = $(this).parent().parent().children("#productId").val();
		var width = $(this).parent().parent().find("#wallWidth").val();
		var height = $(this).parent().parent().find("#wallHeight").val();
		var productPrice = $(this).parent().parent().children("#productPrice").val();
		
		calculate(productPrice, productId, width, height, true);
		
		return false;
	});
});

/**
 * Show an informational message
 */
function showMessage(message){
	$("#content div.message").html(message);
	$("#content div.message").css("display","block").fadeOut(6000);
}


function showStockNotificationMessage(response) {
	var html = "<div class=\"inner\"><a class=\"close\" href=\"#\"/><p>" + response.message + "</p></div>";
	$("#dialog").find("div.inner").replaceWith(html);
	
	$("#dialog").find("div.inner").find("a.close").click(function() {
		$("#dialog").fadeOut();
    	$("#background").fadeOut();
	return false;
	});
	return true;
}
function showAddedToRoomMessage(response) {
	var html = "<div class=\"message\">"+ Messages.get('product.added.project') +"</div>";
	$("div#content").prepend(html);
	$("div.message").fadeOut(1000);
}

function refreshRoomList() {
	if ($("ul.product-rooms").length === 0) {
		$("div.details div.inner").append("<div class='product-rooms'><h4>"+ Messages.get('your.rooms') +"</h4><div class='inner'><ul class='product-rooms'></ul></div></div>");
	}
	
	$("ul.room-list").load($.mapPath("room/userProjects",null,null,null) + " ul.room-list li.rooms", null, function() {
		bindRoomListControls();
	});
	
	$("ul.user-rooms").load($.mapPath("room/userRooms",null,null,null) + " li", null, function() {
		bindRoomListControls();
	});

	$("ul.product-rooms").load($.mapPath("room/productRooms?productId=" + $("meta[name=sku]").attr("content")) + " li", null, function() {
		if ($("ul.product-rooms li").length === 0) {
			$("div.product-rooms").remove();
		}
	});
	return false;
}

function bindRoomListControls() {
	$("a.edit-room").click(function() {	
		var id = $(this).attr("id");

		$("#dialog").popup({
			title: Messages.get('edit.project'),
			url:$.mapPath("room/edit?id=" + id + "&ajax=true"), 
			callback:function() {
				refreshRoomList();
				return false;
			}
		});
		
		return false;
	});

	$("a.delete-room").click(function() {	
		$.get($(this).attr("href") + "&ajax=true", function() {
				refreshRoomList();
			});
		
		return false;
	});
	
	$("a.add-product-to-room").click(function() {
		var roomId = $(this).attr("id");
		$("#dialog").popup({
			title: Messages.get('add.product.to.project'),
			url:$.mapPath("room/addProductItem?roomId=" + roomId + "&ajax=true"), 
			callback:function(response) {
				refreshRoomList();
				if(response.status == "success") {
					return false;
				}
				else {
					showStockNotificationMessage(response);
				}
			}
		});
		
		return false;
	});
	
	$("a.remove-product").click(function() {	
		$.get($(this).attr("href") + "&ajax=true", function() {
				refreshRoomList();
			});
		
		return false;
	});
	
	$("a.copy").click(function() {
		var productItemId = $(this).attr("id");
		var roomId = $(this).attr("rel");
		$("#dialog").popup({
			title: Messages.get('copy.product'),
			url:$.mapPath("room/copyMoveProduct?roomId=" + roomId + "&ajax=true&type=copy&productItemId=" + productItemId), 
			callback:function() {
				refreshRoomList();
				return false;
			}
		});
		return false;
	});
	
	$("a.move").click(function() {
		var productItemId = $(this).attr("id");
		var roomId = $(this).attr("rel");
		$("#dialog").popup({
			title: Messages.get('move.product'),
			url:$.mapPath("room/copyMoveProduct?roomId=" + roomId + "&ajax=true&type=move&productItemId=" + productItemId), 
			callback:function() {
				refreshRoomList();
				return false;
			}
		});
		return false;
	});
	
	$("ul.room-list").accordion({
		event: 'click',
		header: "h5",
		alwaysOpen: false,
		autoHeight: false
	});
}

$(document).ready(function() {
	
	
	$("h4.cant-find a.contact-form").click(function() {
		$("#dialog").popup({
			title: Messages.get('contact.us'),
			url:$.mapPath("contactForm/cantFindContactForm?ajax=true",null,null,null), 
			callback:function() {
				return false;
			}
		});

		return false;
	});

	$("a.add-room").click(function() {		
		$("#dialog").popup({
			title: Messages.get('add.project'),
			url:$.mapPath("room/create?ajax=true",null,null,null), 
			callback:function() {
				refreshRoomList();
				return false;
			}
		});
		
		return false;
	});
	
	$("a.reset").click(function() {
		var customerId = $(this).attr("rel");
		$("#dialog").popup({
			title: Messages.get('change.password'),
			url:$.mapPath("s/customer/resetPassword?customer=" + customerId + "&ajax=true"), 
			callback:function() {
				showMessage(Messages.get('password.changed'));
				return false;
			}
		});
		
		return false;
	});
	
	$("a.stock-notification").click(function() {
		var sku = $(this).attr("rel");
		$("#dialog").popup({
			title: Messages.get('stock.level.notice'),
			url:$.mapPath("product/emailNotification?sku=" + sku + "&ajax=true"), 
			callback:function(response) {
				showStockNotificationMessage(response);
			}
		});
		
		return false;
	});

	$("a.send-to-friend").click(function() {
		var sku = $("meta[name=sku]").attr("content");
		$("#dialog").popup({
			title: Messages.get('send.to.friend'),
			url:$.mapPath("product/sendToAFriendForm?sku=" + sku + "&ajax=true"), 
			callback:function(response) {
				showStockNotificationMessage(response);
			}
		});
		
		return false;
	});	
	
	$("select#roomId").change(function() {
		var sku = $("meta[name=sku]").attr("content");
		var roomId = $(this).val();
		var imageUrl = "";
		imageUrl = $("div.image").find("img.main-image").attr("src");
		$.get($.mapPath("room/addProduct?ajax=true&sku=" + sku + "&imageUrl=" + imageUrl + "&roomId=" + roomId), function(response) {
			refreshRoomList();	
			showAddedToRoomMessage(response);
		});
		
		return false;
	});	
	
	
	$("a.ask").click(function() {
		$("#dialog").popup({
			title: Messages.get('ask.question'),
			url:$.mapPath("faq/askQuestion?ajax=true",null,null,null), 
			callback:function(response) {						
				showStockNotificationMessage(response);
			}
		});
		
		return false;
	});	
	
	$("a.view-in-room").click(function() {
		var productItemId = $(this).attr("rel");
		$("#dialog").popup({
			title: Messages.get('view.in.room'),
			cssClass:'view-in-room',
			url:$.mapPath("viewInRoom/view?&ajax=true&sku=" + productItemId), 
			callback:function() {				
				return true;
			}
		});		
		
		return false;
	});
	
	$("a.fav").click(function() {
		var productItemId = $(this).attr("rel");
		$("#dialog").popup({
			title: Messages.get('view.in.room'),
			cssClass:'view-in-room',
			url:$.mapPath("viewInRoom/view?&ajax=true&sku=" + productItemId), 
			callback:function() {
				return false;
			}
		});
		return false;
	});
	
	$("ul.account-options").accordion({
		event: 'click',
		header: "h5",
		alwaysOpen: false,
		autoHeight: false
	});
	
	bindRoomListControls();
});


(function($) {
	$.mapPath = function(relativeUrl, site, pluginName, pluginVersion) {
		var url = "/";
		
		if (site == null || site === undefined){
			site = $.getSite();
		}

		if (site != null && site.length > 0 && window.location.href.indexOf("/" + site + "/") > 0) {
			url = "/" +  site + "/";
		}
		
		if (pluginName != null) {
			url += "plugins/" + pluginName;
			// our plugin version
			if (pluginName == 'grahambrown'){
				pluginVersion = '0.2';
			}
			if (pluginVersion != null) {
				url += "-" + pluginVersion + "/";
			}
			else {
				url += "-0.1/";
			}
		}

		return url + relativeUrl;
	};
	
	$.getSite = function(){
		var site = $("meta[name='site']").attr('content');
		if (site == null){
			return null;
		}
		if (site.charAt(site.length-1) == "/"){
			site = site.substring(0, site.length-1);
		}
		if (site.charAt(0) == "/"){
			site = site.substring(1);
		}
		return site;
	};

	$.fn.imageLoad = function(url, loading) {
		var preload = new Image();
		var image = this;
		
		$(preload).load(function() {
			$(loading).removeClass("loading");
			$(image).attr("src", url);
		});
		
		$(loading).addClass("loading");
		preload.src = url;
	};

	$.fn.rollover = function() {
		return $(this).each(function() {
			var src = $(this).attr("src");

			if (src) {
				var rolloverSrc = src.replace(/^(.*?)(\.(?:gif|jpg|png))$/, "$1_rollover$2");
				var preload = new Image();
				preload.src = rolloverSrc;

				$(this).hover(function() {
						$(this).attr("src", rolloverSrc);
					},
					function() {
						$(this).attr("src", src);
					});
			}
		});
	};

	$.fn.popup = function(options) {
		return $(this).each(function() {
			$(this).hide();

			var self = $(this);

			var defaults = {
					title: 'Dialog Title',
					show: function() {},
					callback: function() {},
					cancel: function() {},
					cssClass: ''
			};
			
			var opts = $.extend({}, defaults, options);
			var _callback = opts.callback;
			var _show = opts.show;
			
			// if we don't have a background to bind to, create it
			if ($("body").find("#background").length === 0) {
				$(this).before("<div id='background'></div>");
			}

			// load the form
			$.get(opts.url, function(data) {
				if (opts.cssClass !== "") {
					self.addClass(opts.cssClass);
				}
				else {
					self.attr("class", "");
				}

				self.find("div.inner").html($(data).children());
				self.find("h2").text(opts.title);
				self.find("input.rollover").rollover();
				self.find("a.close").click(function() {
        	self.fadeOut();
        	$("#background").fadeOut();
					
					opts.cancel();

					return false;
				});
				
				var form = self.find("form");
				
				if (form.length !== 0) {
					var action = $(form).attr("action");
					action += (/\?/.test(action) ? "&" : "?") + "ajax=true";
					
					$(form).validate({
						submitHandler: function(form) {	
							$(form).ajaxSubmit({
								url: action,
								dataType: "json",
								success: function(response) {
									// run the callback then hide the form
						          	_callback(response);
						          	if(_callback(response) === false){
						          		self.fadeOut();
						          		$("#background").fadeOut();
						          	}
						         }
							});
							return false; // <-- important!
						}
					});
				}

				// centre and resize the dialog
				var width = self.width();  
				var height = self.height();  
				
				var top = $(window).height()/2 - (height/2);
				var left = $(window).width()/2 - (width/2);
		
				if (self.css("position") == "absolute") {
					top = top + $(window).scrollTop();
				}
				
				self.css({top:top, left: left, zIndex: 10002});
				self.find("div.title").css("opacity", "0.8");
			
				// call event to do additional binding etc
				_show();
				
				self.fadeIn();

				if (form.length !== 0 && $(form).find("input[type=text]").get(0) != null) {
					$(form).find("input[type=text]").get(0).focus();
				}
				
				$("#background").css("opacity", "0.5");
				$("#background").fadeIn();
			});
		});
	};
})(jQuery);

$(window).load(function(){
	$("ul.image-list:not(.no-cycle)").cycle({"speed":0,"pause":1});
	$("#main-advert ul.image-list").cycle({"speed":2000, "pause":1});
	$("div.cycle").cycle({"speed":0,"pause":1});
});

$(document).ready(function() {
	// create the dialog box setup
	$("body").append("<div id='dialog'><div class='title'></div><h2>Dialog Title</h2><a href='#' class='close'></a><div class='inner'/></div>");
	
	$("body").append("<div id='speech-box'></div>");

	$('body').supersleight();
	
	if($("a.mail").length > 0){
		var mailname;
		var mailserver;
		var classes = $("a.mail").attr("class").split(" ");
		var i;
		var length;
		for (i = 0, length = classes.length; i < length; i++ ){
			if ( classes[ i ].indexOf("mailname") === 0){
				mailname = classes[ i ].substring(9,classes[ i ].length);
			}
			if ( classes[ i ].indexOf("mailserver") === 0){
				mailserver = classes[ i ].substring(11,classes[ i ].length);
			}
		}
		if(mailname !== undefined && mailserver !== undefined){
			var link = "mailto:" + mailname + "@" + mailserver;
			$("a.mail").attr("href", link);
			$("a.mail").text(mailname + "@" + mailserver);
		}
	}
	
	$("div#search-bar .popup-hover").hover(
		function(){
			$(this).addClass("hover");
			var top = $(this).position().top + $(this).height() + 1;
			var left = $(this).position().left - ($.browser.msie ? 1 : 10); // IE doesn't do rounded corners

			var popup = $(this).find(".popup");
			
			var width = popup.outerWidth();
			var height = popup.outerHeight();
			
			var html = "<iframe style='" + "filter:Alpha(Opacity=\"0\");" + "position:absolute;z-index:-1;top:0;left:0;width:" + width + "px;height:" + height + "px' />";
			
			popup.append(html);
			
			if ($(this).hasClass("last")) {
				popup.css("top", top).css("right", -1).show();				
			}
			else {
				popup.css("top", top).css("left", left < 0 ? 0 : left).show();
			}
			if($("div#shop-wallpaper ul.page-list").height() < $("div#shop-wallpaper ul.right-menu").height()){
				$("div#shop-wallpaper").height($("div#shop-wallpaper ul.right-menu").height()+5);
			}
		},
		function(){
			$(this).removeClass("hover");
			$(this).parent().find(".popup").hide();
			$(this).parent().find(".popup iframe").remove();
		});
	
		
	$("div div#selection").hover(function(){
		$(this).children("a").css("display", "block");
	},
	function(){
		$(this).children("a").css("display", "none");
	});
	
	$("a#close").click(function(){
		$(this).parents("div#warning").remove();			
		$("div#body-content").css("margin-top", "0px");
		return false;
	});
	
	$("input.rollover").rollover();

	$("ol.productResults li,ol.basketItems li").hover(function(){
			$(this).addClass("hover");
		},
		function(){
			$(this).removeClass("hover");
		});

	$("div.country_selector").hover(function(){
			$(this).find("div").show();
			$(this).addClass("flag_hover");
		},
		function(){
			$(this).find("div").hide();
			$(this).find("div.current").show();
			$(this).removeClass("flag_hover");
		});

	$("#navigation ul.more").each(function() {
		if ($(this).find("li:not(.empty)").length > 0) {
			$(this).before("<span class='more'>"+ Messages.get('more') +"</span>");
		}
	});

	$("#navigation ul.more").hide();

	$("#navigation ul li.facet").hover(
		function() {
			$(this).find("span.more").hide();
			$(this).find("ul.more").show();
		}, 
		function() {
			$(this).find("ul.more").hide();
			$(this).find("span.more").show();
	});
	
	$("#navigation ul li.facet ul li a").hover(
			function() {
				var position = $(this).offset();
				
				var html = $(this).parent().children("div.info").html();
				
				if (html) {
					$("#speech-box").html(html).css({top:position.top - 170, left:position.left + $(this).width()}).show();					
				}
			},
			function() {
				$("#speech-box").hide();
			});
	
	$("a.viewRange").click(function(){
		$("div#spotlight").height("110px");
		return false;
	});
	
	$("a.continue-shopping-back").click(function(){
		history.go(-1);
		return false;
	});
	
	//flash content 
	$(".video-content").each(function(){
		var self = $(this);
		var videoDiv = $(this);
		var video = $(this).find("a").attr("href");
		var image = $(this).find("img");
		var width = $(this).attr("content-width") + "px";
		var height = $(this).attr("content-height") + "px";

		var overlayImage = "images/overlay.png";
		var overlayHoverImage = "images/overlay-hover.png";

		if ($.browser.msie && $.browser.version == '6.0') {
			overlayImage = "images/overlay-ie.png";
			overlayHoverImage = "images/overlay-hover-ie.png";
		}

		$(this).append("<img src='" + $.mapPath(overlayImage, null,"grahambrown") + "' class='overlay'/>");
		var overlay = $(this).find("img.overlay");

		overlay.mouseover(function(){
			overlay.attr("src", $.mapPath(overlayHoverImage, null,"grahambrown"));
		});	

		overlay.mouseout(function(){
			overlay.attr("src", $.mapPath(overlayImage, null,"grahambrown"));
		});
		
		overlay.click(function() {
			videoDiv.flash({
				src: $.mapPath("flash/player.swf",null,"grahambrown"),
				width: width,
				height: height,
				flashvars: { file: video, autostart: 'true', skin: $.mapPath("flash/modieus.swf",null,"grahambrown")}
				}, null, null, function() {				
					self.addClass("no-flash");
				
					if (self.hasClass('no-flash')) {
						var message = '<p>Please install or upgrade your Flash Player to view content. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a></p>';
											
						if (self.find("img").length == 0) {
							self.addClass("no-placeholder");
							self.innerHTML(message);
						}
						else {
							self.append($(message));
						}
					}
				});	
			return false;
		});
		
		if(image.attr("src") == "") {
			$(this).flash({
				src: $.mapPath("flash/player.swf",null,"grahambrown"),
				width: width,
				height: height,
				flashvars: { file: video, autostart: 'false', skin: $.mapPath("flash/modieus.swf",null,"grahambrown")}
				}, null, null, function() {				
					self.addClass("no-flash");
					
					if (self.hasClass('no-flash')) {
						var message = '<p>Please install or upgrade your Flash Player to view content. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a></p>';
						
						if (self.find("img").length == 0) {
							self.addClass("no-placeholder");
							self.innerHTML(message);
						}
						else {
							self.append($(message));
						}
					}
				}
			);
		}
				
		image.click(function(){
			videoDiv.flash({
				src: $.mapPath("flash/player.swf",null,"grahambrown"),
				width: width,
				height: height,
				flashvars: { file: video, autostart: 'true', skin: $.mapPath("flash/modieus.swf",null,"grahambrown")}
				}, null, null, function() {				
					self.addClass("no-flash");
				
					if (self.hasClass('no-flash')) {
						var message = '<p>Please install or upgrade your Flash Player to view content. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a></p>';
						
						if (self.find("img").length == 0) {
							self.addClass("no-placeholder");
							self.innerHTML(message);
						}
						else {
							self.append($(message));
						}
					}
				});	
			return false;
		});	
	});	
	
	// flash adverts
	$(".flash-advert a").each(function() {
		var self = $(this);
		var target = $(this).attr("href");
		var image = $(this).find("img");
		var flash = $(this).attr("rel") || image.attr("src");
		var width = $(this).parent().attr("content-width") ? $(this).parent().attr("content-width") + "px" : "120px";
		var height = $(this).parent().attr("content-height") ? $(this).parent().attr("content-height") + "px" : "240px";
		$(this).flash({
			src: flash,
			width: width,
			height: height,
			flashvars : {clickTAG: target}
		}, null, null, function() {
				self.parent().addClass("no-flash");
			
				var message = '<p>Please install or upgrade your Flash Player to view content. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a></p>';
				
				if (self.parent().find("img").length == 0) {
					self.parent().addClass("no-placeholder");
					self.parent().innerHTML(message);
				}
				else {
					self.parent().append($(message));
				}
			}
		);
	});
	
	$('#content').supersleight({backgrounds: false, shim: $.mapPath("images/1x1.gif",null,"grahambrown",null)});
});


$(document).ready(function(){
	if ($("#locationInformation").length > 0 || $("#locationWarning").length > 0) {
		$("#wrapper").css("margin-top", "5.7em");
	}
	else {
		$("#wrapper").css("margin-top", "0");
	}
	
	$("#content #messages").css("display","none");
	
	splitMenu($("div#shop-wallpaper"));
	
	$("form#site-search input.text").focus(function() {
		clearText($(this), Messages.get('searchbar.text'));
	});
	
	$("form#site-search input#go").click(function() {
		clearText($("form#site-search input.text"), Messages.get('searchbar.text'));
	});
	
	function clearText(field, text){	
		
	    if (field[0].value == text) {
	    	field[0].value = '';
	    }
	}	
	
});

function getSplitPointIndex(elements) {	
	var size = elements.size();

	if (size < 2) {
		return -1;
	}
	
	var halfWay = Math.ceil(size / 2) - 1;

	while (halfWay >= 0) {
		var halfWayLi = $(elements[halfWay]);
		
		if (halfWayLi.hasClass("parent")) {
			return halfWayLi.parent().children("li").index(halfWayLi);
		}
		else {
			halfWay--;
		}	
	}
	return -1;
}

function splitMenu(menu) {
	var index = getSplitPointIndex(menu.find("li"));
	if (index != -1) {
		var rhsUl = $("<ul class='right-menu'/>").appendTo(menu);
		var list = menu.find("> ul");
		var items = list.children("li:gt(" + index + ")");
		items.appendTo(rhsUl);
		menu.css({'width':'38em'});
	}	
}

