Form.Validator.add('validate-one-place-or-table', {
    errorMsg: 'Min 1 place, Max 15 places!',
    test: function(element,props){
        var p = element.getParent('table');
        //At least one is larger then 0
		var more_then_zero = p.getElements('input').some(function(el){
			return el.get('value') > 0 && el.get('value') < 15;
		});
		//Both are integers, not letters, not negative numbers
		var all_accepted = p.getElements('input').every(function(el){
			return Form.Validator.getValidator('validate-integer').test(el);
		});
		
		return more_then_zero && all_accepted;
    }
});

BookingForm = new Class({
	
	Implements:[Options, Events],
	
	 placesInitValue: 1,
	 tablesInitValue: 0,
	 isDiscount: false,
	 
	 options: {
		singlePlacePrice: 125,
		discountPrice: 110,
		priceSwitcher: 'priceswitch',
		singleTablePrice: 2200,
		vat: 1.175,
		amountIncVatField: 'amount',
		vatAmountField: 'vatamount',
		amountExcVatField: 'amountnovat',
		priceExcVatElement: 'totalexcludevat',
		priceIncVatElement: 'totalincludevat',
		vatElement: 'totalvat',
		
		placesField: 'places',
		tablesField: false
	},
	
	initialize: function(form, options){
		 this.setOptions(options);
		 $(this.options.placesField).value = this.placesInitValue;
		 if (this.options.tablesField) $(this.options.tablesField).value = this.tablesInitValue;
		 
		 
		 this.validator = new Form.Validator.Inline(form);
		 ///this.ignoreChildren($('invoice_info'));
  		 
  		 this.setSwitcher();
  						
		 this.setPrices();
		 this.typeChoice();
    	 this.initForm();
	},
	
	setSwitcher: function() {
		var checker = $(this.options.priceSwitcher);
		this.validator.add('validateEntrycode', {
    		errorMsg: 'Sorry, we do not have that entry code in our records. Please call us or submit the booking with public price.',
    		test: (function(element,props){
        		var ecode = element.get('value');
        		var checker = $(props.validateEntrycode);
        		var isok = false;
        		if (checker.checked) {
        			var jsonRequest = new Request.JSON({
        				url: "/entry-code-check.php", 
        				async: false,
        				onSuccess: (function(resp){
   	 						isok = resp.good;
   	 						if (isok) {
   	 							this.isDiscount = true;
   	 							this.setPrices();
   	 						} else {
   	 							this.isDiscount = false;
   	 							this.setPrices();
   	 						}
						}).bind(this)
        			}).get({'entrycode': ecode});

        		} else {
        			isok = true;
        			this.isDiscount = false;
   	 				this.setPrices();
        		}
				return isok;
    		}).bind(this)
		});
	},
	
	setPrices: function() {
		
		var placesCount = $(this.options.placesField).value;
		var tablesCount = (this.options.tablesField ? $(this.options.tablesField).value : 0);
		if (this.isDiscount) {
			var sum = this.options.discountPrice * placesCount + this.options.singleTablePrice * tablesCount;
		} else {
			var sum = this.options.singlePlacePrice * placesCount + this.options.singleTablePrice * tablesCount;
		}
		
		this.totalPrice = this.formatPrice(Math.round(100 * sum * this.options.vat) / 100);
		//alert(this.formatPrice(this.totalPrice));
  		$(this.options.priceExcVatElement).set('html',this.formatPrice(Math.round(100 * sum) / 100));
  		$(this.options.vatElement).set('html',this.formatPrice(this.totalPrice - (Math.round(100 * sum) / 100)));
		$(this.options.priceIncVatElement).set('html',this.totalPrice);
		
		$(this.options.amountIncVatField).value = this.totalPrice;
		$(this.options.vatAmountField).value = this.formatPrice(this.totalPrice - (Math.round(100 * sum) / 100));
		$(this.options.amountExcVatField).value = this.formatPrice(Math.round(100 * sum) / 100);
	},
	
	initForm: function() {
  		
  		$(this.options.placesField).addEvent("keyup", (function(event) {
  			if (this.validator.validateField(this.options.placesField)) {
  				this.setPrices();
  			}
  		}).bind(this));
  		
  		if (this.options.tablesField)  {
			$(this.options.tablesField).addEvent("keyup", (function(event) {
				if (this.validator.validateField(this.options.tablesField)) {
  					this.setPrices();
				}
  			}).bind(this));
  		}
  	},
	
	typeChoice:function() {
  		// deo koji radi toogle kad se selektuje payment method
  		var selector = $('payment-method');
  		var options = selector.getChildren('option');
  
  		this.paymentSwitch(options);
  		selector.addEvent('change', (function(event) {  			
  			this.paymentSwitch(options);		
  		}).bind(this));
  		
  		// deo za kopiranje sa gornjih polja
  		$('copyinvoice').addEvent('click', function(){
  			// get the above values
  			var copyfirstname1 = $('contact_firstname').value;
  			var copysurname1 = $('contact_surname').value;
  			var copycompanyemail1 = $('contact_email').value;
  			var copytelephone1 = $('contact_telephone').value;
  			
  			var copydepartment1 = ( $('contact_department') ? $('contact_department').value : '');
  			var copycompanyname1 = ( $('contact_company') ? $('contact_company').value : '' );
  			var copycompanyaddress1 = ( $('contact_company_address') ? $('contact_company_address').value : '');
  			var copytown1 = ( $('contact_town') ? $('contact_town').value : '' );
  			var copypostcode1 = ( $('contact_postcode') ? $('contact_postcode').value : '' );
  			var copycountry1 = ( $('contact_country') ? $('contact_country').value : '' );
  			var copymobile1 = ( $('contact_mobile') ? $('contact_mobile').value : '' );
			// assign them to bellow fields
  			$('payment-method-Offline').getElement('#invoice_firstname').value = copyfirstname1;
  			$('payment-method-Offline').getElement('#invoice_surname').value = copysurname1;
  			$('payment-method-Offline').getElement('#invoice_email').value = copycompanyemail1;
  			$('payment-method-Offline').getElement('#invoice_telephone').value = copytelephone1;
  			
  			$('payment-method-Offline').getElement('#invoice_department').value = copydepartment1;
  			$('payment-method-Offline').getElement('#invoice_company').value = copycompanyname1;
  			$('payment-method-Offline').getElement('#invoice_street').value = copycompanyaddress1;
  			$('payment-method-Offline').getElement('#invoice_town').value = copytown1;
  			$('payment-method-Offline').getElement('#invoice_postcode').value = copypostcode1;
  			$('payment-method-Offline').getElement('#invoice_country').value = copycountry1;
  			$('payment-method-Offline').getElement('#invoice_mobile').value = copymobile1;
  		});
  	},
  	// Switching the payment method, handling the current one and adding the onchange event. unused methods will not be mandatory.
  	paymentSwitch: function(options) {
  		$each(options, (function(val, index){  	
  			if (val.value != "") {		
  				var optionContainer = $('payment-method-' + val.value);
  			
  				if (val.selected) {
  					optionContainer.setStyles({display:"block"});
  					this.enforceChildren(optionContainer);
  				} else {
  					optionContainer.setStyles({display:"none"});
  					this.ignoreChildren(optionContainer);
  				}
  			}
  		}).bind(this));	
  	},
	
	formatPrice: function(price){
        return price.toFixed(2);
    },
    
    ignoreChildren: function(parent) {
    	if (parent) {
    		var childInputs = parent.getElements('input,select,textarea');
    		childInputs.each( function(ch) {
    			this.validator.ignoreField(ch.id);
    		}, this); 
    	}
    },
    
    enforceChildren: function(parent) {
    	if (parent) {
    		var childInputs = parent.getElements('input,select,textarea');
    		childInputs.each( function(ch) {
    			this.validator.enforceField(ch.id);
    		}, this); 
    	}
    }
	
});