var $cart;
var $counter;
var ajaxUrl;
var pageUrl;

function initWebshopProductPage(_pageUrl, _ajaxUrl, numberOfProductsInCart){
	pageUrl = _pageUrl;
	ajaxUrl = _ajaxUrl;
	$cart = $("#webshop_cart");
	$counter = $cart.find("span.count");
	$counter.text( numberOfProductsInCart );
}


/**
 * Dependencies: webshop cart html must be in module website / view / <theme> / layout.php
 */
function addToCart(product_id, amount){
	$.ajax({
		url: ajaxUrl+"/?action=addtocart&product_id="+product_id+"&amount="+amount,
		dataType: "json",
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert(textStatus+"\n\n"+errorThrown);
		},
		success: function(data){
			
			
			$.add2cart('productimage_'+product_id, 'webshop_cart_target', function(){
				$counter.text( data.count );
			});
	  	}
	});
}

function initWebshopCartPage(_pageUrl, _ajaxUrl){
	pageUrl = _pageUrl;
	ajaxUrl = _ajaxUrl;
	$cart = $("#webshop_cart");
	$counter = $cart.find("span.count");
	
	$("td.quantity a.less").click(function(){
		$parentTr = $(this).parent().parent();
		calculateCart($parentTr, -1);
		var product_id = $parentTr.attr("title");
		addToCart(product_id, -1);
		
	});
	$("td.quantity a.more").click(function(){
		$parentTr = $(this).parent().parent();
		calculateCart($parentTr, 1);
		var product_id = $parentTr.attr("title");
		addToCart(product_id, 1);
	});
	$("#webshopform").submit(onCartSubmit);
}

function calculateCart($parentTr, amount){
	var $div = $parentTr.find("div.count");
	var count = Number($div.text());
	count += amount;
	if(count >= 0){
		$div.text( count );
		var price = priceToFloat( $parentTr.find("td.price").text() );
		$parentTr.find("td.priceTotal").text( (count*price)+" NOK" );
		var total = priceToFloat( $("table.cart tr.total td.total").text() );
		var difference = total + (amount * price); 
		$("table.cart tr.total td.total").text( difference+" NOK" );
	}
}

// http://stackoverflow.com/questions/987382/javascript-extracting-number-from-string
function priceToFloat(price){  
   return parseFloat(price.replace(/\./g, '').replace(/,/g,'.').replace(/[^\d\.]/g,''), 10);
}
/*
function cartValidate()
{
$("form#webshopform").validate({ 
							rules: { 
									field_1__11: { required: true },
									field_2__11: { required: true },
									field_25__21: { required: true, email: true },
									field_26__20: { required: true, digits: true },
									field_27__1: { required: true },
									field_28__22: { required: true, digits: true },
									field_29__11: { required: true },
									field_30__11: { required: true },
									
									
									},
							messages: 
									{ 
									field_1__11: "Please enter a valid first name",
									field_2__11: "Please enter a valid last name",
									field_25__21: "Please enter a valid email addres",
									field_26__20: "Please enter a valid phone number",
									field_27__1: "Please enter a valid address",
									field_28__22: "Please enter a valid zip code",
									field_29__11: "Please enter your city",
									field_30__11: "Please enter your country",
									}, 
							
							submitHandler: function() { onCartSubmit(); }
							
					 });
}
*/

function onCartSubmit(){
	$.ajax({
		url: pageUrl+"?action=validateorder",
		type: "POST",
		data: $("#webshopform").serialize(),
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert(textStatus+"\n\n"+errorThrown);
		},
		success: function(htmlAndJson){
			var separator = "";
			for(var i=0; i<32; i++) separator += i;
			var json = jQuery.parseJSON( htmlAndJson.split(separator)[1] );
			if(json.isvalid)
			{
				window.location = pageUrl+"?action=submitorder&order_id="+json.order_id;
			}
			else{
				var s = "";
				for(var i in json){
					if(i != "isvalid"){
						s += json[i]+"\n";
					}
				}
				alert(s);
			}
	  	}
	});
}
























// http://plugins.jquery.com/project/add2cart
// http://i1t2b3.com/2009/01/29/add2cart/

(function($) {
	$.extend({
		add2cart: function(source_id, target_id, callback) {
			var THROW_DURATION = 1000;
			var source = $('#' + source_id );
			var target = $('#' + target_id );
			if(source.length == 0 || source.length == 0){
				callback();
			}
			else{
				var shadow = $('#' + source_id + '_shadow');
				if( !shadow.attr('id') ) {
					
					var style="";
					style += "display: none; ";
					style += "position: static; ";
					style += "top: 0px; ";
					style += "z-index: 100000; ";
					$('body').prepend('<div id="'+source.attr('id')+'_shadow" style="'+style+'"><img width="100%" height="100%" src="'+source.attr('src')+'" /></div>');
					
					var shadow = $('#'+source.attr('id')+'_shadow');
				}
				if( !shadow ) {
					alert('Cannot create the shadow div');
				}
				shadow.width(source.css('width')).height(source.css('height')).css('top', source.offset().top).css('left', source.offset().left).css('opacity', 0.5).show();
				shadow.css('position', 'absolute');
				shadow.animate( { width: target.innerWidth(), height: target.innerHeight(), top: target.offset().top, left: target.offset().left }, { duration: THROW_DURATION } )
		        .animate( { opacity: 0 }, { duration: 200, complete: callback } );
			}
		}
	});
})(jQuery);



