
/* Implement a setfocus method which is easily accessable with $('element').setFocus(); */

Element.implement({
	setFocus: function(index) {
		this.setAttribute('tabIndex',index || 0);
		this.focus();
	}
});

var miniShop = new Class({

	options: {
		id: 0, // ID of page to request...
		step: 1, // step we have reached...
		languageId: 0, // The language the current page is running, this way the AJAX will do callbacks to the tunnel including the language ID...
		ajaxTypeNum: 543, // the typeNum for TYPO3...
		prefix: 'tx_houmarkminishop_pi1',
		quantityClass: 'quantity',
		buttonMinusClass: 'button-minus',
		buttonPlusClass: 'button-plus',
		subTotalPriceId: 'subtotal',
		shippingPriceId: 'shipping',
		totalPriceId: 'total',
		creditCardPayButtonId: 'button_creditcard_pay',
		conditionsCheckboxId: 'conditions_accepted'
	},

	Implements: [Options,Events],

	initialize: function(options) {
		this.setOptions(options);
		consoleLog('Starting minishop class...');
		if (this.options.step == 1) {
			this.checkForAnchors();
			this.bindButtons();
			this.bindFields();
			this.bindGiftQuestion();
			this.getCountryName();
			customerFormValidation.init();
		} else if (this.options.step == 2) {
			this.bindPayButton();
		}
	},

	checkForAnchors: function() {
		var anchor = unescape(self.document.location.hash.substring(1));
		if ($(anchor)) {
			new Fx.Scroll(window).toElement(anchor);
		}
	},

	bindButtons: function() {

		var self = this;

		$$('.'+ self.options.buttonMinusClass).each(function(element) {

			element.addEvent('click', function(e) {
				e.stop();
				value = ($(self.options.prefix +'_'+ element.get('rel') +'_quantity').get('value').toInt() - 1);
				self.changeQuantity(element.get('rel'), value);
			});
		});

		$$('.'+ self.options.buttonPlusClass).each(function(element) {
			element.addEvent('click', function(e) {
				e.stop();
				value = ($(self.options.prefix +'_'+ element.get('rel') +'_quantity').get('value').toInt() + 1);
				self.changeQuantity(element.get('rel'), value);
			});
		});

	},

	bindFields: function() {

		var self = this;

		$$('.'+ self.options.quantityClass).each(function(element) {
			element.addEvent('change', function() {
				self.changeQuantity(element.get('rel'), this.get('value'));
			});
		  element.addEvent('keypress', function(e) {
		    if (e.key == 'enter') {
					e.stop();
					this.fireEvent('change');
					element.blur();
				}
			});
		});
	},

	bindGiftQuestion: function() {
		var self = this;
		boxId = 'minishop_is_gift';
		var box = $(boxId);
		if (!box) return;

		var giftFieldset = $$('div#'+ boxId +' fieldset');
		giftFieldset.setStyle('display', 'none'); // hide from the start to remove validation on gift form part...
		var scroller = new Fx.Scroll(window);
		var boxSlide = new Fx.Slide(box).hide();
		var buttons = $$('div#minishop_question_gift input.is-gift').each(function(button) {
			button.addEvent('click', function(e) {
				if (button.get('checked') == 'true') {
					e.stop();
					return;
				}
				if (button.get('value').toInt() === 1) {
						giftFieldset.setStyle('display', 'block');
						boxSlide.slideIn().chain(function() {
							scroller.toElement('minishop_is_gift').chain(function() {
								if ($(self.options.prefix + '_ship_to_name')) $(self.options.prefix + '_ship_to_name').setFocus();
							});
					});
				} else {
					boxSlide.slideOut().chain(function() {
						giftFieldset.setStyle('display', 'none');
					});
				}
			});
		});
		var yesButton = $$('div#minishop_question_gift input.is-gift-yes');
		if (yesButton.get('checked') == 'true') {
			giftFieldset.setStyle('display', 'block');
			boxSlide.show();
		}
	},

	getCountryName: function() {
		var self = this;

		elementCountry = $(this.options.prefix +'_country_code');
		elementCountryGift = $(this.options.prefix +'_ship_to_country_code');

		// Get first selected element of each country dropdown, if value is different than "" (nothing) for both we stop...
		if (elementCountry.getSelected()[0].value != '' && elementCountryGift.getSelected()[0].value != '') return;

		var request = new Request.JSON({
			method: 'get',
			url: '/index.php',
			data: 'id='+ self.options.id +'&L='+ self.options.languageId +'&type='+ self.options.ajaxTypeNum +'&'+ self.options.prefix +'[action]=get-country',
			noCache: true,
			onSuccess: function(responseJSON, responseText) {

				if (responseJSON.Status == 'OK') {
					self.setCountrySelected(elementCountry, responseJSON.CountryCode);
					self.setCountrySelected(elementCountryGift, responseJSON.CountryCode);
				}

			}.bind(this)
		}).send();

	},

	setCountrySelected: function(field, countryCode) {

		if ((!field) || field.getSelected()[0].value != '') return;

		var options = field.getElements('option');
		options.each(function(option){
			if (option.get('value') == countryCode) {
				option.set('selected', 'selected');
				try { field.getParent().getPrevious().getChildren().addClass('required').addClass('validate-ok');
				} catch(error) {}
			}
		});

		return field;

	},

	changeQuantity: function(productId, value) {

		var self = this;

		var request = new Request.JSON({
			method: 'get',
			url: '/index.php',
			noCache: true,
			data: 'id=' + self.options.id +'&L='+ self.options.languageId +'&type='+ self.options.ajaxTypeNum +'&'+
			self.options.prefix +'[action]=update-quantity&'+ self.options.prefix +'[quantity]='+ value +'&'+
			self.options.prefix +'[productId]='+ productId,
			onRequest: function() {
			},
			onSuccess: function(responseJSON, responseText) {
				self.updateQuantity(productId, responseJSON.quantity);
				self.updateTotalPrice(responseJSON);
			}.bind(this),
			onFailure: function() {
			}
		}).send();

	},

	updateQuantity: function(productId, quantity) {
		consoleLog('updating quantity to value '+ quantity +' for product ID '+ productId);
		$(this.options.prefix +'_'+ productId +'_quantity').set('value', quantity);
	},

	updateTotalPrice: function(JSON) {
		if ($(this.options.subTotalPriceId)) {
			consoleLog('updating subtotal to '+ JSON.subtotal);
			$(this.options.subTotalPriceId).set('text', JSON.subtotal ? JSON.subtotal : '0,00');
		}
		if ($(this.options.shippingPriceId)) {
			consoleLog('updating shipping price to '+ JSON.shipping);
			$(this.options.shippingPriceId).set('text', JSON.shipping ? JSON.shipping : '0,00');
		}
		if ($(this.options.totalPriceId)) {
			consoleLog('updating total to '+ JSON.total);
			$(this.options.totalPriceId).set('text', JSON.total ? JSON.total : '0,00');
		}
	},

	paymentMonitor: function() {
		var self = this;

		var orderId = $('orderid').get('value');
		if (!orderId) return;

		var request = new Request.JSON({
		    method: 'get',
		    url: '/index.php?id='+ self.options.id +'&L='+ self.options.languageId +'&type='+ self.options.ajaxTypeNum +'&'+ self.options.prefix +'[action]=payment-monitor&'+ self.options.prefix +'[orderid]='+ orderId,
		    initialDelay: 8000,
		    delay: 3000,
		    limit: 10000,
				noCache: true,
				onSuccess: function(responseJSON, responseText) {
					if (responseJSON.payment == 'OK' && responseJSON.redirectTo != '') {
						request.stopTimer();
						// Redirect to thank-you page...
						document.location.href = responseJSON.redirectTo;
					}
				}
		}).startTimer();
	},

	bindPayButton: function() {
		var self = this;
		var newWindow = null;
		$(self.options.creditCardPayButtonId).addEvent('click', function(e) {
			if ($(self.options.conditionsCheckboxId).get('checked') != true) {
				alert($(self.options.conditionsCheckboxId).get('title'));
				e.stop();
				return false;
			}
			try {
		  	newWindow = window.open('', 'paywin', 'scrollbars,status,width=550,height=600');
		  	newWindow.focus();
			} catch(error) {}
			self.paymentMonitor();
		});
	},

	validateBasketValue: function() {
		var self = this;
		var totalValue = 0;

		$$('.'+ self.options.quantityClass).each(function(element) {
			totalValue += element.get('value').toInt();
		});
		if (totalValue == 0) {
			return alert('Basket empty...');
		} else {
			return totalValue;
		}
	}

}); // end class

var customerFormValidation = {
	init: function(){
		Locale.use("da-DK");
		if ($('minishop-form')) {
			var validateCustomerForm = new Form.Validator.Tips($('minishop-form'), {
			    evaluateFieldsOnBlur: false,
			    evaluateFieldsOnChange: true,
					useTitles: true,
					// serial: false,
					ignoreHidden: true,
					onElementPass: function(field) {
						// Bug in Form.Validator or Mootools
						// Cannot pass field win IE and Fx
						// So to stop errors for now we put in within a try/catch
						try {
							if (field.getParent().get('tag') == 'select') {
								var labelElement = field.getParent().getParent().getPrevious().getChildren();
							} else if(field != undefined) {
								var labelElement = field.getParent().getPrevious().getChildren();
							}
							labelElement.addClass('validate-ok');
							field.removeClass('server-validation-error');
							consoleLog('element passed validation');
						} catch(error) {}
					},
					onElementFail: function(field, failedValidators) {
						var scroller = new Fx.Scroll(window);
						// See description in onElementPass
						try {
							if (field.getParent().get('tag') == 'select') {
								var labelElement = field.getParent().getParent().getPrevious().getChildren();
							} else {
								var labelElement = field.getParent().getPrevious().getChildren();
							}
							labelElement.addClass('required').removeClass('validate-ok');
							field.setFocus();
							scroller.toElement(field);
						} catch(error) {}
					},
			    onElementValidate: function(isValid, field, className, warn){
			      var validator = this.getValidator(className);
						// var labelElement = field.getParent().getPrevious().getChildren();
			      if (!isValid && validator.getError(field)){
							// alert(validator.getError(field));
							// field.setFocus();
							// Get the label field to the right and update the style...
						// 	if (labelElement.get('for') == field.get('id')) {
						// 		labelElement.addClass('required').removeClass('validate-ok');
						// 	}
						// } else {
						// 	if (labelElement.get('for') == field.get('id') && field.hasClass('validation-passed')) {
						// 		labelElement.addClass('validate-ok');
						// 	}
						}
			    },
			    onFormValidate: function(passed, myform, event) {
			        if (!passed) {

								// alert('Some fields failed validation. Please correct the errors!');
							} else {
								var totalValue = 0;
								$$('.quantity').each(function(element) {
									totalValue += element.get('value').toInt();
								});
								if (totalValue == 0) {
									if ($('empty_basket')) alert($('empty_basket').get('title'));
									event.preventDefault();
								}
							}
							// stop form from submitting...
			        // event.preventDefault();
			    }
			}); // end validator
		} // end if

		Form.Validator.add('validateFullName', {
			errorMsg: 'Feltet er ikke korrekt udfyldt.',
			test: function(element, props) {
				// Re-use minLength from the minLength validator core...
				if (typeOf(props.validateFullName) != 'null') var minLengthValid = Form.Validator.getValidator('minLength').test(element, {minLength:props.validateFullName});
				return !Form.Validator.getValidator('IsEmpty').test(element) && element.get('value').test(/\s/) && minLengthValid;
		   }
		});

		Form.Validator.add('validateZipCode', {
			errorMsg: 'Feltet er ikke korrekt udfyldt.',
			test: function(element, props) {
				consoleLog(Form.Validator.getValidator('validate-integer').test(element));
				// Re-use minLength from the minLength validator core...
				if (typeOf(props.validateZipCode) != 'null') var minLengthValid = Form.Validator.getValidator('minLength').test(element, {minLength:props.validateZipCode});
				return !Form.Validator.getValidator('IsEmpty').test(element) && Form.Validator.getValidator('validate-integer').test(element) && minLengthValid;
		   }
		});

		consoleLog('Form validator instance was started...');
	}

} // end customerFormValidation


function consoleLog(msg) {
	try {
		// console.log(msg);
	}
	catch(error) { }
}
