var pennyAppeal = {
    languagePicker: function(){
		var $header = $("#header");
		$("<div/>").attr("id","languageSelector")
					.css({left:$header.offset().left})
					.html('<h3>Select language</h3>'
						  + '<ul>'
						  + '<li id="lang-en"><a href="#"><b>English</b></a></li>'
						  + '<li id="lang-fr"><a href="#googtrans/en/fr/"><b>French</b></a></li>'
						  + '<li id="lang-es"><a href="#googtrans/en/es/"><b>Spanish</b></a></li>'
						  + '<li id="lang-de"><a href="#googtrans/en/de/"><b>German</b></a></li>'
						  + '</ul>'
					).appendTo("#footer");
		$("#languageSelector a").bind("click",function(e){
			e.preventDefault;
			var $this = $(this),
				link = $this.attr("href"),
				url = window.location.href,
				hash = url.indexOf("#");
			if(hash > 0){
				url = url.substring(0,hash);
			}
			window.location.href = url+link;
			location.reload(true);
			return false;
		});
	},
	
	addProduct : function(form){
		var $this = $(form),
			formData = $this.serialize(),
			$qtys = $this.find(".qty"),
			$miniCart = $("#miniCart");
			prodCount = 0;
	
		$qtys.each(function(){
			prodCount = prodCount + parseInt($(this).val());
		});
		
		if(prodCount < 1){
			$("<div/>").attr("id","modalDiv")
	 		   .attr("title","No Quantity Selected")
	 		   .css({textAlign:"center"})
	 		   .html("<p>You did not select a product quantity</p>")
	 		   .dialog({
	 			   modal: true,                            
				       position: ["center",150],
				       resizable: false,
				       buttons: { 
				           "OK": function() {
				 			  $(this).dialog("close");
	 			   			}
				       }
	 		   });
			return false;
		}
		
		jQuery.getJSON("/shop/addtocart?"+formData+"&format=json",null,function(data){
			if(data.result == 'OK'){
				$modal = $("<div/>").attr("id","modalDiv")
		 		   .attr("title",data.message);
				
				// Add product descriptions to modal
				itemstring = '';
				jQuery.each(data.products,function(){
					itemstring += "<p>"+this.qty+" x "+this.name+"</p>";
					//$("<p/>").html(this.qty+" x "+this.name).appendTo($modal);
				});
				$(itemstring).appendTo($modal);
				
				// Add current cart status to modal
				var cartValue = new String(data.cart.total);
				if(cartValue.indexOf(".") == -1){
					cartValueString = "&pound;"+cartValue+".00";
				}
				else {
					cartValueString = "&pound;"+cartValue+"0";
				}
				$("<p/>").html("Your Cart: "+data.cart.count+" items "+cartValueString)
					.css({textAlign:"center"})
					.appendTo($modal);
				
				//show modal
				$modal.dialog({
	 			   modal: true,                            
				       position: ["center",150],
				       width:400,
				       resizable: false,
				       buttons: { 
				           "Continue Shopping": function() {
				 			  $(this).dialog("close");
	 			   			},
	 			   			"View Cart & Checkout": function() {
	 			   				$("#modalDiv").html("<p>You are being redirected...</p>")
	 			   						  .dialog('option',{title:'Please Wait...',buttons:{}});
	 			   					window.location = "/shop/cart";
		 			   			}
				       }
	 		   });
				
				// reset form qtys to 0
				$qtys.each(function(){
					$(this).val(0);
				});
				
				// Create / Update miniCart
				if($miniCart.length){
					$miniCart.find("#miniCartCount").html(data.cart.count);
					$miniCart.find("#miniCartTotal").html(cartValueString);
				}
				else {
					$("<div/>").attr("id","miniCart")
						.html('<p><span id="miniCartCount">'+data.cart.count+'</span> items <span id="miniCartTotal">'+cartValueString+'</span> <a href="/shop/cart" id="viewCart">View Cart</a></p>')
						.prependTo("#mainContent");
				}
			}
			else {
				
			}
			
			
			
		});
	},
	
	giftAidCheck: function(e,target){
		var $this = $(target);
		if($this.attr("rel") == 'checked'){
			return true;
		}
		else {
			e.preventDefault();
			var $GA = $("#giftAid:checked");
			$this.attr("rel","checked");
			if($GA.val() == null){
				$("<div/>")
				.attr("id","modalDiv")
	 		   	.attr("title","Please Consider Gift Aid")
	 		   	.css({textAlign:"center"})
	 		   	.html("<p>You have chosen not to 'Gift Aid' your donation.</p>"
	 				   +"<p>If you are eligable, the extra 28% donation can really help us make a difference.</p>")
	 		    .dialog({
	 			   modal: true,                            
			       position: ["center",150],
			       resizable: false,
			       buttons: { 
			           "No Thanks": function() {
 			   			   $("#modalDiv").html("<p>Submitting form please wait...</p>").dialog('option',{title:'Please Wait...',buttons:{}});
 			   			   
			        	   $this.trigger('submit');
 			   			},
			           "Add Gift Aid": function() {
 			   			   $("#modalDiv").html("<p>Submitting form please wait...</p>").dialog('option',{title:'Please Wait...',buttons:{}});
 			   			   
 			   			   $("#giftAid").attr("checked",true);
 			   			   $this.trigger('submit');
			        	}
			       }
	 		   });
			}
			else {
				$this.trigger('submit');
				return true;
			}
		}
		
		return false;
	}
};

$(document).ready(function(){
	pennyAppeal.languagePicker();
	
	$("input.qty").focus(function(){		
		var $this = $(this);
		if($this.val() == '0'){
			$this.val('');
		}
	});
	$("input.qty").blur(function(){		
		var $this = $(this);
		if($this.val() == ''){
			$this.val(0);
		}
	});
	
	$("#productAddForm").bind("submit",function(e){
		e.preventDefault();
		pennyAppeal.addProduct(this);
		return false;
	});
	
	$(".buyNow").click(function(e){
		e.preventDefault();
		var $qty = $(this).parents("tr").find(".qty");
		if(parseInt($qty.val()) == 0){
			$qty.val(1);
		}
		$("#productAddForm").submit();
		return false;
	});
	
	$(window).resize(function(){
		$picker = $("#languageSelector");
		if($picker.length){
			$picker.css({left:$("#header").offset().left});
		}
	});
	
	$("#cartDelete").css({cursor:"pointer"}).bind("click",function(){
		$("#cartForm input:checkbox").each(function(){
			$(this).attr("checked",true);
		});
	});
	
	$("#checkoutForm").bind('submit',function(e){
		result = pennyAppeal.giftAidCheck(e, this);
		return result;		
	});
	
	$("#mainContent img").mouseover(function(e){
		$this = $(this);
		if($this.parent().is("a") === false && $this.attr("longdesc") != "nozoom"){
			$this.css({cursor:"pointer"});
		}
	});
	
	$("#mainContent img").click(function(e){
		var $this = $(this),
			newId =  "zoomLink" + Math.ceil(10000*Math.random());
			if($this.parent().is("a") === false && $this.attr("longdesc") != "nozoom"){
				var src = $this.attr("src"),
					desc = $this.attr("alt"),
					qPos = src.indexOf("?"),
					newSrc = src.substring(0,qPos),
					link = $("<a/>").attr('href',newSrc)
							.attr("id",newId)
							.attr("title",desc);				
				$this.wrap(link);
				$("#"+newId).fancybox().trigger("click");
			}
	});
	
});