var ref;

﻿function login()
{
	dijit.byId('loginError').show();
}

function checkOrder(max_products) 
{
        var recipient;
        var products;
        var productsTotal;
        var total;
        var shippingCost;
        var allTotal;
        var confirm;
        var notice;
        var amount;

        ref = document.referrer;
        if (ref.indexOf('.net/en') != -1)
        {
            recipient = 'Recipient information';
            products = 'Products';
            productsTotal = 'Products total:';
            total = 'total';
            shippingCost = 'Shipping fee:';
            allTotal = 'Total:';
            confirm = 'Confirm your order';
            notice = 'Products will be mailed to your address when payment is <br />' +
		      'made to Los Niños del Sol Ry bank account <br />' +	
		      'IBAN FI54 5700 9520 0568 24, BIC OKOYFIHH.<br /><br />';
            amount = 'pcs';
        }
        else
        {
            recipient = 'Tilaajan tiedot';
            products = 'Tuotteet';
            productsTotal = 'Tuotteet yhteensä:';
            total = 'yhteensä';
            shippingCost = 'Postituskulut:';
            allTotal = 'Kaikki yhteensä:';
            confirm = 'Vahvista tilauksesi';
            notice = 'Tilaamanne tuotteet postitetaan antamaanne osoitteeseen kun maksu <br />' +
		      'on suoritettu yhdistyksen tilille. Pankkiyhteytemme on Los Niños del Sol Ry <br />' +	
		      '570095-256824 (IBAN FI54 5700 9520 0568 24, BIC OKOYFIHH).<br /><br />';
            amount = 'kpl';
        }

	if (validate('orderForm')) {
		var product = new Array();
		var size = new Array();
		var price = new Array();
		var quantity = new Array();
		var quality = new Array();

		var productsSelected = false;
		var position = 0;

		for (var i = 0; i < max_products; i++)
		{
			var id = 'product' + i;
			var id2 = 'quality' + i; 
			var current = dijit.byId(id).value.split(';');
			if (current[0].length > 0)
			{
				product[position] = current[0];
				size[position] = current[1];
				price[position] = current[2];
				quantity[position] = current[3];
				quality[position] = dijit.byId(id2);
				
				position++;
				productsSelected = true;
			}
		}

		if (productsSelected)
		{
			var msg;
			var totalPrice = 0;
			var cumulativeWeigth = 0.0;
			var cumulativePrice = 0;
			var postFee = 0;
			
			msg = '<b>' + recipient + '</b><br />' +
				  dojo.byId('fullname').value + '<br />' +
				  dojo.byId('address').value + '<br />' +
				  dojo.byId('city').value + '<br />' +
				  'P. ' + dojo.byId('phone').value + '<br />' +
				  dojo.byId('email').value + '<br />' +
				  '<br />' + 
				  '<b>' + products + '</b>';
				  
			for (var i = 0; i < product.length; i++)
			{
				totalPrice = parseFloat(price[i]) * parseFloat(quantity[i]);
				cumulativePrice += totalPrice;
				msg += '<br />' + 
					   product[i] + ', ' +  
					   quality[i] + ', ' +
					   quantity[i] + ' ' + amount + ', ' + 
					   total + ' ' + totalPrice.toFixed(2) + ' euro';
				cumulativeWeigth += size[i] * quantity[i];
			}
			msg += '<br /><br /><b>' + productsTotal + '</b><br />' + cumulativePrice.toFixed(2) + ' euro<br /><br />'; 
			
			/*
			if (cumulativeWeigth < 2)
				postFee = 6.80;
			else if (cumulativeWeigth < 5)
				postFee = 8.00;
			else 
				postFee = 10.00;
			*/
			
			if (cumulativeWeigth <= 1.5)
				postFee = 8.50;
			else 
				postFee = 10.05;
			
			cumulativePrice += postFee;
			msg += '<b>' + shippingCost+ '</b><br />' + postFee.toFixed(2) + ' euro<br /><br />' + 
				   '<b>' + allTotal + '</b><br />' + cumulativePrice.toFixed(2) + ' euro<br /><br />' +
				   notice;

			var url = '?content=' + msg + '&' + 
				  'email=' + dojo.byId('email').value + '&' + 
				  'rand=' + getRandomNumber();
                        
                        if (ref.indexOf('.net/en') != -1)
			    url = '../processorder.php' + url; 
                        else
                            url = 'processorder.php' + url;
			 	  
				  
			confirmOrder(confirm, msg, url);
		}
		else
		{
			dijit.byId('shopError').show();
		}
	}
	else {
		dijit.byId('shopError').show();
	}
}

/* Show "support LC" dialog */
function supportLC()
{
	dijit.byId('supportLC').show();
}

/* Utility function to raise a dialog asking the user a yes/no question. */
function confirmOrder(title, msg, url) 
{
        ref = document.referrer;

	var dialog = new dijit.Dialog({ id: 'dialog', title: title });
	var commonCallback = function(mouseEvent) {
		dialog.hide();
		dialog.destroyRecursive();
		
		var button;
		try
		{
			// FireFox
			button = mouseEvent.explicitOriginalTarget.id;
		}
		catch (ex)
		{
			// IE
			button = window.event.srcElement.id;
		}
		
		if (button == 'yesButton' || button == 'yesButton_label')  // _label to handle Google Chrome
		{
			dojo.xhrGet({
				url: url,
				handleAs: "text",
				handle: function(data, args){
					if (data)
					{
						if (data == 'true')
						{						
							dijit.byId('orderForm').reset();
							dojo.byId('fullname').value = '';
							dojo.byId('address').value = '';
							dojo.byId('city').value = '';
							dojo.byId('phone').value = '';
							dojo.byId('email').value = '';
							dijit.byId('shopSuccess').show();
						}
						else
						{
							//alert(data);
							dijit.byId('shopFailed').show();
						}
					}
					else
					{
						//alert(data);
						dijit.byId('shopFailed').show();
					}
				}
			});
		} 
	};
	
	var questionDiv = dojo.create('div', { innerHTML: msg });
        if (ref.indexOf('.net/en') != -1)
        {
	    var yesButton = new dijit.form.Button(
				{ label: '&nbsp;&nbsp;Order&nbsp;&nbsp;', id: 'yesButton', onClick: commonCallback });
	    var noButton = new dijit.form.Button(
				{ label: 'Cancel', id: 'noButton', onClick: commonCallback });
        }
        else
        {
            var yesButton = new dijit.form.Button(
				{ label: '&nbsp;&nbsp;Tilaa&nbsp;&nbsp;', id: 'yesButton', onClick: commonCallback });
	    var noButton = new dijit.form.Button(
				{ label: 'Peruuta', id: 'noButton', onClick: commonCallback });
        }

	dialog.containerNode.appendChild(questionDiv);
	dialog.containerNode.appendChild(yesButton.domNode);
	dialog.containerNode.appendChild(noButton.domNode);
	dialog.show();
}

/* Validate orde form fields */
function validate(form) 
{
    var isValid = dijit.byId(form).validate();
    if (isValid) return true;
    else return false;
}

/* Return random number (used to generate unique http calls) */
function getRandomNumber() 
{
    var stamp = new Date();
	stamp = stamp.getTime();
	return stamp;
}
