/**
 * Checkout.js - Toppoint proposal/order form behavior
 * 
 * @author Webstores <info at webstores dot nl>
 *         Copyright (c) Webstores internet totaalbureau <http://www.webstores.nl/>
 */
function CheckoutForm(id) {
	this.formId = id;
	this.form = jQuery(id);
	this.maxFiles = 3;
	this.fileCount = 1;
	this.init();
    this.request = Array();
};

CheckoutForm.prototype = {
	/**
	 * @constructor
	 */
	init: function() {
		if(this.form.length) {
			switch(this.form.attr('name')) {
				case 'checkout-step1':
					jQuery('#reorder-number, #quantities, #quantity-table-1, #quantity-table-2, #quantity-controls .remove-icon, #dimension-lengthwidth, #dimension-diameter, #addtocart, .stock-row').not('.expanded').hide();
					jQuery('#order-blank-text, #order-monster-text').not('.expanded').hide();
					//jQuery('#quantities:hidden input.quantity').not('.expanded input.quantity').attr('disabled', true);
                    jQuery('input.diameter').not('.expanded input.diameter').attr('disabled', true);
                    jQuery('input.width').not('.expanded input.width').attr('disabled', true);
                    jQuery('input.length').not('.expanded input.length').attr('disabled', true);
					this.addEventListenersStepOne();
					break;
				case 'checkout-step2-position':
					jQuery('#color-quantity, #colorswitch-quantity, #samelogoas-properties, #print-properties, #print-properties tr.color, tr.color-switch, #variable-1, #variable-2, #print-properties tr.file:not(tr#file-0), #dimension-rectangular, #dimension-circular').not('.expanded').hide();
					this.addEventListenersStepTwo();
					break;
				case 'checkout-step3':
					this.addEventListenersStepThree();
					break;
				case 'customer-proposal':
					jQuery('#fixed-proposal, #carbon-copy-email').not('.expanded').hide();
					this.addEventListenersCustomerProposal();
					break;
                case 'superuser':
					this.addEventListenersSuperuser();
                    break;
			}
			
			// General event listeners
			jQuery('#reminder-table .sub').not('.expanded').hide();
			this.addEventListenersGeneral();
			
			// Global AJAX settings
			jQuery.ajaxSetup({
				url: this.form.attr('action'),
				cache: false,
				dataType: 'json',
				context: this
			});
		}
	},
	
	/**
	 * Add event listeners for step 1
	 */
	addEventListenersStepOne: function() {
		var self = this;

		jQuery('#tostep2').click(function(event) {
			if (jQuery('#quantity').val() > 20000 && confirm(lang.confirmLargeOrder) === false) {
				event.preventDefault();
			}
		});
		
		jQuery('#order-type').change(function() {
			self.orderTypeChangeHandler(this);
		});
		
		jQuery('input[name="data[Order][reorder]"]').click(function() {
			self.reorderClickHandler(this);
		});
		
		jQuery('.colors input[type="checkbox"]').click(function() {
			self.colorClickHandler(this);
		});
		
		jQuery('.quantity-table tr').not('.expanded,.total').hide();
		
		jQuery('.quantity-table input.quantity').keyup(function() {
			self.quantityKeyupHandler(this);
		});
		
		jQuery('#quantity-controls .add-icon').click(function(e) {
			e.preventDefault();
			self.quantityAddClickHandler();
		});
		
		jQuery('#quantity-controls .remove-icon').click(function(e) {
			e.preventDefault();
			self.quantityRemoveClickHandler();
		});

        jQuery('#order-shape').change(function() {
            self.orderShapeChangeHandler(this);
        });

        jQuery('.width').keyup(function() {
            if (jQuery('#order-shape').val() == 3) {
                jQuery('.length').val(jQuery('.width').val());
            }
        });

        jQuery('.length').keyup(function() {
            if (jQuery('#order-shape').val() == 3) {
                jQuery('.width').val(jQuery('.length').val());
            }
        });
	},
	
	/**
	 * Add event listeners for step 2 position
	 */
	addEventListenersStepTwo: function() {
		var self = this;
		
		jQuery('#product-part').change(function() {
			self.productPartChangeHandler(this);
		});
		
		jQuery('#print-method').change(function() {
			self.printMethodChangeHandler(this);
		});
		
		self.addPositionEventListeners();

		jQuery('#color-quantity-select').change(function() {
			self.colorQuantityChangeHandler(this);
		});
		
		jQuery('input.switch-color').click(function() {
			self.colorSwitchClickHandler(this);
		});

		jQuery('#samelogoas').change(function() {
			self.sameLogoAsChangeHandler(this);
		});
		
		jQuery('#add-file').click(function(e) {
			e.preventDefault();
			self.addFileClickHandler();
		});
		
		jQuery('tr.file .delete').click(function(e) {
			e.preventDefault();
			self.removeFileClickHandler(this);
		});
		
		jQuery('#variable-1-select').change(function() {
			self.variableOneChangeHandler(this);
		});
	},
	
	/**
	 * Add event listeners for step 3
	 */
	addEventListenersStepThree: function() {
		var self = this;
		
        jQuery('input[name="data[Order][transmit-time]"]').click(function() {
            if (this.value == 0) {
                // jQuery('#sample').attr('disabled', false);

                jQuery('#proof').attr('disabled', false);
            } else {
                // jQuery('#sample').val(0);
                // jQuery('#sample').attr('disabled', true);

                jQuery('#proof').val(0);
                jQuery('#proof').attr('disabled', true);
            }
        });

        jQuery('input[name="data[Offer][transmit-time]"]').click(function() {
            if (this.value == 0) {
                // jQuery('#sample').attr('disabled', false);
            } else {
                // jQuery('#sample').val(0);
                // jQuery('#sample').attr('disabled', true);
            }
        });

		jQuery('#pickup').click(function() {
			self.pickupClickHandler(this);
		});
	},
	
	/**
	 * Add event listeners for customer proposal
	 */
	addEventListenersCustomerProposal: function() {
		var self = this;

		jQuery('input[name="data[Customer][proposalType]"]').click(function() {
			self.proposalTypeClickHandler(this);
		});
		
		// Input name end with "][factor]"
		jQuery('input[name$="][factor]"]').keyup(function() {
			self.factorKeyupHandler(this);
		});
        jQuery('input[name$="][factor]"]').change(function() {
            if (this.value.replace(/,/g, '.') < this.title) {
                alert(lang.minimumFactor + ' ' + this.title);
            }
        });
        // Checkbox name end with "][active]"
        jQuery('input[name$="][active]"]').change(function() {
			self.factorKeyupHandler(this);
        });

		jQuery('#sender').change(function() {
            if (this.value == 0) {
                jQuery('#carbon-copy-email').show();
            } else {
                jQuery('#carbon-copy-email').hide();
            }
        });
	},

	/**
	 * Add event listeners for customer proposal
	 */
	addEventListenersSuperuser: function() {
		var self = this;

		// Input name begins with "data[SuperUser]"
		jQuery('#superuser-table input[name^="data[SuperUser]"]').keyup(function() {
			self.superuserKeyupHandler(this);
		});
	},

	/**
	 * Add event listeners for all or multiple steps
	 */
	addEventListenersGeneral: function() {
		var self = this;
		
		jQuery('input#reminder').click(function() {
			self.reminderClickHandler(this);
		});
		
		// Moved from step 3 to general
		jQuery('#existing-address').change(function() {
			self.existingAddressChangeHandler(this);
		});
	},
	
	/**
	 * When the order type select fires onchange
	 * 
	 * @param {Object} el The HTMLSelectElement
	 */
	orderTypeChangeHandler: function(el) {
		if(el.value == 'print') {
			jQuery('#addtocart').hide();
			jQuery('#reorder').show();
            jQuery('#li-tostep2').show();
			this.reorderClickHandler();
		}
		else {
			jQuery('#addtocart').show();
			jQuery('#reorder, #reorder-number').hide();

            if (jQuery('#hasBlank').val() == 1 || jQuery('#hasMonster').val() == 1) {
                jQuery('#li-tostep2').hide();
            } else {
                jQuery('#li-tostep2').show();
            }
		}

        jQuery('#order-monster-text').hide();
        jQuery('#order-blank-text').hide();
        if (el.value == 'blank') {
            /*if (jQuery('#hasBlank').val() == 1) {
                jQuery('#li-tostep2').hide();
            } else {
                jQuery('#li-tostep2').show();
            }*/
            jQuery('#order-blank-text').show();
        } else if (el.value == 'sample') {
            /*if (jQuery('#hasMonster').val() == 1) {
                jQuery('#li-tostep2').hide();
            } else {
                jQuery('#li-tostep2').show();
            }*/
            jQuery('#order-monster-text').show();
        }
	},
	
	/**
	 * When one of the reorder radio buttons fires onclick
	 * 
	 * @param {Object} el The HTMLInputElement
	 */
	reorderClickHandler: function(el) {
		(jQuery('input[name="data[Order][reorder]"]:checked').attr('id') == 'reorder-yes') ? jQuery('#reorder-number').show() : jQuery('#reorder-number').hide();
	},

    /**
     * When the order shape select fires onchange
     *
     * @param {Object} el The HTMLSelectElement
     */
    orderShapeChangeHandler: function(el) {
        jQuery('#dimension-lengthwidth, #dimension-diameter').hide();
        jQuery('input.length, input.width, input.diameter').attr('disabled', true);

        if (el.value == 3) {
            jQuery('.length').val(jQuery('.width').val());
        }

        if (el.value == 0) {
        } else if (el.value == 1) {
            jQuery('#dimension-diameter').show();
            jQuery('input.diameter').attr('disabled', false);
        } else {
            jQuery('#dimension-lengthwidth').show();
            jQuery('input.length, input.width').attr('disabled', false);
        }
    },
	
	/**
	 * When one of the color checkboxes fires onclick
	 * 
	 * @param {Object} el The HTMLInputElement
	 */
	colorClickHandler: function(el) {
		this.toggleColorQuantities();
		var index = jQuery('.colors input[type="checkbox"]').index(el);

		if(el.checked) {
			jQuery('.quantity-table tr:nth-child(' + (index + 1) + ')').show();
            jQuery('#stock-' + index).show();
		}
		else {
            var colors = jQuery('.colors input[type="checkbox"]');

            if (jQuery('.colors input[type="checkbox"]:checked').length) {
                jQuery('.quantity-table tr:nth-child(' + (index + 1) + ')').hide();
                jQuery('#stock-' + index).hide();
            } else {
                el.checked = true;
                this.toggleColorQuantities();
            }
		}
	},
	
	/**
	 * Toggles color quantities
	 */
	toggleColorQuantities: function() {
		if(jQuery('.colors input[type="checkbox"]:checked').length) {
			jQuery('#quantities').show();
		}
		else {
			jQuery('#quantities').hide();
		}
	},

	/**
	 * When one of the quantity inputs fires onkeyup
	 * 
	 * @param {Object} el The HTMLInputElement
	 */
	quantityKeyupHandler: function(el) {
		var total = 0;
		var quantities = jQuery(el).parents('.quantity-table').find('input.quantity');
		
		quantities.each(function() {
			if(this.value) {
				total += parseInt(this.value);
			}
		});
		
		jQuery(el).parents('.quantity-table').find('tr.total .quantity').text(total);
	},
	
	/**
	 * When the quantity add anchor fires onclick
	 */
	quantityAddClickHandler: function() {
		jQuery('#quantities .quantity-table:hidden').first().show()/*.find('input.quantity').attr('disabled', false)*/;
		
		if(jQuery('#quantities .quantity-table:visible').length == 3) {
			jQuery('#quantity-controls .add-icon').hide();
		}
		
		jQuery('#quantity-controls .remove-icon').show();

        jQuery('#quantity-colors').val(jQuery('#quantities .quantity-table:visible').length);
	},
	
	/**
	 * When the quantity remove anchor fires onclick
	 */
	quantityRemoveClickHandler: function() {
		jQuery('#quantities .quantity-table:visible:gt(0):last').hide()/*.find('input.quantity').attr('disabled', true)*/;
		
		if(jQuery('#quantities .quantity-table:visible').length == 1) {
			jQuery('#quantity-controls .remove-icon').hide();
		}
		
		jQuery('#quantity-controls .add-icon').show();

        jQuery('#quantity-colors').val(jQuery('#quantities .quantity-table:visible').length);
	},
	
	/**
	 * When the product part select element fires onchange
	 * 
	 * @param {Object} el The HTMLSelectElement
	 */
	productPartChangeHandler: function(el) {
		/* 
		 * JSON response
		 * 
			{
				"options": [
					{
						"text": "Kies...",
						"value": "-1",
						"defaultSelected": true,
						"selected": true
					},
					{
						"text": "Foo",
						"value": "100",
						"defaultSelected": false,
						"selected": false
					},
					{
						"text": "Bar",
						"value": "200",
						"defaultSelected": false,
						"selected": false
					}
				]
			}
		*/
		jQuery.ajax({
			data: 'type=productPart&cdadmin=' + jQuery('#cdadmin').val() + '&cdproduct=' + jQuery('#cdproduct').val() + '&productPart=' + el.value,
			success: function(data) {
				var printMethodSelect = jQuery('#print-method').get(0);
				
				this.context._clearSelect(printMethodSelect);
				this.context._addOptionsJSON(printMethodSelect, data.options);
				
				// Only one option possible, so show available positions
				if(data.options.length === 1) {
					this.context.printMethodChangeHandler(printMethodSelect);
				}
			}
		});
	},
	
	/**
	 * When the print method select element fires onchange
	 * 
	 * @param {Object} el The HTMLSelectElement
	 */
	printMethodChangeHandler: function(el) {
		/* 
		 * JSONreponse
		 * 
			{
			    "positionsHtml": "<div class=\"column position-options default-positions\"><p>Standaard positie:<\/p><ul><li><a class=\"thumb\" href=\"content\/print-position-1.jpg\" title=\"Verlengde van de clip\" rel=\"shadowbox\"><img src=\"content\/print-position-thumb-1.jpg\" alt=\"Verlengde van de clip\" width=\"108\" height=\"65\"><span class=\"zoom\">Vergroten<\/span><\/a><p class=\"position-caption\"><a href=\"#\" title=\"Verlengde van de clip selecteren\">Verlengde van de clip selecteren<\/a><\/p><\/li><\/ul><\/div><div class=\"column position-options other-positions\"><p>Overige posities:<\/p><ul><li><a class=\"thumb\" href=\"content\/print-position-2.jpg\" title=\"Verlengde van de clip\" rel=\"shadowbox\"><img src=\"content\/print-position-thumb-2.jpg\" alt=\"Verlengde van de clip\" width=\"108\" height=\"65\"><span class=\"zoom\">Vergroten<\/span><\/a><p class=\"position-caption\"><a href=\"#\" title=\"Verlengde van de clip selecteren\">Verlengde van de clip selecteren<\/a><\/p><\/li><\/ul><\/div>"
		    }
		*/
		jQuery.ajax({
			data: 'type=printMethod&orderId=' + jQuery('#order-id').val() + '&productPart=' + jQuery('#product-part').val() + '&printMethod=' + el.value + '&index=' + jQuery('#position-index').val(),
			success: function(data) {
				jQuery('#positions').html(data.positionsHtml);
				this.context.addPositionEventListeners();
			}
		});

        if (jQuery('#print-method').val() == 'Blinddruk') {
            jQuery('#color-quantity').hide();
            jQuery('#color-0').hide();
            jQuery('#color-1').hide();
            jQuery('#color-2').hide();
            jQuery('#color-3').hide();
        }
	},
	
	/**
	 * When a position element fires onclick
	 */
	addPositionEventListeners: function() {
		var self = this;
		
		jQuery('#positions .position-caption input[type="radio"]').click(function(e) {
			self.positionClickHandler(this);
		});
	},
	
	/**
	 * When a position element fires onclick
	 * 
	 * @param {Object} el The position link
	 */
	positionClickHandler: function(el) {
		jQuery('#position-id').val(jQuery(el).val());
		
		/* 
		 * JSON response
		 * 
			{
				"options": [
					{
						"text": "Kies...",
						"value": "-1",
						"defaultSelected": true,
						"selected": true
					},
					{
						"text": "Foo",
						"value": "100",
						"defaultSelected": false,
						"selected": false
					},
					{
						"text": "Bar",
						"value": "200",
						"defaultSelected": false,
						"selected": false
					}
				]
			}
		*/
		jQuery.ajax({
			data: 'type=position&cdadmin=' + jQuery('#cdadmin').val() + '&cdproduct=' + jQuery('#cdproduct').val() + '&cdstandeenheid=' + jQuery('#cdstandeenheid').val() + '&printMethod=' + jQuery('#print-method').val() + '&positionId=' + jQuery('#position-id').val(),
			success: function(data) {
				var colorQuantitySelect = jQuery('#color-quantity-select').get(0);
				
				this.context._clearSelect(colorQuantitySelect);
				this.context._addOptionsJSON(colorQuantitySelect, data.options);

                //var colorSwitchQuantity = jQuery('#colorswitch-quantity-select').get(0);
				//this.context._clearSelect(colorSwitchQuantity);
				//this.context._addOptionsJSON(colorSwitchQuantity, data.options);

				// Only one option possible, so show print properties
				if(data.options.length === 1) {
					this.context.colorQuantityChangeHandler(colorQuantitySelect);
				}

                if (jQuery('#print-method').val() == 'Blinddruk') {
                    jQuery('#color-quantity').hide()
                    jQuery('#color-0').hide();
                    jQuery('#color-1').hide();
                    jQuery('#color-2').hide();
                    jQuery('#color-3').hide();
                }
			}
		});
		
        if (jQuery('#print-method').val() != 'Blinddruk') {
            jQuery('#color-quantity').show();
        } else {
            jQuery('#color-quantity').hide();
            jQuery('#color-0').hide();
            jQuery('#color-1').hide();
            jQuery('#color-2').hide();
            jQuery('#color-3').hide();
        }
        //jQuery('#colorswitch-quantity').show();
	},
	
	/**
	 * When the color quantity select element fires onchange
	 * 
	 * @param {Object} el The HTMLSelectElement
	 */
	colorQuantityChangeHandler: function(el) {
		var self = this;

        var printMethod = jQuery('#print-method').val();

		jQuery('#print-properties tr.color').each(function(i) {
			if(i < el.value && printMethod != 'Etching' && printMethod != 'Laser') {
				jQuery(this).show();
				self.colorSwitchClickHandler(jQuery(this).find('input.switch-color').get(0));
			}
			else {
				jQuery(this).hide();
				jQuery(this).next('tr.color-switch').hide();
			}
		});

		/* 
		 * JSON response
		 * 
			{
				"options": [
					...
				],
				"dimensions": {
					"type": "rectangular",
					"width": 100,
					"height": 50,
					"unit": "mm"
				}
			}
			
			or
			
			{
				"options": [
					...
				],
				"dimensions": {
					"type": "circular",
					"diameter": 100,
					"unit": "mm"
				}
			}
		*/
		jQuery.ajax({
			data: 'type=colorQuantity&cdadmin=' + jQuery('#cdadmin').val() + '&cdproduct=' + jQuery('#cdproduct').val() + '&cdstandeenheid=' + jQuery('#cdstandeenheid').val() + '&printMethod=' + jQuery('#print-method').val() + '&positionId=' + jQuery('#position-id').val() + '&colorQuantity=' + el.value + '&positionIndex=' + jQuery('#position-index').val() + '&printCode=' + jQuery('#print-code').val(),
			success: function(data) {
				// Set print code
				jQuery('#print-code').val(data.printcode);

				// Options
				var variableOneSelect = jQuery('#variable-1-select').get(0);

				if(variableOneSelect) {
					this.context._clearSelect(variableOneSelect);
					this.context._addOptionsJSON(variableOneSelect, data.options);
					this.context.variableOneChangeHandler(variableOneSelect);
					
					if(data.options.length) {
						jQuery('#variable-1').show();
					}
				}

				this.context.setSameLogoAs(data.dimensions);

				// Dimensions
				switch(data.dimensions.type) {
					case 'rectangular':
						jQuery('#print-width').val(data.dimensions.width);
						jQuery('#print-height').val(data.dimensions.height);
						jQuery('#max-print-width').text(data.dimensions.width + data.dimensions.unit);
						jQuery('#max-print-height').text(data.dimensions.height + data.dimensions.unit);
						jQuery('#dimension-rectangular').show();
						jQuery('#dimension-circular').hide();
						break;
					case 'circular':
						jQuery('#print-diameter').val(data.dimensions.diameter);
						jQuery('#max-print-diameter').text(data.dimensions.diameter + data.dimensions.unit);
						jQuery('#dimension-circular').show();
						jQuery('#dimension-rectangular').hide();
						break;
					default:
						jQuery('#dimension-circular').hide();
						jQuery('#dimension-rectangular').hide();
						break;
				}
			}
		});
		
		jQuery('#print-properties').show();
	},
	
	/**
	 * When a color switch checkbox fires onclick
	 * 
	 * @param {Object} el The HTMLInputElement
	 */
	colorSwitchClickHandler: function(el) {
		if(el) {
			if(el.checked) {
				jQuery(el).parents('tr.color').next('tr.color-switch').show();
			}
			else {
				jQuery(el).parents('tr.color').next('tr.color-switch').hide();
			}
		}
	},
	
	/**
	 * When the add file button fires onclick
	 */
	addFileClickHandler: function() {
		jQuery('tr.file:hidden').first().show();
	},
	
	/**
	 * When a remove file button fires onclick
	 * 
	 * @param {Object} el The remove button
	 */
	removeFileClickHandler: function(el) {
		var self = this;
		
		switch(el.nodeName) {
			case 'A':
				if(confirm(lang.confirmDeleteFile)) {
					jQuery.ajax({
						url: el.href,
						success: function() {
							var cell = jQuery(el).parent().empty();
							var row = cell.parents('tr.file');
							
							var input = jQuery(document.createElement('input'));
							input.attr('type', 'file');
							input.attr('name', 'data[Order][file]');
							cell.append(input);
							
							// Add delete button and hide the table row if it's not the first file
							if(jQuery('tr.file').index(row.get(0)) > 0) {
								var deleteImg = jQuery(document.createElement('img'));
								deleteImg.addClass('delete');
								deleteImg.attr('src', 'img/delete.png');
								deleteImg.attr('alt', lang.deleteFile);
								deleteImg.attr('title', lang.deleteFile);
								deleteImg.click(function() {
									self.removeFileClickHandler(this);
								});
								cell.append(deleteImg);
								row.hide();
							}
						}
					});
				}
				break;
			case 'IMG':
				jQuery(el).parents('tr.file').hide();
				break;
		}
	},
	
	/**
	 * When the variable 1 select element fires onchange
	 * 
	 * @param {Object} el The HTMLSelectElement
	 */
	variableOneChangeHandler: function(el) {
		/* 
		 * JSON response
		 * 
			{
				"options": [
					{
						"text": "Kies...",
						"value": "-1",
						"defaultSelected": true,
						"selected": true
					},
					{
						"text": "Foo",
						"value": "100",
						"defaultSelected": false,
						"selected": false
					},
					{
						"text": "Bar",
						"value": "200",
						"defaultSelected": false,
						"selected": false
					}
				]
			}
		*/
		jQuery.ajax({
			data: 'type=variableOne&colorQuantity=' + jQuery('#color-quantity-select').val() + '&positionIndex=' + jQuery('#position-index').val() + '&printCode=' + jQuery('#print-code').val() + '&variableOne=' + el.value,
			success: function(data) {
				var variableTwoSelect = jQuery('#variable-2-select').get(0);
				
				if(variableTwoSelect) {
					this.context._clearSelect(variableTwoSelect);
					this.context._addOptionsJSON(variableTwoSelect, data.options);
					
					if(data.options.length) {
						jQuery('#variable-2').show();
					}
				}
			}
		});
	},

	/**
	 * Dezelfde logo dropdown genereren voor huidige positie
	 *
	 * @param {String} value
	 * @param {Array} dimensions
	 */
	setSameLogoAs: function(dimensions) {
		var total = 0;
		
		var options = [{
			"text": positionoptions[0].name,
			"value": positionoptions[0].volgnummer,
			"defaultSelected": false,
			"selected": false
		}];
		
		var width = dimensions.width ? dimensions.width : 0;
		var height = dimensions.width ? dimensions.height : 0;
		var diameter = dimensions.diameter ? dimensions.diameter : 0;
		
		for(var i = 1; i < positionoptions.length; i++) {
			if(positionoptions[i].printmethode == jQuery('#print-method').val() && positionoptions[i].aantalkleur == jQuery('#color-quantity-select').val() &&
				positionoptions[i].breedte == width && positionoptions[i].hoogte == height && positionoptions[i].diameter == diameter) {
				total++;

				options[total] = {
					"text": positionoptions[i].name,
					"value": positionoptions[i].volgnummer,
					"defaultSelected": false,
					"selected": false
				};
			}
		}
		
		var sameLogoAsSelect = jQuery('#samelogoas').get(0);
		if(sameLogoAsSelect ) {
			this._clearSelect(sameLogoAsSelect );
			this._addOptionsJSON(sameLogoAsSelect , options);
		}
		
		this.sameLogoAsChangeHandler();
	},

	/**
	 * When the samelogoas select element fires onchange
	 * 
	 * @param {Object} el The HTMLSelectElement
	 */
	sameLogoAsChangeHandler: function(el) {
		if(jQuery('#color-quantity-select').val() <= 0) {
			jQuery("#print-properties").hide();
			jQuery("#samelogoas-properties").hide();

		}
		else {
			if(document.getElementById("samelogoas")) {
				jQuery("#samelogoas").get(0).length > 1 ? jQuery("#samelogoas-properties").show() : jQuery("#samelogoas-properties").hide();
				jQuery("#samelogoas").val() > 0 ? jQuery("#print-properties").hide() : jQuery("#print-properties").show();
			}
		}
	},

	/**
	 * When the pickup checkbox fires onclick
	 * 
	 * @param {Object} el The HTMLInputElement
	 */
	pickupClickHandler: function(el) {
		el.checked ? jQuery('#delivery-address').hide() : jQuery('#delivery-address').show();
	},
	
	/**
	 * When the existing address select element fires onchange
	 * 
	 * @param {Object} el The HTMLSelectElement
	 */
	existingAddressChangeHandler: function(el) {
		/* 
		 * JSON response
		 * 
			{
				"fullname": "Webstores Internet totaalbureau",
				"attn": "T.J. Bouma",
				"address": "Kruiwiel 1",
				"postcode": "7773NL",
				"city": "Hardenberg",
				"countryCode": "NL"
			}
			
			or (when value is -1)
			
			{
				"fullname": "",
				"attn": "",
				"address": "",
				"postcode": "1234AB", // Depending on extranet language
				"city": "",
				"countryCode": "NL" // Depending on extranet language
			}
		*/
		jQuery.ajax({
			data: 'type=address&addressId=' + el.value,
			success: function(data) {
				for(key in data) {
					jQuery('#' + key).val(data[key]);
				}
				
				if(el.value == -1) {
					jQuery('#postcode').removeClass('focus');
					jQuery('#save-address').show();
				}
				else {
					jQuery('#postcode').addClass('focus');
					jQuery('#save-address').hide();
				}
			}
		});
	},
	
	/**
	 * When one of the proposal type radio buttons fires onclick
	 * 
	 * @param {Object} el The HTMLInputElement
	 */
	proposalTypeClickHandler: function(el) {
		if(el.value == "fixed") {
			jQuery('#fixed-proposal').show();
			jQuery('#advanced-proposal').hide();
		}
		else {
			jQuery('#advanced-proposal').show();
			jQuery('#fixed-proposal').hide();
		}
	},
	
	/**
	 * When a factor text input fires onkeyup
	 * 
	 * @param {Object} el The HTMLInputElement
	 */
	factorKeyupHandler: function(el) {
        if (el.type != 'checkbox' && el.value.replace(/,/g, '.') < el.title) {
            return;
        }

		var self = this;
		var proposalSectionId = jQuery(el).parents('li.expanded').attr('id');
        if (!proposalSectionId) {
            proposalSectionId = jQuery(el).parents('tr').attr('id');
        }

		/* 
		 * JSON response
		 * 
			Fixed
			
			{
				"type": "fixed",
				"quantity": 2000,
				"total": "&euro; 1.078,24"
			}
			
			or advanced
			
			{
				"type": "advanced",
				"quantity": 2000,
				"row": {
					"sku": "LT80374",
					"quantityPrice": "&euro; 0,32",
					"unitPrice": "&euro; 0,32",
					"subTotal": "&euro; 1.682,48"
				},
				"totals": {
					"quantityPrice": "&euro; 1.613,83",
					"unitPrice": "&euro; 0,317",
					"grandTotal": "&euro; 1.613,83"
				}
			}
		*/
		if (this.request[proposalSectionId]) {
			this.request[proposalSectionId].abort();
		}
		this.request[proposalSectionId] = jQuery.ajax({
			url: '/customers/update/',
			cache: false,
			dataType: 'json',
			type: 'POST',
			data: jQuery('input[name="data[Customer][proposalType]"]:checked, #' + proposalSectionId + ' input').serialize(),
			success: function(data) {
				self.updateProposalTable(data);
			}
		});
	},

	/**
	 * Update proposal tables with new price data
	 * 
	 * @param {Object} data JSON object containing updated prices
	 */
	updateProposalTable: function(data) {
		switch(data.type) {
			case 'fixed':
				jQuery('#product-' + data.type + '-' + data.quantity + ' .grand-total').html(data.total);
				break;
			case 'advanced':
                for (var i = 0; i < data.rows.length; i++) {
                    var rowId = '#product-' + data.quantity + '-' + data.rows[i].sku;
                    if (data.rows[i].index || data.rows[i].index == 0) {
                        rowId += '-' + data.rows[i].index;
                    }
                    var productRow = jQuery(rowId);
                    
                    jQuery('.quantity-price', productRow).html(data.rows[i].quantityPrice);
                    jQuery('.unit-price', productRow).html(data.rows[i].unitPrice);
                    jQuery('.subtotal', productRow).html(data.rows[i].subTotal);
                }
                var row = jQuery('#product-' + data.quantity + '-total');
                jQuery('.average', row).html(data['factor']);
				break;
		}
	},

	/**
	 * When a superuser text input fires onkeyup
	 * 
	 * @param {Object} el The HTMLInputElement
	 */
	superuserKeyupHandler: function(el) {
		var self = this;

		/* 
		 * JSON response
		 * 
			{
				"rows": [{
					"sku": "LT80374",
					"quantityPrice": "&euro; 0,32",
					"subTotal": "&euro; 1.682,48"
				}],
				"total": {
					"quantityPrice": "&euro; 1.613,83",
					"unitPrice": "&euro; 0,317",
					"grandTotal": "&euro; 1.613,83"
				}
			}
		*/
		if (this.request['superuser']) {
            this.request['superuser'].abort();
        }

		this.request['superuser'] = jQuery.ajax({
			url: '/orders/super_user_json',
			cache: false,
			dataType: 'json',
			type: 'POST',
			data: jQuery('#superuser-table input[name^="data[SuperUser]"]').serialize(),
			success: function(data) {
                if (data) {
                    self.updateSuperUserTable(data);
                }
			}
		});
	},

	/**
	 * Update superuser tables with new price data
	 * 
	 * @param {Object} data JSON object containing updated prices
	 */
	updateSuperUserTable: function(data) {
        for (var i = 0; i < data.rows.length; i++) {
            var productRow = jQuery('#' + data.rows[i].sku);

            jQuery('.quantity-price', productRow).html(data.rows[i].quantityPrice);
            jQuery('.subTotal', productRow).html(data.rows[i].subTotal);
        }

        // Set total
        var row = jQuery('#product-total');
        jQuery('.quantity-price', row).html(data.total.quantityPrice);
        jQuery('.unit-price', row).html(data.total.unitPrice);
        jQuery('.grandTotal', row).html(data.total.grandTotal);

        for (var i = 0; i < data.total.length; i++) {
            var productTotal = jQuery('#' + data.total[i].sku);

            jQuery('.quantity-price', productTotal).html(data.total[i].quantityPrice);
            jQuery('.unit-price', productTotal).html(data.total[i].unitPrice);
            jQuery('.grandTotal', productTotal).html(data.total[i].grandTotal);
        }
	},

	/**
	 * When the pickup checkbox fires onclick
	 * 
	 * @param {Object} el The HTMLInputElement
	 */
	reminderClickHandler: function(el) {
		if(el.checked) {
			jQuery('#reminder-table .sub').show();
		}
		else {
			jQuery('#reminder-table .sub').hide();
		}
	},
	
	/**
	 * Add an option to a select element
	 * 
	 * @param {Object} select The HTMLSelectElement
	 * @param {Object} option The HTMLOptionElement
	 */
	_addOption: function(select, option) {
		select.options[select.length] = option;
	},
	
	/**
	 * Add multiple options to a select element
	 * 
	 * @param {Object} select The HTMLSelectElement
	 * @param {Array} options An array containing the option elements to add
	 */
	_addOptions: function(select, options) {
		for(var i = 0; i < options.length; i++) {
			this._addOption(select, options[i]);
		}
	},
	
	/**
	 * Add multiple options to a select element with a JSON object
	 * 
	 * @param {Object} select The HTMLSelectElement
	 * @param {Object} options A JSON object containing the option data
	 */
	_addOptionsJSON: function(select, options) {
		var optArr = [];
		
		for(var i = 0; i < options.length; i++) {
			optArr.push(new Option(options[i].text, options[i].value, options[i].defaultSelected, options[i].selected));
		}
		
		this._addOptions(select, optArr);
	},
	
	/**
	 * Clear all options of a select element
	 * 
	 * @param {Object} select The HTMLSelectElement
	 */
	_clearSelect: function(select) {
		select.options.length = 0;
	}
};

