var dChar='%';
var cChar='#';
var currency='$';

$(document).ready(function() {
	Cufon.replace('#cartItemCount');	
	/*$('form.cartItemForm').live("submit",function(){
		//setCookie('cItemList','',1);
		alert('here');
		var id= $(this).find('input[name=itemId]').val();
		var qty=$(this).find('input[name=itemQty]').val();
		var name=$(this).find('input[name=itemName]').val();
		var price=$(this).find('input[name=itemPrice]').val();
		var total=parseInt(qty)*parseFloat(price);
		total=total.toFixed(2);
			var pos;
			var itemCount=countItem();
			if (itemCount<1){
				addCartItem(id,qty,name,price);
				$('#removeAllSpan').html("<a href=\"javascript:removeAll();\">remove All</a>");
			}
			else{
				pos=getItemPos(id);
				if (pos<0){
					addCartItem(id,qty,name,price,total);
				}
				else{
					updateCartItem(pos,qty,price);
				}
			}
			return false;
	});	*/
	$('.itemAddBtn').live('click',function(){
		var id= $(this).parent().parent().find('input[name=itemId]').val();
		var qty=$(this).parent().parent().find('input[name=itemQty]').val();
		var name=$(this).parent().parent().find('input[name=itemName]').val();
		var price=$(this).parent().parent().find('input[name=itemPrice]').val();
		var total=parseInt(qty)*parseFloat(price);
		total=total.toFixed(2);
			var pos;
			var itemCount=countItem();
			if (itemCount<1){
				addCartItem(id,qty,name,price);
				$('#removeAllSpan').html("<a href=\"javascript:removeAll();\" class=\"removeAll\">remove All</a>");
			}
			else{
				pos=getItemPos(id);
				if (pos<0){
					addCartItem(id,qty,name,price,total);
				}
				else{
					updateCartItem(pos,qty,price);
				}
			}
	});
	
	$('.removeItem').live("click",function(){
		var url=$(this).attr('href');
		var chunk=url.split('=');
		var id=chunk[1];
		deleteCartItem(id);
		//$('#cartItemCount').html('Your Cart ( '+countItem()+' item )');
		printItemCount();
		return false;
	});

	$(".inputQty").keydown(function(event) {
		qtyKeyDown(this,event);
        // Allow only backspace and delete
        /*if ( event.keyCode == 46 || event.keyCode == 8 ) {
                // let it happen, don't do anything
        }
        else {
                // Ensure that it is a number and stop the keypress
                if (event.keyCode < 48 || event.keyCode > 57 ) {
                        event.preventDefault(); 
                }       		
        }*/
    });

	
	$('.cartitemQty').live('keyup',function(){
		alert('ss');
		qtyKeyUp(this);
		/*var qty=$(this).val();
		if ((qty.length>0)&&(qty.length<5)){
			if (qty>1000){
				$(this).val(1000);
			}
			else	
			if (qty<1){
				$(this).val(1);
			}
			else
			if (qty==''){
				$(this).val(1);
			}
		}
		else		
		$(this).val(1);
		var price=parseInt($(this).parent().parent().find('.cartItemPrice').html());
		qty=parseInt($(this).val());
		var id=$(this).parent().parent().find('.cartItemId').val();
		pos=getItemPos(id);
		changeCartItem(pos,qty,price);*/
		//$(this).parent().parent().find('.cartItemTotalPrice').html(total);
	});
	
	$('.listItemQty').keyup(function(){
		var qty=$(this).val();
		if ((qty.length>0)&&(qty.length<5)){
			if (qty>1000){
				$(this).val(1000);
			}
			else	
			if (qty<1){
				$(this).val(1);
			}
			else
			if (qty==''){
				$(this).val(1);
			}
		}
		else		
		$(this).val(1);
	});
	
	$('.itemAddtoCart').hover(function(){
		$(this).addClass("itemAddtoCartHover");
	},function(){
		$(this).removeClass("itemAddtoCartHover");
	});
	
	$('.itemAddtoCart').mousedown(function(){
		$(this).addClass("itemAddtoCartActive");
	});
	
	$('.itemAddtoCart').mouseup(function(){
		$(this).removeClass("itemAddtoCartActive");
	});
	
	$('#shoppingCartHeader a').live("click",function(){
		 toggleCart();
		 return false;
	});
});

function printItemCount(){
	$('#cartItemCount').html('Your Cart ( '+countItem()+' item )');
	Cufon.replace('#cartItemCount');	
}

function toggleCart(){
	$('#shoppingCartContent').toggleClass('hideCart');
	$('#shoppingCartHeader a').toggleClass('open');
		if ($('#shoppingCartHeader a').hasClass('open')){
		Cufon.replace('#cartItemCount',{ color: 'black'});
	}
	else
	Cufon.replace('#cartItemCount',{ color: 'white'});
}

function itemSubmit(form){
		var id= $(form).find('input[name=itemId]').val();
		var qty=$(form).find('input[name=itemQty]').val();
		var name=$(form).find('input[name=itemName]').val();
		var price=$(form).find('input[name=itemPrice]').val();
		var total=parseInt(qty)*parseFloat(price);
		total=total.toFixed(2);
			var pos;
			var itemCount=countItem();
			if (itemCount<1){
				addCartItem(id,qty,name,price);
				$('#removeAllSpan').html("<a href=\"javascript:removeAll();\" class=\"removeAll\">remove All</a>");
			}
			else{
				pos=getItemPos(id);
				if (pos<0){
					addCartItem(id,qty,name,price,total);
				}
				else{
					updateCartItem(pos,qty,price);
				}
			}
			return false;
}

function addCartItem(id,qty,name,price,total){
	var itemList=getCookie('cItemList');
	//var itemList=$('#mycookie').html();
	var newItem=id+dChar+name+dChar+qty+dChar+price+cChar;
	var newItemList=itemList+newItem;
	setCookie('cItemList',newItemList,1);
	$('#mycookie').html(newItemList);
	addTableItem(id,name,qty,price,total);
	printItemCount();
	printCartSum();
	//$('#script').load('shoppingcartscript.php');
	//updateCartTable();
}

function updateCartItem(pos,qty,price){
	//var itemList=getCookie('cItemList');
	var itemList=getCookie('cItemList');
	//var itemList=$('#mycookie').html();
	var item=itemList.split(cChar);
	var count=item.length-1;
	var newItemList="";
	var chunk=item[pos].split(dChar);
	var newQty=parseInt(qty)+parseFloat(chunk[2]);
	item[pos]=chunk[0]+dChar+chunk[1]+dChar+newQty+dChar+chunk[3];
	for (i=0;i<=item.length-2;i++){
		newItemList+=item[i]+"#";
	}
	setCookie('cItemList',newItemList,1);
	$('#mycookie').html(newItemList);
	var total=newQty*price;
	total=total.toFixed(2);
	updateTableItem(pos,newQty,total);
	printCartSum();
	//updateCartTable();
}

function changeCartItem(pos,qty,price){
	//var itemList=getCookie('cItemList');
	var itemList=getCookie('cItemList');
	//var itemList=$('#mycookie').html();
	var item=itemList.split(cChar);
	var count=item.length-1;
	var newItemList="";
	var chunk=item[pos].split(dChar);
	item[pos]=chunk[0]+dChar+chunk[1]+dChar+qty+dChar+chunk[3];
	for (i=0;i<=item.length-2;i++){
		newItemList+=item[i]+"#";
	}
	setCookie('cItemList',newItemList,1);
	$('#mycookie').html(newItemList);
	var total=qty*price;
	total=total.toFixed(2);
	updateTableItem(pos,qty,total);
	printCartSum();
}

function deleteCartItem(id){
	var pos=parseInt(getItemPos(id));
	var itemList=getCookie('cItemList');
	var item=itemList.split(cChar);
	var count=item.length-1;
	var newItemList="";
	for (i=0;i<=item.length-2;i++){
		if (i!=pos)
		newItemList+=item[i]+"#";
	}
	setCookie('cItemList',newItemList,1);
	$('#mycookie').html(newItemList);
	deleteTableItem(pos);
	printCartSum();
}

function getItemPos(id){
	//var itemList=$('#mycookie').html();
	var itemList=getCookie('cItemList');
	var item=itemList.split(cChar);
	var count=item.length-1;
	var chunk,pos;
	pos=-1;
	for (i=0;i<=count;i++){
		chunk=item[i].split(dChar);
		if (chunk[0]==id){
			pos=i;
			break;
		}
	}
	return pos;
}

function printCartSum(){
	var itemList=getCookie('cItemList');
	var item=itemList.split(cChar);
	var count=item.length-1;
	var chunk,sum,total;
	sum=0;
	for (i=0;i<=count-1;i++){
		chunk=item[i].split(dChar);
		total=parseInt(chunk[2])*parseFloat(chunk[3]);
		sum+=total;
	}
	sum=sum.toFixed(2);
	$('#cartSum').html(currency+' '+number_format(sum,2,".",","));
}

function countItem(){
	//var itemList=$('#mycookie').html();
	var itemList=getCookie('cItemList');
	var item=itemList.split(cChar);
	var count=item.length-1;
	return count;
}

function addTableItem(id,name,qty,price,total){
	var itemCount=countItem();
	var total=parseInt(qty)*parseFloat(price);
	name="<input type=\"hidden\" name=\"citemId[]\" value="+id+"  class=\"cartItemId\">"+name+" <a href=\"?removeId="+id+"\" class=\"removeItem\">remove</a>";
	var item="<tr class=\"item\"><td class=\"cartItemName\">"+name+"</td><td><input type=\"text\" name=\"citemQty[]\" class=\"cartItemQty\" maxlength=\"4\" size=\"4\" value="+qty+" onkeyup=\"qtyKeyUp(this);\" onkeydown=\"qtyKeyDown(this,event);\"></td><td class=\"right\">"+currency+" <span class=\"cartItemPrice\">"+number_format(price,2,".",",")+"</span></td><td class=\"right\">"+currency+" <span class=\"cartItemTotalPrice\">"+number_format(total,2,".",",")+"</span></td></tr>"
	if (itemCount<2){
		$(".cartTable tbody").prepend(item);
		$(".cartTable tbody tr.itemNone").remove();
	}
	else{
		$(".cartTable tbody").append(item);
	}
	//$('.cartTable tbody tr.item:last-child').find('.cartItemQty').toggleClass('inputQty');
}

function qtyKeyDown(element,event){
	 // Allow only backspace and delete

        if ((event.keyCode==37 || event.keyCode==39)|| (event.keyCode == 46 || event.keyCode == 8 )) {
                // let it happen, don't do anything
        }
        else {
                // Ensure that it is a number and stop the keypress
                if (event.keyCode < 48 || event.keyCode > 57 ) {
                        event.preventDefault(); 
                }       		
        }
}

function qtyKeyUp(element){
		var qty=$(element).val();
		if ((qty.length>0)&&(qty.length<5)){
			if (qty>1000){
				$(element).val(1000);
			}
			else	
			if (qty<1){
				$(element).val(1);
			}
			else
			if (qty==''){
				$(element).val(1);
			}
		}
		else		
		$(element).val(1);
		var price=stripNonNumeric($(element).parent().parent().find('.cartItemPrice').html());
		price=parseFloat(price);
		qty=parseInt($(element).val());
		var id=$(element).parent().parent().find('.cartItemId').val();
		pos=getItemPos(id);
		changeCartItem(pos,qty,price);
}

function updateTableItem(pos,qty,total){
	pos+=1;
	$(".cartTable tbody tr:nth-child("+pos+")").find('.cartItemQty').val(qty);
	$(".cartTable tbody tr:nth-child("+pos+")").find('.cartItemTotalPrice').html(number_format(total,2,".",","));
}

function deleteTableItem(pos){
	if (countItem()>0){
		pos+=1;
		$(".cartTable tbody tr:nth-child("+pos+")").remove();
	}
	else{
		removeAll();
	}
	//$('#cartItemCount').val('Your Cart ( '+countItem()+' item )')
	printItemCount();
}

function removeAll(){
	setCookie('cItemList','',1);
	$(".cartTable tbody").html("<tr class=\"itemNone\"><td colspan=\"4\">No Item</td></tr>");
	$('#removeAllSpan').html("&nbsp;");
	//$('#cartItemCount').val('Your Cart ( '+countItem()+' item )')
	printItemCount();
	$('#cartSum').html(currency+' 0.00');
	//updateCartTable();
}

function updateCartTable(){
		$('#shoppingCart').load("shoppingCartTable.php");
}

 function number_format(a, b, c, d) {
	var a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	var e = a + '';
	var f = e.split('.');
	if (!f[0]) {
		f[0] = '0';
	}
	if (!f[1]) {
		f[1] ='';
	}
	if (f[1].length < b) {
		g = f[1];
		for (i=f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if ((d != '') && (f[0].length > 3)) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j+=3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] +'';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '' : c;
	var str= f[0] + c + f[1];
	return str;
}

function stripNonNumeric( str ){
  str += '';
  var rgx = /^\d|\.|-$/;
  var out = '';
  for( var i = 0; i < str.length; i++){
    if( rgx.test( str.charAt(i) ) ){
      if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||
             ( str.charAt(i) == '-' && out.length != 0 ) ) ){
        out += str.charAt(i);
      }
    }
  }
  return out;
}
 
function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}
