window.addEvent("domready", function() {
	ajaxCartFx = new Fx.Slide($("cart-items"), {
		hideOverflow : false
		//resetHeight : true	
		});
	ajaxCartFx.element.setOpacity(0)
	// Load the cart
	getCartSummary(true)
	
	// Hide the login window
	$("my-account").getFirst("div").setStyles({
		"opacity":0,
		"display":"none"
		});
	
	if ($("login-failed")) {
		$("login-failed").tween("opacity", 0)
		}
	
	new Element("li", {"class":"facebook-link"}).set("html", "<a target=\"_blank\" href=\"http:\/\/www.facebook.com\/pages\/Beauty-Enhanced\/145894262100205\"><img src=\"\/storage\/images\/facebook-nav-icon.png\" /></a>").inject($("main-menu"));
	
	$(document).addEvent("click", function (ev) {
		//console.log(ev.target)
		
		//$("my-account").getFirst("div").fade("out");
		})
	
	
	$$("input.pre-text").each(
		function (element, indx, array) {
			element.addEvent("blur", function () {
				if(element.get("value") == "" || element.get("value") == element.get("title")) {
					element.addClass("empty");
					element.set("value", element.get("title"))
					}
				});
			element.addEvent("focus", function () {
				element.removeClass("empty");
				if(element.get("value") == "" || element.get("value") == element.get("title")) {
					element.set("value", "");
					}
				});
			element.fireEvent("blur")
			}
		);
	
	
	});

function getCartSummary(init) {
//	console.log(init)
	if (!init) init = false;
	new Request.JSON({
		url : "/viewmodes/shop/ajax/add-to-basket.cfm",
		onSuccess : function (jsonResponse) {
			refreshCartSummary(jsonResponse);
			if (init) {
				//console.log("hiding")
				ajaxCartFx.hide();
				ajaxCartFx.element.setOpacity(1)
				}
			}
		 
		}).get()
	}
	
function setDelivery(obj) {
	formObj = obj.form;

	if (obj.checked) {
		formObj.delivery_address.value = formObj.address.value;
		formObj.delivery_suburb.value = formObj.suburb.value;
		formObj.delivery_postcode.value = formObj.postcode.value;
		formObj.delivery_state.value = formObj.state.value;
		formObj.delivery_contactnumber.value = formObj.contactnumber.value;
		formObj.delivery_country.value = formObj.country.value;
		}
	else {	
		formObj.delivery_address.value = "";
		formObj.delivery_suburb.value = "";
		formObj.delivery_postcode.value = "";
		formObj.delivery_state.value = "";
		formObj.delivery_contactnumber.value = "";
		formObj.delivery_country.value = "";
		}
	}
function refreshCartSummary(json) {
	if (!json) {
		getCartSummary();
		}
	else {
		// Update the cart summary info
		$("cart-items").getFirst("div").set("html", json.HTML);
		$("cart-summary").getElement("span[class=qty]").set("text", Math.round(json.QTY));
		$("cart-summary").getElement("span[class=total]").set("text", json.TOTAL);
		
		// Add event to remove the product item from the cart
		$("cart-items").getFirst("div").getElements("div[class=remove]").getElement("a").addEvent("click", function (ev) {
			ev.stop();
			var json = JSON.decode(this.getParent("li").get("rel"));
			new Request.JSON({
				url : "/viewmodes/shop/ajax/remove-from-basket.cfm",
				onSuccess : function (jsonResponse) {
					refreshCartSummary(jsonResponse);
					}
				}).get("basketitemid=" + json.basketitem)
			});
			
		// Show the product info from the cart	
		$("cart-items").getFirst("div").getElements("div[class=info]").getElement("a").addEvent("mouseover", function (ev) {
			ev.stop()
			if (!this.getElement("div")) {
				var json = JSON.decode(this.get("rel"));
				new Element("div").set("html", "<h3>" + json.PRODUCTNAME + "</h3><div><dl><dt><img src=\"" + json.IMG + "\" /><p><b>Cost : </b>" + json.PRICE + "<br /><b>Weight : </b>" + json.WEIGHT + "<br /><b>Qty : </b>" + json.QTY + "</p></dt><dd><p>" + json.DESCRIPTION + "</p></div>").inject(this);
				}
			});
		// Hide the product info from the cart
		$("cart-items").getFirst("div").getElements("div[class=info]").getElement("a").addEvent("mouseout", function (ev) {
			ev.stop();
			this.getElement("div").dispose();
			
			});
		}
	}


function addProductToBasket(ev) {
	ev.stop();
	
	var f = this;
	var submitBtn = f.getElement("input[type=submit]");
	
	//var hasOptions = (submitBtn.get("rel") ? (JSON.decode(submitBtn.get("rel")).hasOptions) : null);
	if (f.hasOptions) {
		if (f.hasOptions.value == "true") {
			f.getElement("a[class=more-info]").fireEvent("click");
			return;
		}
	}
	if(f.getElement("div[class=product-added-notice]")) f.getElement("div[class=product-added-notice]").dispose();
	var submitBtnLocation = submitBtn.getCoordinates(f);
	var notice = new Element("div", {"class":"product-added-notice"}).set("html", "<br />...Processing...").setOpacity(0).inject(f.getElement("input[type=submit]").getParent());
	notice.setStyles({
	//	"top" : (submitBtnLocation.top - submitBtnLocation.height) - ( notice.getSize().y),
	//	"left" : submitBtnLocation.left - (Math.max(submitBtnLocation.width, notice.getSize().x) - Math.min(submitBtnLocation.width, notice.getSize().x))/2,
		"top" : (notice.getSize().y)* -1,
		"left" : ((Math.max(submitBtnLocation.width, notice.getSize().x) - Math.min(submitBtnLocation.width, notice.getSize().x))/2)*-1,
		});
	notice.fade("in");
	this.set("send", {
		url: "/viewmodes/shop/ajax/add-to-basket.cfm",
		onSuccess : function (responseText) {
			$("cart-summary").getElement("div").pulse({pulses : 3});
			refreshCartSummary(JSON.decode(responseText));
			
			notice.set("html", "This item has been added to your shopping cart");
			(function(){new Fx.Morph(notice, {onComplete: function(){this.dispose()}.bind(this)}).start({"opacity": 0})}).delay(3000, notice)
			}
	
		})
	
	this.send()
	}
window.addEvent("load", function() {
	
	// products buy button
	$$("form.buy-now-form").addEvent("submit", addProductToBasket);
	
	$$("form.buy-now-form").getElement("a[class=more-info]").addEvent("click", function (ev) {
		if(ev) ev.stop();
		productDetailOverlay = new Overlay({
				title	: this.getParent("li").getElement("h3").get("text"),
				type 	: "panel",
				size 	: "xlarge",
				url 	: "/viewmodes/shop/product-detail.cfm?id=" + this.getParent("form").getFirst("input").get("value"),
				buttons	: [{label:"Close",id: "close-mask"}], //,{label:"Print",id:"print-mask"}
				onComplete : function () {
						// Google Analytics Tracking of products pages
						if(_gaq) _gaq.push(['_trackPageview', this.href]);
						
						$("site-mask").getElements("form").addEvent("submit", addProductToBasket);
						$("site-mask").getElements("a[class=more-info]").addEvent("click", function (ev) { 
							ev.stop();
							//console.log(this.getParent("li").getElement("h3").get("text"))
							productDetailOverlay.reloadURL({
									title	: this.getParent("li").getElement("h3").get("text"),
									url 	: "/viewmodes/shop/product-detail.cfm?id=" + this.getParent("form").getFirst("input").get("value"),
									});
							});
					}
				}).create();
		})

	
	
	//ajaxCartFx.element.setStyle("display", "")
	$("cart-summary").addEvent("click", function() {
		ajaxCartFx.toggle();
		$("my-account").getFirst("div").fade("out");
		})
	
	$("my-account-btn").addEvent("click", function(ev) {
		ev.stop();
		var endPoint = 0;
		var loginBox = $("my-account").getFirst("div");
		if (loginBox.get("opacity") == 0) {
			loginBox.setStyle("display", "");
			endPoint = 1;
			}
		new Fx.Morph(loginBox, {
			onComplete : function () {
				if(loginBox.get("opacity")==0) loginBox.setStyle("display", "none")
				}
			}).start({"opacity": endPoint})
		//$("my-account").getFirst("div").fade("toggle");
		ajaxCartFx.slideOut();
		})
	
	if($("my-account-login")) {
		$("my-account-login").addEvent("submit", function (ev) {
			if(ev) ev.stop();
			$("login-failed").tween("opacity", 0);
			new Element("input", {type:"hidden", name:"username", value:$("login-email-address").value}).inject(this);
			new Element("input", {type:"hidden", name:"password", value:$("login-password").value}).inject(this);
			this.set("send", {
				"url" 		: "/viewmodes/my-account/menu.cfm?reset=true&" + new Date(),
				"method" 	: "post",
				"onSuccess" : function (responseText, responseXML) {
									var response = new Element("div").set("html", responseText);
									if (response.getElement("div[id=login]")) {
										$("login-failed").tween("opacity", 1);
										$("login-failed").getElement("a").addEvent("click", function (ev) {
											if(ev) ev.stop();
											
											new Request.HTML({
												"method" : "POST",
												"data" : "email=" + $("login-email-address").get("value"),
												"url": $("login-failed").getElement("a").get("href")
												,"update" : $("login-failed").getElement("p")
												}).send();
											
											
											});
											
										this.getElements("input[type=hidden]").dispose()
										}
									else {
										response.getFirst("div").replaces($("login"));
										refreshCartSummary();
										}
									}.bind(this)
				});
			this.send();	
			})
		}
	
	});

function dynamicWindow(str, w, h)
	{
	dynamicPopup = window.open("about:blank","dynamicPopup","status=1,width=" + w + ",height=" + h);
	docStyle = document.getElementsByTagName("link");

	docStyles = "";
	for (i=0; i < docStyle.length; ++i) {
		//docStyles += docStyle[i].outerHTML;
		}

	dynamicPopup.document.write(docStyles + str);
	dynamicPopup.document.title = document.title;
	dynamicPopup.document.close();
	}
	
function openVC() {
	var content = "<html><title>What are Credit Security Codes</title></html><body><style>body,li,ul,ol,p,div,td,a {font-family:arial; font-size:9pt;}</style><h2>Credit Card Security Code</h2><p>The Card Security Code (CSC) Number is printed on your credit card and provides you with extra security.</p><p>The location of the number varies from card to card:</p><ul><li><strong>Visa, Mastercard and Bankcard</strong><br><br>- Several digits are printed in the signature area on the back of your card. The last three digits make up the CSC Number. <br><img src=\"/storage/images/cvv.jpg\" title=\"Credit Card Security Code (CSC)\" alt=\"Credit Card Security Code (CSC)\" /></li></ul><br><a href=\"javascript:window.close()\"><strong>close window</strong></a></body></html>";
	dynamicWindow(content, 400, 400);
	}
	
function openInvoice(props) {
	var content = "<html><title>Invoice " + props.InvoiceNumber + "</title></html><body><style media='print'>#print-btn {display:none;}</style><div id=\"print-btn\"><a href=\"javascript:window.print()\"><strong>Print</strong></a></div>" + props.Invoice + "</body></html>";
	dynamicWindow(content, 700, window.getSize().height);
	}	
