function overlayEnquiryForm() {
  
  this.enabled = true;
  
  this.setQuoteRef = function (value) {
    if(typeof(value)!='string') return false;
    this.container.find('.quote-ref').text(value);
    this.container.find('input[name=ref]').val(value);
  }

  this.setTravelType = function (value) {
    if(typeof(value)!='string') return false;
    this.container.find('input[name="travel_type"]').val(value);
  }

  this.open = function () {
  
  	var $selectedItem = $('div.rb-package:not(.ui-tabs-hide)').eq(0);
	this.setQuoteRef($selectedItem.attr('quoteRef'));
	this.setTravelType($selectedItem.attr('travelType'));
    this.container.dialog('open');	
  }

  this.close = function () {
    this.reset();
    this.containerForm.find('input.date-picker').datepicker('hide');
  }
  
  this.disable = function () {
    
    var callback = this;
    if(!this.enabled) {
      window.setTimeout('$("'+this.containerSelector+'").trigger("callbackDisable");',1000);
      return false;
    }
       
    this.container.dialog('disable');
    
    this.container.find('.ajax-busy').fadeIn('fast', function () {
      callback.enabled=false;
    });
    
    
  }
  
  this.enable = function () {
    var callback = this;
    
    if(this.enabled) {
      window.setTimeout('$("'+this.containerSelector+'").trigger("callbackEnable");',1000);
      return false;
    }
    
    this.container.find('.ajax-busy').fadeOut('fast', function () {
      callback.container.dialog('enable');
      callback.enabled=true;
    });
    
  }
  
  this.reset = function () {
    this.validator.resetForm();
    this.containerForm.find('input[type=text],select,textarea').val('');
    this.containerForm.find('textarea[name="children_ages"]').attr('disabled', 'disabled');
    this.containerForm.find('textarea[name="children_ages"]').parent('div').parent('div.field').hide();
    this.container.find('.ajax-busy').hide();
  }
  
  this.showSuccess = function () {

    var title = 'Thank you for your enquiry';
    if(typeof(this.successTitle)=='string') {
        title = this.successTitle;
    }
    this.container.dialog('close');
    
    $(this.containerDoneSelector).dialog("option", "title", title).dialog("open");
        
    window.setTimeout("$('"+this.containerDoneSelector+"').dialog('close');", 10000);
    
  }
  
  this.error = function (message, title) {

    if(typeof(title)!='string') title='Form Submission Error';
    if(typeof(message)!='object') message=$('<p>Sorry, there was an unknown problem processing your data</p>');
    
    $(this.containerErrorSelector).find('div.intro:first').empty().append(message);
    
    $(this.containerErrorSelector).dialog("option", "title", title);
    $(this.containerErrorSelector).dialog("open");
    
  }
  
  this.showFaultList = function (faults) {
    var formFaults={};
    var formFaultCount=0;
    var faultCount=0;
    
    
    this.containerForm.find('input,textarea,select').each(function () {
      var name=$(this).attr('name');
      if(typeof(faults[name])!='undefined') {
        formFaults[name]=faults[name];
        formFaultCount++;
        delete faults[name];
      }
    });
    
    
    if(formFaultCount) this.validator.showErrors(formFaults);
    
    var message=$('<ul class="error"></ul>');
    message.append('<p class="error">The following errors occurred while processing your submission:</p>');
    if(typeof(faults)=='object' && faults) {
      for(var i in faults) {
        faultCount++;
        if(typeof(faults[i])=='string') message.append('<li>'+faults[i]+'</li>');
        else if(typeof(faults[i])=='object') {
          for(var j=0; j<faults[i].length; j++) {
            if(typeof(faults[i][j])=='string') message.append('<li>'+faults[i][j]+'</li>');
          }
        } else {
          message.append('<li>undefined error</li>');
        }
      }
      this.error(message);
    }
    
    if(!faultCount) {
      this.error();
    }
  }

  this.submit = function () {
    this.disable();
    var callback = this;
    
    //alert($.toJSON(this.getValues()));
    
    var formValues = this.getValues();
	
    $.get('/ajax/enquiry/submit', {formType: this.formType, data: $.toJSON(formValues)},
        function(data){
          var objData;
          try {
            objData = $.secureEvalJSON(data);
          } catch (err) {
            callback.error($('<pre>'+data+'</pre>'));
            callback.enable();
            return;
          }
          
          // Submit DC Storm track
          var enquiryType       = ucwords(callback.formType) + ' Enquiry';
          var productName       = formValues.holiday || formValues.hotel || 'N/A';
          var productReference  = formValues.ref || 'N/A';
          var departureDate     = formValues.o_date || 'N/A';
          var dcStr = 'isconv=1|itemcount=1|itemvalue=0|m1='+enquiryType+'|m2='+productName+'|m3='+productReference+'|m4='+departureDate;
          //alert(dcStr);
          logOCSale(dcStr);
          
          callback.submitResult(objData);
          
        });
  }
  
  this.submitResult = function (data) {
    if(typeof(data)!='object') data = {success: 0};

    if(data.success>0) {
      this.showSuccess();
    } else {
      if(typeof(data.faults)=='object') {
        this.showFaultList(data.faults);
      } else {
        this.error();
      }
    }
    this.enable();
  }
  
  this.getValues = function () {
    var data = {};
    this.containerForm.find('input[type=text],input[type=hidden],input[type=radio]:checked,input[type=checkbox]:checked,select,textarea').each(function (i, j) {
      j=$(j);
      var name=j.attr('name');
      var value=j.val();    
      if(typeof(name)!='undefined') data[name]=value;
    });
    
    this.containerForm.find('input.date-picker').each(function (i, j) {
      j=$(j);
      var name=j.attr('name');
      var value=$.datepicker.formatDate('yy-mm-dd', $.datepicker.parseDate('dd/mm/yy', j.val()));
      if(typeof(name)!='undefined') data[name+'_mysql']=value;
    });
    
    return data;
  }

  this.init = function (dialogTitle) {
    var callback = this;
    
    this.container.dialog({
      autoOpen: false,
      draggable: false,
      modal: true,
      resizable: false,
      width: 630,
      buttons: {
        "Send Enquiry >>": function () {
          if(!callback.enabled) return false;
          callback.container.find('form:first').trigger('submit');
        },
        "Cancel": function () {
          if(!callback.enabled) return false;
          callback.container.dialog('close');
        }
      },
      title: this.dialogTitle,
      close: function(event, ui) {
        callback.close();
      }
    });

    this.container.bind('callbackDisable', function () {
      callback.disable();
    }).bind('callbackEnable', function () {
      callback.enable();
    });
    
    this.containerForm.find('input.date-picker').datepicker({
        showOn: 'button',
        buttonImage: '/assets/gfx/calendar.gif',
        buttonImageOnly: true,
        dateFormat: 'dd/mm/yy',
        minDate: '+14d',
        maxDate: '+1y',
        closeText: 'X',
        closeAtTop: true,
        onSelect: function(dateText, inst) {
            
            if(inst.input.hasClass('min-date-for'))
            {
                var minDateFor=inst.input.attr('mindatefor');
                var value=$.datepicker.parseDate('dd/mm/yy', inst.input.val());
                value = new Date(value.getFullYear(), value.getMonth(), value.getDate()+1);
                
                // Set minDate of return cal to value
                if(typeof(minDateFor)=='string')
                {
                    callback.container.find('input[name="'+minDateFor+'"]').datepicker('disable').val('').datepicker('hide').datepicker('change', {minDate: value}).datepicker('enable').trigger('change');
                }
            }

            inst.input.focus();
            
        }
    });
    

    this.containerForm.find('select[name="num_children"]').bind('change', function () {
      if($(this).val()>0) {
        callback.containerForm.find('textarea[name="children_ages"]').attr('disabled', '');
        callback.containerForm.find('textarea[name="children_ages"]').parent('div').parent('div.field').show();
      } else {
        callback.containerForm.find('textarea[name="children_ages"]').attr('disabled', 'disabled');
        callback.containerForm.find('textarea[name="children_ages"]').parent('div').parent('div.field').hide();
      }
      
    }).trigger('change');
    
    $(this.containerErrorSelector).dialog({
      autoOpen: false,
      draggable: false,
      modal: true,
      resizable: false,
      width: 500,
      buttons: {
        'OK': function () {
          $(this).dialog("close");
        }
      },
      title: 'No Title'
    });
    
    $(this.containerDoneSelector).dialog({
      autoOpen: false,
      draggable: false,
      modal: true,
      resizable: false,
      width: 600,
      buttons: {
        'OK': function () {
          $(this).dialog("close");
        }
      },
      title: 'No Title'
    });

    
  }
  
  this.formType = 'overlay';
  
}


function breakEnquiryForm(containerSelector, containerDoneSelector, containerErrorSelector) {
  var callback = this;
  this.container = $(containerSelector);
  this.containerSelector = containerSelector;
  this.containerDoneSelector = containerDoneSelector;
  this.containerErrorSelector = containerErrorSelector;
  this.containerForm = this.container.find('form:first');
  this.formType = 'break';
  this.successTitle = 'City Break Enquiry';
  this.dialogTitle = 'City Break Enquiry Form';
  this.init();

  this.validator = this.containerForm.validate({
  
    //onfocusout: false,
    onkeyup: false,
    
    focusInvalid: false,
    focusCleanup: true, // not recommended with focusInvalid
    
    errorClass: "form-error",
    
    submitHandler: function(form) {
        callback.submit();
    },
    
    invalidHandler: function(form, validator) {
        setTimeout(function() {
            var firstError = $('.form-error:visible', callback.containerForm).eq(0);
            var scrollPosTop = (firstError.position().top)-50;
            $.scrollTo({top: scrollPosTop, left: 0}, 'slow');
        }, 250);
    },
    
    errorPlacement: function(error, element) {
      if(element.attr('errorboxid')) {
        error.appendTo('#'+element.attr('errorboxid'));
      } else {
        error.insertAfter(element);
      }
    },
    
    rules: {
      title: {required: true},
      forename: {required: true},
      surname: {required: true},
      /*
      landline: {
        required: function(element) {
          return (callback.containerForm.find('input[name="mobile"]').val()=='');
        }
      },
      */
      home_country: {required: true},
      email: {email: true, required: true},
      o_station: {required: true},
      o_date: {
        required: true
      },
      r_date: {
        required: true
      },
      num_adults: {required: true},
      children_ages: {required: true},
      
      other_requirement: {
        required: function(element) {
          return (callback.containerForm.find('#site-tld').val()=='au');
        }
      }
      
    },
    
    messages: {
      email: {
        required: 'Please enter your email address.',
        email: 'Please enter a valid email address.'
      },
      forename: 'Please enter your first name.',
      surname: 'Please enter your family name.',
      title: 'Please select your title.',
      landline: 'Please enter your phone number.',
      home_country: 'Please select the country you live in.',
      o_station: 'Please enter your departure point.',
      o_date: {
        required: 'Please select your date of travel.'
      },
      r_date: {
        required: 'Please select your date of travel.'
      },
      num_adults: 'Please select number of people travelling.',
      children_ages: 'Please enter the ages of the children travelling.'
    }
    
  });

 
}

breakEnquiryForm.prototype = new overlayEnquiryForm();



function holidayEnquiryForm(containerSelector, containerDoneSelector, containerErrorSelector) {
  var callback = this;
  this.formType = 'holiday';
  this.successTitle = 'Holiday Enquiry';
  this.container = $(containerSelector);
  this.containerSelector = containerSelector;
  this.containerDoneSelector = containerDoneSelector;
  this.containerErrorSelector = containerErrorSelector;
  this.containerForm = this.container.find('form:first');
  this.dialogTitle = 'Holiday Enquiry Form';
  this.init();
  
  this.validator = this.containerForm.validate({
    
    //onfocusout: false,
    onkeyup: false,
    
    focusInvalid: false,
    focusCleanup: true, // not recommended with focusInvalid
    
    errorClass: "form-error",
   
    submitHandler: function(form) {
        callback.submit();
    },
    
    invalidHandler: function(form, validator) {
        setTimeout(function() {
            var firstError = $('.form-error:visible', callback.containerForm).eq(0);
            var scrollPosTop = (firstError.position().top)-50;
            $.scrollTo({top: scrollPosTop, left: 0}, 'slow');
        }, 250);
    },

    errorPlacement: function(error, element) {
      if(element.attr('errorboxid')) {
        error.appendTo('#'+element.attr('errorboxid'));
      } else {
        error.insertAfter(element);
      }
    },
    
    rules: {
      title: {required: true},
      forename: {required: true},
      surname: {required: true},
      /*
      landline: {
        required: function(element) {
          return (callback.containerForm.find('input[name="mobile"]').val()=='');
        }
      },
      */
      home_country: {required: true},
      email: {required: true, email: true },
      o_station: {required: true},
      o_date: {
        required: true
      },
      r_station: {required: true},
      r_date: {
        required: true
      },
      num_adults: {required: true},
      children_ages: {required: true},
      
      other_requirement: {
        required: function(element) {
          return (callback.containerForm.find('#site-tld').val()=='au');
        }
      }
      
    },
    
    messages: {
      email: {
        required: 'Please enter your email address.',
        email: 'Please enter a valid email address.'
      },
      forename: 'Please enter your first name.',
      surname: 'Please enter your family name.',
      title: 'Please select your title.',
      landline: 'Please enter your phone number.',
      home_country: 'Please select the country you live in.',
      o_city: '*',
      o_date: {
        required: 'Please select your date of travel.'
      },
      r_city: '*',
      r_date: {
        required: '*'
      },
      num_adults: 'Please select number of people travelling.',
      children_ages: 'Please enter the ages of the children travelling.'
    }
    
  });


}

holidayEnquiryForm.prototype = new overlayEnquiryForm();

