if (!window.Itw) var Itw = {};

Itw.showProgress = function(s) {
	if (!s) s = Itw.LoadingMsg;
	jQuery('#notifications').attr('class', 'notify-progress').text(s).fadeIn('fast');
};

Itw.showError = function(s) {
	jQuery('#errorPopup p').text(s);
	Itw.Popup.open(jQuery('#errorPopup'), 300, 200);
};

Itw.hideProgress = function() {
	jQuery("#notifications").fadeOut("slow");
};

Itw.showCartStatus = function(text) {
	$("#cart-status-message").text(text);
	$("#cart-status-icon :first-child").show();
}

Itw.hideCartStatus = function() {
	$("#cart-status-message").text('');
	$("#cart-status-icon :first-child").hide();
}

Itw.Order = {

	pay: function() {
		if (jQuery('#paymentForm').valid()) {
	        var json = jQuery.toJSON(Itw.Order._form2payment());
	        jQuery('#payment-btn').attr('src', Itw.Context.path + 'images/' + Itw.Context.locale + '/btn-do-payment-disabled.png');
	        jQuery('#payment-btn').attr('disabled', 'disabled');
	        jQuery.post(jQuery('#paymentForm').attr('action'), { 'payment': json }, Itw.Order.handlePaymentResult, 'json');	        
	        Itw.showProgress();
		}
    },
    
    place: function() {
    	var order = Itw.Order._form2order();
    	if (order.itemsDTO.length == 0) {
    		Itw.showError("The cart is empty");
    		return false;
    	} else {
            jQuery('#order').val(jQuery.toJSON(order));
            return true;    		
    	}
    },

    putItem: function(id) {
    	Itw.showProgress();
    	jQuery.ajax({
    		  url: Itw.Context.path + 'cart/put',
    		  type: 'POST',
    		  data: { 'id' : id },
    		  success: function(result) {
    			  Itw.hideProgress();
    		      jQuery('#cart-panel').html(result);
    		  },
              error: function(ret) {
    			  Itw.hideProgress();
                  Itw.showError(ret.status + ": " + ret.statusText);
              }
		});
    },
    
    // Hack per forzare un delay sull'evento onkeypup delle textbox nelle quali si inseriscono le quantita'.
    // updateItemHandler registra globalmente l'id della chiamata e, con un leggero ritardo, chiama updateItemDelayed.
    // Se al momento in cui viene eseguita updateItemDelayed, l'id globale è cambiato, significa che updateItemHandler
    // è stato chiamato una seconda volta (cioè: l'utente sta ancora inviando eventi onkeyup, scrivendo nella textbox)
    // e updateItemDelayed esce, altrimenti updateItemDelayed chiama l'handler vero e proprio che aggiorna il carrello.
    
    eventId: 0,
    
    updateItemHandler: function(id, qty) {
    	if (!isNaN(parseInt(qty))) {
        	Itw.Order.eventId = new Date().getMilliseconds();
        	setTimeout('Itw.Order.updateItemDelayed(' + id + ', ' + qty + ', ' + Itw.Order.eventId + ')', 350);
    	}    
    },
    
    updateItemDelayed: function(id, qty, eventId) {
    	if (eventId == Itw.Order.eventId) {
    		Itw.Order.eventId = 0;
    	    Itw.Order.updateItem(id, qty);
    	}
    },    
    
    updateItem: function(id, qty) {
    	
    	qty = parseInt(qty);
    	
    	if (isNaN(qty)) {
    		return;
    	}
    	
    	Itw.showProgress();
    	jQuery.ajax({
    		  url: Itw.Context.path + 'cart/update',
    		  type: 'POST',
    		  data: { 'id' : id, 'qty' : parseInt(qty) },
    		  success: function(result) {
    			  Itw.hideProgress();
    		      jQuery('#cart-panel').html(result);
    		  },
              error: function(ret) {
    			  Itw.hideProgress();
    			  Itw.showError(ret.status + ": " + ret.statusText);
              }
		});
    },

    removeItem : function(id) {
    	Itw.Order.updateItem(id, 0);
    },
    
    applyDiscountCode: function() {
    	if (jQuery('#discount_code').val()) {
	    	jQuery('#apply').hide();
	    	Itw.Order.updateCharges();
    	}
    },

    handlePaymentResult: function(result) {
        Itw.hideProgress();
        if (result.isOk) {
            location.href = Itw.Context.path + 'confirmed';
        } else if (result.isSystemError) {
        	location.href = Itw.Context.path + 'error';
        } else {
            jQuery('#error_label').html(Itw.PayBankErrorMsg + ' ' + result.resultMessage);
			jQuery('#payment-btn').attr('src', Itw.Context.path + 'images/' + Itw.Context.locale + '/btn-do-payment.png');
			jQuery('#payment-btn').attr('disabled', '');        
        }
    },

    updateCharges: function() {
        
    	var country = jQuery('#shipping_country').val();
        var isACompany = jQuery('#is_a_company').is(':checked');
        var requestData = { country: country, isACompany: isACompany };

        Itw.showProgress();

        if (Itw.Order.isCountryOutsideEU(country))
            Itw.Order.hideTaxWarning();
        else
            Itw.Order.displayTaxWarning();

        jQuery.ajax({
            url: Itw.Context.path + 'cart/updateOrderCharges',
            type: 'POST',
            data: requestData,
            success: function(result) {
        	 	Itw.hideProgress();
        	 	jQuery('#cart-panel').html(result);
            },
            error: function(result) {
            	Itw.hideProgress();
                Itw.showError(ret.status + ": " + ret.statusText);
            }
        });
        return false;
    },

    displayTaxWarning: function() {
        jQuery('#tax-warning').fadeIn('fast');
    },

    hideTaxWarning: function() {
        jQuery("#tax-warning").fadeOut("fast");
    },

    isCountryOutsideEU: function(country) {
        var euCountries = {"AT":0, "BE":0, "BG":0, "CY":0, "DK":0, "EE":0, "DE":0, "FI":0, "FR":0,
            "GB":0, "IE":0, "LV":0, "LT":0, "LU":0, "MT":0, "NL":0, "PL":0, "PT":0,
            "CZ":0, "SK":0, "RO":0, "SI":0, "ES":0, "SE":0, "HU":0, "GR":0, "IT":0};
        return country in euCountries;
    },

    _form2payment: function() {
        var payment = Itw.Order.newPayment();
        payment.creditCardNumber = jQuery('#cc_nr').val();
        payment.creditCardOwnerFullName = jQuery('#cc_name').val();
        payment.cvv = jQuery('#cc_cvv').val();
        payment.twoDigitsYear = jQuery('#cc_year').val();
        payment.month = jQuery('#cc_month').val();
        return payment;
    },

    _form2order: function() {
    	
        var order = Itw.Order.newOrder();

        order.customerDTO.firstname = jQuery("#firstname").val();
        order.customerDTO.lastname = jQuery("#lastname").val();
        order.customerDTO.email = jQuery("#email").val();
        order.customerDTO.phone = jQuery("#contacts").val();
        order.customerDTO.isCompany = jQuery("#is_a_company").is(":checked");
        order.comment = jQuery("#comment").val();

        var sh_street = jQuery("#shipping_address1").val();
        var in_street = jQuery("#invoicing_address1").val();

        order.shippingAddressDTO = Itw.Order.newAddress(sh_street, jQuery("#shipping_nearby").val(), jQuery("#shipping_postcode").val(),
                jQuery("#shipping_city").val(), jQuery("#shipping_province").val(), jQuery("#shipping_country").val());

        if (jQuery("#is_a_company").is(":checked")) {
            order.customerDTO.companyName = jQuery("#company_name").val();
            order.customerDTO.vatNumber = jQuery("#vat_number").val();
            order.customerDTO.taxCode = jQuery("#tax_code").val();
        }

        if ((jQuery("#is_a_company").is(":checked") && jQuery("#is_using_shipping_data").is(":checked")) || !jQuery("#is_a_company").is(":checked")) {
            order.invoicingAddressDTO = Itw.Order.newAddress(sh_street, jQuery("#shipping_nearby").val(), jQuery("#shipping_postcode").val(),
                    jQuery("#shipping_city").val(), jQuery("#shipping_province").val(), jQuery("#shipping_country").val());
        } else {
            order.invoicingAddressDTO = Itw.Order.newAddress(in_street, "", jQuery("#invoicing_postcode").val(),
                    jQuery("#invoicing_city").val(), jQuery("#invoicing_province").val(), jQuery("#invoicing_country").val());
        }

        order.itemsDTO = [];

        var quantities = Itw.Order.selectQuantities(); 
        for (var i = 0; i < quantities.length; i++) {
        	var pos = quantities[i].name.indexOf('_');
        	var productId = quantities[i].name.substring(pos + 1); 
        	if (pos < quantities[i].name.length-1) {
        		order.itemsDTO.push({ "productId" : productId, "quantity" : quantities[i].value });
        	}
        }

        return order;
    },

    selectQuantities: function() {
    	return jQuery("input[name^='qty_']");
    },
    
    newAddress: function(street, nearby, zipCode, city, provinceState, country) {
        return { "street" : street, "nearby" : nearby, "zipCode" : zipCode, "city" : city, "provinceState" : provinceState, "country" : country };
    },

    newPayment: function() { 
    	return { 
    		"orderId" : null, 
    		"creditCardNumber" : null, 
    		"creditCardOwnerFullName" : null,
    		"creditCardOwnerEmail" : null,
    		"twoDigitsYear" : null, 
    		"month" : null, 
    		"cvv" : null  
		};
    },
    
    newOrder: function() {
        return {
            "trackingNumber": "",
            "itemsDTO" : [],
            "comment" : "",
            "customerDTO": {
                "firstname": "",
                "lastname" : "",
                "phone" : "",
                "email" : "",
                "vatNumber" : "",
                "sellingRegion" : "Italy",
                "companyName" : "",
                "taxCode" : "",
                "isCompany": false
            },
            "shippingAddressDTO": {
                "street" : "",
                "nearby" : "",
                "zipCode" : "",
                "city" : "",
                "provinceState" : "",
                "country" : ""
            },
            "invoicingAddressDTO": {
                "street" : "",
                "nearby" : "",
                "zipCode" : "",
                "city" : "",
                "provinceState" : "",
                "country" : ""
            }
        };
    }
};

Itw.Popup = {
	open: function(dialog, width, height) {
		var w = document.documentElement.clientWidth;
		var h = document.documentElement.clientHeight;
		var background = $("#popupBackground"); 
		dialog.css({ 'width': width, 'height': height, 'position': 'absolute', 'top': h/2 - height/2, 'left': w/2 - width/2 });
		background.css({ 'width': w, 'height': h, 'opacity': 0.7 });
		background.fadeIn('slow');
		dialog.fadeIn('slow');
	},

	close: function() {
		jQuery('#popupBackground').fadeOut('fast');
		jQuery('.popup').fadeOut('fast');
	}
};



