var login_validated = false;

$(function(){
	if($("div.cart").length > 0 && $("#empty").length == 1) {
 		$("#checkout").hide();
 	}
 	$("//input[@name='amount']").numeric();
 	$("//input[@name='amount[]']").numeric();
 	
 	$("//input[@name='amount[]']").bind("keyup", function() { 		
 		var item_id   = this.parentNode.parentNode.id.replace(/item_/, "");
 		$.ajax(
 			{
			   type: "POST",
			   url: $("#checkout").attr("action").replace(/checkout/, "changeamount"),
			   data: "item_id="+item_id+"&amount="+this.value,
			   success: function(z) {}
			}
		);
			   	
 		var unitprice = parseFloat($("#unitprice_" + item_id).get(0).innerHTML);
 		var amount	  = parseInt(this.value);
 		$("#price_" + item_id).get(0).innerHTML = convert_to_price(unitprice * amount);
 		recalculate_total();
 	});
 	
 	$("//select[@name='size[]']").bind("change", function() { 		
 		var item_id   = this.parentNode.parentNode.id.replace(/item_/, "");
 		$.ajax(
 			{
			   type: "POST",
			   url: $("#checkout").attr("action").replace(/checkout/, "changesize"),
			   data: "item_id="+item_id+"&size="+this.value,
			   success: function(z) {}
			}
		);
 	});
 	
 	$("//select[@name='color[]']").bind("change", function() { 		
 		var item_id   = this.parentNode.parentNode.id.replace(/item_/, "");
 		$.ajax(
 			{
			   type: "POST",
			   url: $("#checkout").attr("action").replace(/checkout/, "changecolor"),
			   data: "item_id="+item_id+"&color="+this.value,
			   success: function(z) {}
			}
		);
 	});
 	
 	if($("#existing").get(0).checked) {
 		$("#repeat_password_container").hide();
 	}
 	else {
 		$("#repeat_password_container").show();
 	}
 		
 	$("#existing").bind("click", function() {
 		$("#repeat_password_container").hide();
 	});
 	
 	$("#new").bind("click", function() {
 		$("#repeat_password_container").show();
 	});
 	
 	$("form#login").bind("submit", function () {
 		login_validated = true;
 		var passwords_equal = true;
 		

 		$("form#login input.text").each(function() {
		
 			if(this.id == "emailt") {
 				
 				if(this.value == "") {
 					login_validated = false; 								
					$("#emailt_error").text("(cannot be empty)");
 				}	
 				else if(!this.value.match(/^([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-z]{2,6})?$/)) {
 					login_validated = false;
 					$("#emailt_error").text("(invalid email address)");
 				}
 				else {
 					$("#emailt_error").text("");
 				}
 			}
 			else if(this.id == "password") {
 				if(this.value != "" && $("input#new").get(0).checked && this.value != $("input#repeat_password").get(0).value) {
 					login_validated = false;
 					passwords_equal = false;
 					//$("//label[@for='password']").css("color", "#FF0000");
 					$("#password_error").text("");
 					$("#repeat_password_error").text("(does not match)");
 				}
 				else if(this.value == "") {
 					login_validated = false;					
 					$("#password_error").text("(cannot be empty)");
 				}
 				else {
 					$("#password_error").text("");
 				}
 			}
 			else if(this.value == "" && $("input#new").get(0).checked) {
 				login_validated = false;
 				$("#repeat_password_error").text("(cannot be empty)");
 			}
 			else if(this.value != "" && passwords_equal == true) {
 				$("#repeat_password_error").text("");
 			}
 		});
 		
 		if(login_validated) {
	 		$.ajax({
			   	type: "POST",
			   	url:  $("form#login").attr("action"),
			   	data: "email="+$("#emailt").attr("value")+"&"+
			   	      "password="+$("#password").attr("value")+"&"+
			   		  "login_type="+($("#new").get(0).checked?"new":"existing")+"&"+
			   		  "repeat_password="+$("#repeat_password").attr("value"),
				success: function(login_result) {
					if(login_result=="") {
						$("form#checkout").submit();
					}
					else {
						var errors = login_result.split("&");
						for(var i = 0; i < errors.length; i++) {
							var error = errors[i].split("=");
							var field = error[0] + "_error";
							var value = error[1];
							$("#" + field).text(value);
						}
					}
				}
			});
		}

		return false;
 	});	
 	
 	$("form#newsletter_form").bind("submit", function () {
 		
 		var e = $("#email").get(0).value;
 		if(e == "") {
  			$("#subscription_result").html("");
 		}
 		else if(e.match(/^([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-z]{2,6})?$/)) {
			
			$.ajax({
			   	type: "POST",
			   	url:  $("form#newsletter_form").attr("action"),
			   	data: "email="+$("#email").attr("value"),
				success: function(subscription_result) {
					$("#subscription_result").html(subscription_result);
				}
			});
			
		}
 		else if(e != "") {
 			$("#subscription_result").html("<span class=\"error\">Error: invalid email address</span>");
 		}
 		
 		
		return false;
	});
	
});
  
function addtocart() {
	
	$.ajax({
	   type: "POST",
	   url: $("#addtocart").attr("action"),
	   data: "product_id="+$("#product_id").attr("value")+"&"+
	   		 "amount="+$("#amount").attr("value")+"&"+
	   		 "color="+$("#color").attr("value")+"&"+
	   		 "size="+$("#size").attr("value"),
			   success: function(item_html) {
			   		
			   		
			   		itemHtml = $(item_html)
				    if(itemHtml.attr("class") == "new") {
				    	itemHtml.hide().appendTo("div.cart ul").show("slow"); 
				    	$('#empty').hide("slow", function() { 
				    		$('#empty').remove(); });
				    		if($("#checkout").css('display') == 'none') {
					 			$("#checkout").slideDown("slow");
					 		}
				    }
				    else {
						alert(item_html);
					}
	   }
	 });
}

function removefromcart(item_id) {
	$.ajax({
	   type: "GET",
	   url: ci_base_url+"page/removefromcart/" + item_id,
	   success: function(item_html){
	     	$('#item_' + item_id).hide("slow", function() { 
	     		$('#item_' + item_id).remove(); 		    	
		    	if($("div.cart ul li").length == 0) {
		     		$("#checkout").slideUp("slow");
		     		$("<li id=\"empty\"><em>empty</em></li>").hide().appendTo("div.cart ul").show("slow");
		     	
		     	}
	     	});
	   }
	 });
}

function removefromcheckout(item_id) {
	$.ajax({
	   type: "GET",
	   url: ci_base_url+"page/removefromcart/" + item_id,
	   success: function(item_html){
	   		$("#item_" + item_id).remove();
	   		
	   		$("tr.item").each(function(i) {
	   			$(this).css("background-color", i%2==0?"#E9E9E9":"#FFFFFF");
	   		});		
	   		recalculate_total();   	
	   }
	 });
}

function convert_to_price(v) {
	v = String(Math.round(v*100)/100); 
	   		
	if(v.match(/\./)) {
   		m = v.match(/\.([0-9]*)/);
   		if(m && m.length > 1 && m[1].length == 1) {
   			v += "0";
   		}
	}
	else {
		v += ".00";
	}
	return v;
}

function recalculate_total() {
   	var total = 0; 
	$("span.itemprice").each(function(i) {
		total += parseFloat(this.innerHTML);
	});
	
	$("#total").get(0).innerHTML = convert_to_price(total);
	$("#discount").get(0).innerHTML = convert_to_price(-total/10);
	$("#grandtotal").get(0).innerHTML = convert_to_price(total*0.9);
}