YAHOO.util.Event.onDOMReady(init);
var myDataTable;

function init()
{
	createCart( sShoppingCart );
}

/**
* Creates the shopping cart
*/
function createCart( aCartData )
{
	var aData = new Array();
	for (var item in aCartData)
	{
		if (item in Object.prototype) continue;
		if (aCartData[item]['amount'] != undefined)
		{
			var id = aCartData[item]['id_product'];
			var name = aCartData[item]['name']; 
			var quantity = aCartData[item]['amount'];
			aData.push( {id: id,name: name,quantity: quantity,remove:"<img src='"+document.getElementById('path_images').value+"b_drop.png' style='cursor:pointer;'/>"} );
		}
	}
	
	YAHOO.SHOPPING_CART = new function() {
        var myColumnDefs = [
            {key:"id", label:'Id'},
            {key:"name", label:'Prod.'},
            {key:"quantity", label:'Cant.'},
            {key:"remove", label:''}
        ];
		
        this.myDataSource = new YAHOO.util.DataSource( aData );
        this.myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
        this.myDataSource.responseSchema = {
            fields: ["id","name","quantity","remove"]
        };
        
        myDataTable = new YAHOO.widget.DataTable("div_shopping_cart",myColumnDefs, this.myDataSource);
        
      	myDataTable.subscribe('cellClickEvent',myDataTable.onEventShowCellEditor);
        
		myDataTable.subscribe('cellClickEvent',function(ev) {
		    var target = YAHOO.util.Event.getTarget(ev);
		    var column = myDataTable.getColumn(target);
		    if (column.key == 'remove') {
		        if (confirm('Seguro?')) {
		        	
		        	var oRecord = myDataTable.getRecord(target);
		            var aData = oRecord.getData();
		            
		        	removeFromCart( aData['id'] );
		        	
		            //delete the row
		            myDataTable.deleteRow(target);
		        }
		    } else {
		        myDataTable.onEventShowCellEditor(ev);
		    }
		});
		
		myDataTable.hideColumn("id");
	};
}

/**
* Add an item to the cart
*/
function addCart(id_product)
{
	var amount = document.getElementById('cart_quantity_' + id_product).value;
	
	document.getElementById('div_loading_cart').style.display = 'block';
	
	if (amount > 0)
	{
		var oCallback = { 
						    success: function(o) { 
						    	var results = YAHOO.lang.JSON.parse(o.responseText);
						    	
						    	document.getElementById('div_loading_cart').style.display = 'none';
						    	
						    	if (results['success'] == false)
									alert(results['message']);
						    	else
						    	{
									createCart( results['aCart'] );

									document.getElementById('cart_quantity_' + id_product).value = 1;
									document.getElementById('div_cart_quantity_' + id_product).innerHTML = results['iAmountProduct'];
									document.getElementById('div_cart_price_quantity_' + id_product).innerHTML = roundNumber(results['dPricePerAmount'] * results['iAmountProduct'], 2);
									if (document.getElementById('div_sub_total') != null )
										document.getElementById('div_sub_total').innerHTML = results['dSubTotal'];
										
									calculateTotal();
						    	}
						    }, 
						    failure: function(o) { 
						        var results = YAHOO.lang.JSON.parse(o.responseText); 
						        
						        document.getElementById('div_loading_cart').style.display = 'none';
						        
						        alert(results['message']);
						    }, 
						    scope: this, 
						    argument: this.login_name 
						}
		var dataSource = document.getElementById('form1').action + 'cart/add-to-cart/';
		
		var postData = 'amount=' + amount + '&id_product=' + id_product;
		
		var request = YAHOO.util.Connect.asyncRequest('POST', dataSource, oCallback, postData);
	}
	else
	{
		showMessage('Tiene que ingresar un producto por lo menos!');
	}
}

/**
* Remove an item from the cart
*/
function removeFromCart(id_product) {
	document.getElementById('div_loading_cart').style.display = 'block';
	
	var oCallback = { 
					    success: function(o) { 
					    	var results = YAHOO.lang.JSON.parse(o.responseText);
					    	
					    	document.getElementById('div_loading_cart').style.display = 'none';
					    	
					    	if (results['success'] == false)
								alert(results['message']);
					    	else
					    	{
								createCart( results['aCart'] );
								
								//var id_product = results['id_product'];
								
								if (document.getElementById('div_cart_quantity_' + id_product) != null )
									document.getElementById('div_cart_quantity_' + id_product).innerHTML = 0;
								
								if (document.getElementById('div_cart_price_quantity_' + id_product) != null)
									document.getElementById('div_cart_price_quantity_' + id_product).innerHTML = 0;
									
								if (document.getElementById('div_sub_total') != null )
									document.getElementById('div_sub_total').innerHTML = results['dSubTotal'];
									
								calculateTotal();
					    	}
					    }, 
					    failure: function(o) { 
					        var results = YAHOO.lang.JSON.parse(o.responseText); 
					        
					        document.getElementById('div_loading_cart').style.display = 'none';
					        
					        alert(results['message']);
					    }, 
					    scope: this, 
					    argument: this.login_name 
					}

	var dataSource = document.getElementById('form1').action + 'cart/remove-from-cart/';
	
	var postData = 'id_product=' + id_product;
	
	var request = YAHOO.util.Connect.asyncRequest('POST', dataSource, oCallback, postData);	
}

/**
* According to the delivery type, they have to select where is it going to be delivered the products
*/
function setDeliveryType(id_delivery_type, id_delivery)
{
	var oCallback = { 
					    success: function(o) { 
					    	var results = YAHOO.lang.JSON.parse(o.responseText);
					    	
					    	if (results['success'] == false)
								alert(results['message']);
					    	else
					    	{
					    		populateDeliveryAddressesSelect(results['aAddresses']);					    		
								populatePaymentTypeSelect(results['aPaymentTypes']);								
								
								if (id_delivery == id_delivery_type)
								{
									document.getElementById('id_extra_price_delivery').disabled = false;
									
									var places = document.getElementById('id_extra_price_delivery');
									var id_extra_price_delivery = places.options[places.selectedIndex].value;
									getDeliveryPrice(id_extra_price_delivery);
									//document.getElementById("div_delivery_address_legend").style.visibility = 'hidden';
								}
								else
								{
									document.getElementById("div_delivery_place_legend").style.visibility = 'hidden';
									document.getElementById('id_extra_price_delivery').disabled = true;
									getDeliveryPrice(0);
								}
								
					    	}
					    }, 
					    failure: function(o) { 
					        var results = YAHOO.lang.JSON.parse(o.responseText); 
					        alert(results['message']);
					    }, 
					    scope: this, 
					    argument: this.login_name 
					}

	var dataSource = document.getElementById('form1').action + 'cart/set-delivery-type/';
	
	var postData = 'id_delivery_type=' + id_delivery_type;
	postData+= '&id_extra_price_delivery=' + $('#id_extra_price_delivery').val();
	
	var request = YAHOO.util.Connect.asyncRequest('POST', dataSource, oCallback, postData);
}

function populateDeliveryAddressesSelect(aAddresses)
{
	document.getElementById('address').options.length = 0;
	for (var id in aAddresses)
	{
		if (aAddresses[id]['address'] == undefined) continue;
		
		var optn = document.createElement("OPTION");
		optn.text = aAddresses[id]['address'];
		optn.value = aAddresses[id]['id'];
		optn.title = aAddresses[id]['legend'];
		document.getElementById('address').options.add(optn);
	}
	
	if ($('#address').val() == 'new')
		$('.tr-address').show();
	else
		$('.tr-address').hide();
}

function populatePaymentTypeSelect(aPaymentTypes)
{
	document.getElementById('payment').options.length = 0;
	for (id in aPaymentTypes)
	{
		if (aPaymentTypes[id]['name'] == undefined) continue;
		
		var optn = document.createElement("OPTION");
		optn.text = aPaymentTypes[id]['name'];
		optn.value = aPaymentTypes[id]['id_payment_type'];
		document.getElementById('payment').options.add(optn);
	}
	
	document.getElementById('div_extra_payment_type').innerHTML = 0;
}

/**
* Confirm order
*/
function confirmTermsAndConditions()
{
	/*** si quedo guardada una sesion anterior y no se actualizo el navegador, no se van a mostrar los campos dinamicamente. entonces no dejo que confirme la compra.***/
	/*if(document.getElementById('tipo_factura_a').checked == true && document.getElementById('cuit_a')==null){
		alert("Debido a actualizaciones de D+LED, ud. necesita eliminar las cookies y cache de su navegador. Si no sabe como borrar las cookies y la cache de su navegador, entre a http://braulioaquino.com/2009/01/como-eliminar-cookies-y-cach")
		return false;	
	}
	
	if (document.getElementById('tipo_factura_b').checked == true && document.getElementById('cuit_b')==null){
		alert("Debido a actualizaciones de D+LED, ud. necesita eliminar las cookies y cache de su navegador. Si no sabe como borrar las cookies y la cache de su navegador, entre a http://braulioaquino.com/2009/01/como-eliminar-cookies-y-cach")
		return false;	
	}*/
	/**************************************************************************************************************************************************/
	
	//var is_agree = document.getElementById('is_agree').checked?1:0;
	
	if ($('#is_agree').is(':checked'))
		confirmOrderMessage();
	else
		alert('Tiene que aceptar los Terminos y Condiciones');
}

/**
* Show the Confirmation Message
*/
function confirmOrderMessage()
{
	calculateTotal();
	
	var total = document.getElementById('div_total').innerHTML;
	
	if (confirm("Confirmar compra? Total $" + total))
	{
		confirmOrder();
	}
}

function confirmOrder(isBudget)
{
	if (isBudget == undefined)
		isBudget = false;
	
	var delivery_types = document.getElementById('id_delivery_type');
	var id_delivery_type = delivery_types.options[delivery_types.selectedIndex].value;
	
	var address = document.getElementById('address');
	var id_address = 0;
	if (address.options.length > 0)
		id_address = address.options[address.selectedIndex].value;
	
	var payment = document.getElementById('payment');
	var id_payment = payment.options[payment.selectedIndex].value;
	var div_extra_payment_type = document.getElementById('div_extra_payment_type').innerHTML;	
	
	var places = document.getElementById('id_extra_price_delivery');
	var id_extra_price_delivery = 0;
	if (places.disabled == false)
		id_extra_price_delivery = places.options[places.selectedIndex].value;
	
	var comments = document.getElementById('comments').value;
	
	var total = document.getElementById('div_total').innerHTML;
	
	var dollar_quote = document.getElementById('dollar_quote').value;
	
	document.getElementById('div_loading').style.display = 'block';
	
	var oCallback = { 
				    success: function(o) { 
				    	var results = YAHOO.lang.JSON.parse(o.responseText);
				    	
				    	document.getElementById('div_loading').style.display = 'none';
				    	
				    	if (results['success'] == false)
				    		alert(results['message']);
				    	else
			    		{
				    		$('#table-confirm-order').hide();
				    		window.location.href = document.getElementById('form1').action + 'client/history/?dtpm=1';				    		
			    		}
				    }, 
				    failure: function(o) { 
				        var results = YAHOO.lang.JSON.parse(o.responseText); 
						document.getElementById('div_loading').style.display = 'none';
				        alert(results['message']);
				    }, 
				    scope: this, 
				    argument: this.login_name 
				}
					
	var dataSource = document.getElementById('form1').action + 'cart/confirm-order/';
	
	var postData = 'id_delivery_type=' + id_delivery_type;
	postData+= '&id_address=' + id_address;
	postData+= '&id_payment=' + id_payment;
	postData+= '&comments=' + comments;
	postData+= '&id_extra_price_delivery=' + id_extra_price_delivery;
	postData+= '&total=' + total;
	postData+= '&extra_payment_type=' + div_extra_payment_type;
	postData+= '&dollar_quote=' + dollar_quote;
	
	//Get business information
	postData+= '&tfact=' + $("#tfact").val();
	
	if ($('#country_valued_added_tax_mandatory').val() == '1' || $("#tfact").val() != '')
	{
		postData+= '&id_number=' + $("#id_number").val();
		postData+= '&legal_name=' + $("#legal_name").val();
		postData+= '&business_category=' + $("#business_category").val();
		postData+= '&id_country_business=' + $("#id_country_business").val();
		postData+= '&id_state_business=' + $("#id_state_business").val();
		postData+= '&city_business=' + $("#city_business").val();
		postData+= '&locality_business=' + (($("#locality_business").val()!=undefined)?$("#locality_business").val():'');
		postData+= '&address_business=' + $("#address_business").val();
		postData+= '&number_business=' + $("#number_business").val();
		postData+= '&floor_business=' + $("#floor_business").val();
		postData+= '&department_business=' + $("#department_business").val();
		postData+= '&zip_code_business=' + $("#zip_code_business").val();
		postData+= '&other_state_business=' + $("#other_state_business").val();
	}
	
	if ($('#address').val() == 'new')
	{
		postData+= '&id_country_new=' + $("#id_country_new").val();
		postData+= '&id_state_new=' + $("#id_state_new").val();
		postData+= '&city_new=' + $("#city_new").val();
		postData+= '&locality_new=' + (($("#locality_new").val()!=undefined)?$("#locality_new").val():'');
		postData+= '&address_new=' + $("#address_new").val();
		postData+= '&number_new=' + $("#number_new").val();
		postData+= '&floor_new=' + $("#floor_new").val();
		postData+= '&department_new=' + $("#department_new").val();
		postData+= '&zip_code_new=' + $("#zip_code_new").val();
		postData+= '&other_state_new=' + $("#other_state_new").val();
	}

	postData+= '&is_budget=' + isBudget;
	
	var request = YAHOO.util.Connect.asyncRequest('POST', dataSource, oCallback, postData);
}

function selectExtraPaymentType(id_payment_type)
{
	var oCallback = { 
				    success: function(o) { 
				    	var results = YAHOO.lang.JSON.parse(o.responseText);
				    	
				    	if (results['success'] == false)
							alert(results['message']);
				    	else
						{
							document.getElementById('div_extra_payment_type').innerHTML = results['extra_percentage'];
							
							calculateTotal();
						}
				    }, 
				    failure: function(o) { 
				        var results = YAHOO.lang.JSON.parse(o.responseText); 
				        alert(results['message']);
				    }, 
				    scope: this, 
				    argument: this.login_name 
				}
					
	var dataSource = document.getElementById('form1').action + 'cart/get-extra-payment/';
	
	var places = document.getElementById('id_extra_price_delivery');
	var id_extra_price_delivery = places.options[places.selectedIndex].value;
									
	var postData = 'id_payment_type=' + id_payment_type + "&id_extra_price_delivery=" + id_extra_price_delivery;
		
	var request = YAHOO.util.Connect.asyncRequest('POST', dataSource, oCallback, postData);	
}


function getDeliveryPrice(id_extra_price_delivery)
{
	var oCallback = { 
				    success: function(o) { 
				    	var results = YAHOO.lang.JSON.parse(o.responseText);
				    	
				    	if (results['success'] == false)
							alert(results['message']);
				    	else
						{
							document.getElementById('div_extra_delivery').innerHTML = results['price'];
							
							if (results['comments'] != null)
							{
								if (results['comments'] != "")
									document.getElementById('div_delivery_place_legend').style.display = 'inline';
								else
									document.getElementById('div_delivery_place_legend').style.display = 'none';
								
								document.getElementById('div_delivery_place_legend').innerHTML = results['comments'];
							}
							else
								document.getElementById('div_delivery_place_legend').style.display = 'none';
							
							populatePaymentTypeSelect(results['aPaymentTypes']);
							
							calculateTotal();
						}
				    }, 
				    failure: function(o) { 
				        var results = YAHOO.lang.JSON.parse(o.responseText); 
				        alert(results['message']);
				    }, 
				    scope: this, 
				    argument: this.login_name 
				}

	document.getElementById('payment').selectedIndex = 0;
	document.getElementById('div_extra_payment_type').innerHTML = 0;
	
	var dataSource = document.getElementById('form1').action + 'cart/get-extra-delivery/';
	
	var postData = 'id_extra_price_delivery=' + id_extra_price_delivery;
	postData+= '&id_delivery_type=' + $('#id_delivery_type').val();
		
	var request = YAHOO.util.Connect.asyncRequest('POST', dataSource, oCallback, postData);	
}

function calculateTotal()
{
	var postData = "id_delivery_type=" + $('#id_delivery_type').val(); 
	postData+= "&id_extra_price_delivery=" + (($('#id_extra_price_delivery').is(':enabled')) ? $('#id_extra_price_delivery').val() : 0);
	postData+= "&id_payment_type=" + $('#payment').val();
	postData+= "&tfact=" + $('#tfact').val();
	
	$.ajax({
	   type: "POST",
	   url: document.getElementById('form1').action + 'cart/get-total/',
	   data: postData,
	   success: function(data){
		   $('#div_total').text(data['total']);
		   $('#div_total_usd').text(data['total_usd']);
	   }
	 });
}

//function that will round to certain decimal points
function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function getFactDetails(){	
	if(document.getElementById('tipo_factura_a').checked == false && document.getElementById('tipo_factura_b').checked == false)
		return '';
	
	if(document.getElementById('tipo_factura_a').checked == true)
		return '&tfact=A'+'&cuit='+document.getElementById('cuit_a').value+'&legal_name='+document.getElementById('raz_soc_a').value+'&legal_address='+document.getElementById('dom_fisc_a').value;
		
	if(document.getElementById('tipo_factura_b').checked == true)
		return '&tfact=B'+'&cuit='+document.getElementById('cuit_b').value+'&legal_name='+document.getElementById('raz_soc_b').value+'&legal_address='+document.getElementById('dom_fisc_b').value;
	
}

function generateBudget()
{
	confirmOrder(true);
}
