/**
*	Function for products manipulation in the system
*
*	Author: Jean-Francois G�linas
*	Date: 2009-04-16
**/


function manual_qty_entry(input, pack_qty, max_qty, sku) {
	
	if ( input.value == ""){
		curr_input =0;
	} else {
		curr_input = input.value;
	}
	

	if (isNaN(curr_input)) {
		curr_input = parseInt(0);
	} else {
		curr_input = parseInt(curr_input);
	}

	if (curr_input < pack_qty) {
		curr_input = pack_qty;
	}
	
	if ((curr_input % pack_qty) != 0) {
		// round up to pack multiplier
		curr_input += pack_qty - (curr_input % pack_qty);
	}
	
	if (curr_input > max_qty) {
		// set to max available products
		curr_input = max_qty - (max_qty % pack_qty);
	}
	
	if(curr_input == 0){
		// Maximum product's quantity
		input.value = max_qty;
		curr_input  = max_qty;
	} else {
		input.value = curr_input;
	}
	
	
	
	calcultingAmounts(sku, curr_input,'');
}


function addItemtoCart(idProduct,sku,image){
	
	
	quantity	= document.getElementById("prod_qty_"+sku).value; 
	price 		= document.getElementById("price_"+sku).value;
	
	 $.post('models/cart.actions.php?order_code='+idProduct+'&order_code='+idProduct+'&quantity='+quantity+'&price='+price+'&sku='+sku+'&image='+image,
	 		 
	 		 function(data){
	 		 	 $("#"+sku).html(data);
	 		 }
	 	);
	
	$.post('models/cart.actions.php?action=removeAddProductButton&sku='+sku,
	 		 
			 function(data){
	 		 	 $("#action_"+sku).html(data);
	 		 }
	);
}

function saveItemstoCart(btn_Proceed){
	
	//var saved	=	false;
	var items 	= 	$("#numrows").val();
	
	
		//Charging new items to the cart 
		for (var x=0;x<=items;x++){
			
			sku	 	  	= $("#productId_"+x).val();
			
			if (isInteger(sku)){			
				//alert(x+' '+sku);
				code_sku 	= $("#code_"+x).val().toUpperCase();						
				qty			= $("#qty_"+code_sku).val(); 						
				price		= $("#unit_price_"+code_sku).val();
				
				if( (sku!="") && (qty=="")){
					qty=1;
				}
							
				//$.post('../models/cart.actions.php?action=addQuickOrder&price='+price+'&sku='+sku+'&qty='+qty,async:   false);
				$.ajax({
				   url: "../models/cart.actions.php",
				   type: "POST",
				   data: "action=addQuickOrder&price="+price+"&sku="+sku+"&qty="+qty,
				   success: function(msg){	
							
				                     
				   },
					async:   false

				 });
				
				//saved		= true;

			}		
		}
		
		if(btn_Proceed==1){					
			$('#frmQuickOrder').submit();
		} else {
			alert(_ITEMS_SAVED);
		}	
	
}

function add_pack_qty(input, pack_qty, max_qty, sku) {

	var curr_input	 = parseInt(document.getElementById(input).value);
	
   
	if (isNaN(curr_input)) {
		curr_input = parseInt(0);
	}

	curr_input = curr_input + pack_qty;
	if (curr_input > max_qty) {
		// set to max available products
		curr_input = max_qty;
	}
	
	document.getElementById(input).value = curr_input;
		
	calcultingAmounts(sku, curr_input,'');
}

function rem_pack_qty(input, pack_qty, max_qty, sku) {
	
	var curr_input 	 = parseInt(document.getElementById(input).value);
	
	var less_value;
	
	if (isNaN(curr_input)) {
		curr_input = parseInt(0);
	}
	
	less_value = curr_input;
	curr_input = curr_input - pack_qty;
	
	if (curr_input <= 0) {
		// set min available quantity of product
		curr_input = less_value;		
	} else {
		calcultingAmounts(sku, curr_input,'');
	}
		
	document.getElementById(input).value = curr_input;
	
	
}

function recalculatingAmountNewPrice(input, sku , i_price) {
	
	var curr_input 	 = parseInt(document.getElementById(input).value);
	
	calcultingAmounts(sku, curr_input, i_price);
			
	document.getElementById(input).value = curr_input;
		
}


function calcultingAmounts(sku, curr_input, i_price ){
	
	var unit_price = parseFloat($("#unit_price_"+sku+", label[for='unit_price_"+sku+"']").text());			
		
	if (isNaN(unit_price)){
		
		// This code is execute in quick order because the unitary price is not a label. It's a text box
		unit_price = round(parseFloat($("#unit_price_"+sku).val()),2);
				
			if (isNaN(unit_price)){
				
				// if the unit price typed is NaN or not valid set cart new price.
				unit_price = $("#original_unit_price_"+sku).val();
				
				if (isNaN(unit_price)){
					unit_price = $("#original_unit_price_"+i_price).val();					
				}
											
			}
		
		// Setting round value into text box					
		$("#unit_price_"+sku).val(unit_price);
		
	}
	
	var tot_price_prod = curr_input * unit_price;
	
	tot_price_prod 	= tot_price_prod.toFixed(2);
	
	$("#tot_price_prod_"+sku+", label[for='tot_price_prod_"+sku+"']").text(tot_price_prod);	
	
	calculatingTaxANDTotals($("#state").val(),0);	
}

function calcultingAmountsNewPrice(sku, newPrice, qty, old_pricetotal){
	
	var unit_price = parseFloat($("#inputNewPrice_"+sku).val());
	var subtotal = parseFloat($("#subtotalPrice").val());
	var string_total = ($("#tot_price_prod_"+sku+", label[for='tot_price_prod_"+sku+"']").text()).substr(1);
	var old_total = parseFloat(string_total);
	old_pricetotal  = parseFloat(old_pricetotal);
	
	if(!isNaN(unit_price)){
		if(unit_price>0){
			var tot_price_prod = qty * unit_price;
			
			tot_price_prod 	= tot_price_prod.toFixed(2);
			
			$("#tot_price_prod_"+sku+", label[for='tot_price_prod_"+sku+"']").text("$"+tot_price_prod);
			subtotal = (( parseFloat(subtotal) -  parseFloat(old_total)) +  parseFloat(tot_price_prod));
			
			//$("#subtotalPrice").val() = subtotal;
			document.getElementById('subtotalPrice').value = subtotal ;
			calculatingTaxANDTotals($("#state").val(),subtotal);	
		}
	}else{
		$("#tot_price_prod_"+sku+", label[for='tot_price_prod_"+sku+"']").text("$"+old_pricetotal);
		document.getElementById('inputNewPrice_'+sku).value="";
		
		subtotal = (( parseFloat(subtotal) -  parseFloat(old_total))+old_pricetotal);
		document.getElementById('subtotalPrice').value = subtotal ;
		calculatingTaxANDTotals($("#state").val(),subtotal);	
		
		alert("Invalid Price");
	}
	
}
function calculatingTaxANDTotals(state,subtotal_calculated){

	var subtotal   = 0.00;	
	var total	   = 0.00;
	var arr ;		
	
	if(subtotal_calculated == 0){
		$('.totcol').each(function(key,value){
			subtotal_tag = parseFloat($("#"+value.htmlFor+", label[for='"+value.htmlFor+"']").text());
			if(!isNaN(subtotal_tag)){
				subtotal = subtotal + subtotal_tag;
			}
			
		});	
	} else {
		subtotal = parseFloat(subtotal_calculated);
	}
	
	if(subtotal != 0){		
		if(!isNaN(subtotal)){
			$.ajax({
				   type: "POST",
				   url: "../models/cart.actions.php",
				   type: "POST",
				   data: "action=taxCalc&state="+state+"&subtotal="+subtotal,
				   success: function(msg){	
				
						arr = msg.split(',');
						
						total 	=	parseFloat(arr[0]);
						taxHST	=   parseFloat(arr[1]);
						taxGST	=   parseFloat(arr[2]);
						taxPST  = 	parseFloat(arr[3]);												
						
						rewriteTaxesLabes(total,subtotal,taxHST,taxGST,taxPST);				
				                     
				   }
				 });
		}
		return true;
	} else {		
		if(!isNaN(subtotal)){
			rewriteTaxesLabes(0,0,0,0,0);
		}
	}
}

function rewriteTaxesLabes(total,subtotal,taxHST,taxGST,taxPST){
	
	var total_taxes;
	total_taxes = taxHST + taxGST + taxPST;
	
	if(taxPST > 0){
		$("#pst_label").show();
		$("#pst_amount").show();
		$("#pst, label[for='pst']").text('$ '+taxPST.toFixed(2));
	} else {
		$("#pst_label").hide();
		$("#pst_amount").hide();
		$("#pst, label[for='pst']").text('$ 0.00');
	}
	
	if(taxGST > 0){
		$("#gst_label").show();
		$("#gst_amount").show();
		$("#gst, label[for='gst']").text('$ '+taxGST.toFixed(2));
	} else {
		$("#gst_label").hide();
		$("#gst_amount").hide();
		$("#gst, label[for='gst']").text('$ 0.00');
	}
	
	if(taxHST > 0){
		$("#hst_label").show();
		$("#hst_amount").show();
		$("#hst, label[for='hst']").text('$ '+taxHST.toFixed(2));
	} else {
		$("#hst_label").hide();
		$("#hst_amount").hide();
		$("#hst, label[for='hst']").text('$ 0.00');
	}
	
	if(total_taxes == 0){
		$("#total_amount").hide();
	}
	
	$("#total_amount, label[for='total_amount']").text('$ '+total.toFixed(2));
	$("#subtotal_amount, label[for='subtotal_amount']").text('');	
	$("#subtotal_amount, label[for='subtotal_amount']").text('$ '+subtotal.toFixed(2));	
	
	//$("#hst, label[for='hst']").text('$ '+taxHST.toFixed(2));
	//$("#pst, label[for='pst']").text('$ '+taxPST.toFixed(2));
	//$("#gst, label[for='gst']").text('$ '+taxGST.toFixed(2));
	
	return true;
}
    	
/*
jQuery.fn.enter2tab = function() 
 

 
    this.keypress(function(e){ 
    	
    	
    	
 
        // get key pressed (charCode from Mozilla/Firefox and Opera / keyCode in IE) 
 
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0; 
 
 
 
        var tmp = null; 
 
        var maxTabIndex = 96; 
 
 
 
        // get tabindex from which element keypressed 
 
        var nTabIndex=this.tabIndex+1; 
 
 
 
        // get element type (text or select) 
 
        var myNode=this.nodeName.toLowerCase(); 
 
 
 
        // allow enter/return key (only when in an input box or select) 
 
        if(nTabIndex > 0 && key == 13 && nTabIndex <= maxTabIndex && ((myNode == "textarea") || (myNode == "input") || (myNode == "select") || (myNode == "a"))) 
 
        { 
 
            for (var x=0; x<3; x++) 
 
            { 
 
                tmp = $("a[@tabIndex='"+nTabIndex+"'],textarea[@tabIndex='"+nTabIndex+"'],select[@tabIndex='"+nTabIndex+"'],input[@tabIndex='"+nTabIndex+"']").get(0); 
 
                if (typeof tmp != "undefined" && !$(tmp).attr("disabled")) 
 
                { 
 
                    $(tmp).focus(); 
 
                    return false; 
 
                    //break; 
 
                } 
 
                else 
 
                { 
 
                    nTabIndex++; 
 
                } 
 
            } 
 
            return false; 
 
        } 
 
        else if(key == 13) 
 
        { 
 
            return false; 
 
        } 
 
    }) 
 
    return this; 
 
}  
 */

