
// ==============================================================================
// Someone has clicked the search button


// ==============================================================================
(function($) { 

  if (typeof $.fn.disableTextSelect == 'undefined') {
    $.extend($.fn.disableTextSelect = function() {
      var bindType = 'mousedown';
      if ($.browser.msie)
        bindType = 'selectstart';
      return this.each(function() {
        $(this).bind(bindType, function() { return false; });
      });
    });
  }


  $(document).ready(function() {

    var arriveMinObj = new Date(_propertyDate); //$('#booking-search-container input[name=propertyDate]').val()
    var departMinObj = new Date(arriveMinObj);
    departMinObj.setDate(arriveMinObj.getDate() + 1);

    $("#booking-search-container #fromDate").datepicker({
      minDate: arriveMinObj,
      maxDate: "2y",
      dateFormat: "d M yy",
      altField: '#booking-search-container input[name=fromDateActual]',
      altFormat: "yy-mm-dd",
      showAnim: 'fadeIn',
      onSelect: function(selectedDate) {
        var instance = $(this).data("datepicker");
        var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
        date.setDate(date.getDate() + 1);
        $("#booking-search-container #toDate").datepicker("option", 'minDate', date);
      }
    });

    $("#booking-search-container #toDate").datepicker({
      minDate: departMinObj,
      maxDate: "2y",
      dateFormat: "d M yy",
      altField: '#booking-search-container input[name=toDateActual]',
      altFormat: "yy-mm-dd",
      showAnim: 'fadeIn'
    });



    $("#booking-search-container .toDate-cal a").click(function() {
      $('#booking-search-container #toDate').datepicker('show');
      return false;
    });
    
    $("#booking-search-container .fromDate-cal a").click(function() {
      $('#booking-search-container #fromDate').datepicker('show');
      return false;
    });


    $("#booking-search-container div.region-tab, #booking-search-container div.property-tab").disableTextSelect();
    
	  $('#booking-inner-container #propertyId').attr('disabled', 'disabled');

    // add the tab smarts
	// region tab active
    $("#booking-search-container div.region-tab").click(function() {
      $('#booking-inner-container #search-type').find('select, input').css('display', 'none');
	  
	  $('#booking-panel-tabs').addClass('region-tab-active');
	  $('#booking-panel-tabs').removeClass('property-tab-active');
      $(this).addClass('region-tab-active-colour');
	  $(this).removeClass('property-tab-active-colour');
      $("#booking-search-container .property-tab").addClass('property-tab-inactive-colour');
	  $(this).removeClass('region-tab-inactive-colour');
	 
	  $('#booking-inner-container #propertyId').css('display', 'none').attr('disabled', 'disabled');
      
	  $("#booking-inner-container #propertyId").hide();
	  $("#booking-inner-container #regionId").show();
	  $("#booking-inner-container #regionId").addClass('region-select').focus();

      $('#search-type-title').text('Region');
      $('#booking-search-container input[name=selectedTab]').val('region');
    });

	// property tab active
    $("#booking-search-container div.property-tab").click(function() {
      $('#booking-inner-container #propertyId').removeAttr('disabled');
	   $('#booking-panel-tabs').removeClass('region-tab-active');
	   $('#booking-panel-tabs').addClass('property-tab-active');
	  $(this).addClass('property-tab-active-colour');
	  $(this).removeClass('region-tab-active-colour');
      $("#booking-search-container div.region-tab").addClass('region-tab-inactive-colour');
      $(this).removeClass('property-tab-inactive-colour');

	  $("#booking-inner-container #regionId").addClass('region-select-inactive');
	  $("#booking-inner-container #regionId").hide();
	  $("#booking-inner-container #propertyId").show();
      $("#booking-inner-container #propertyId").addClass('property-select-active').focus();
      $("#search-type-title").text('Property');
      $('#booking-search-container input[name=selectedTab]').val('property');

    });

    //$('#booking-inner-container #search-type select').each(function() {
    //  if ($(this).attr('id') == '') {
    //    $(this).css('background-color', '#ffffff');
    //  }
    //});

/*
    $('#booking-inner-container #propertyId').searchable({
      maxListSize: 150,                       // if list size are less than maxListSize, show them all
      maxMultiMatch: 150,                      // how many matching entries should be displayed
      exactMatch: false,                      // Exact matching on search
      wildcards: false,                       // Support for wildcard characters (*, ?)
      ignoreCase: true,                       // Ignore case sensitivity
      latency: 200,                           // how many millis to wait until starting search
      warnMultiMatch: 'top {0} matches ...',  // string to append to a list of entries cut short by maxMultiMatch
      warnNoMatch: 'no matches ...',          // string to show in the list when no entries match
      zIndex: 'auto'                            // zIndex for elements generated by this plugin
    });
*/

	// close both client login and booking cancellations box
	$("#booking-search-container .close-button, #client-login-submit, #cancel-submit").click(function() {
		$("#background-popup").css("display", "none");
		$("#booking-inner-container .center-horizon").css("display", "none");
		$("#booking-inner-container .client-login-box").css("display", "none");
		$("#booking-inner-container .cancel-box").css("display", "none");
	});

	// client login box
	$("#booking-search-container .client-link a").click(function() {
		if ($('#booking-search-container input[name=selectedTab]').val() == 'property' && $('#propertyId').val() != '' ) {
			var propertyName = $('#propertyId option:selected').text();
			$('#booking-search-container .client-content-text').html('Please enter your user name and password to access <b>' + propertyName + '</b> Special Client Booking Facility. <br /><br /><span style="font-size: 10px;">Note: If you have a Corporate login use the region tab first.</span>');
		} else {
			$('#booking-search-container .client-content-text').html('Please enter your <b>Corporate Client</b> user name and password for access to the Special Client Booking Facility. <br /><br /><span style="font-size: 10px;">Note: If you have a specific property login use the property tab and select the property first.</span>');
		}

    // we have a form underneath us, make a new form and put our bits in it
	  $("#booking-search-container #client-login-submit").click(function() {
      var actionUrl = '';
      if ( $('#booking-search-container input[name=selectedTab]').val() == 'property' && $('#propertyId').val() != '' ) {
        actionUrl = 'http://'+ $('#propertyId').val() + '/clientAuthenticate.html';
      } else {
        actionUrl = _actionSite + 'clientAuthenticate.html';
      }

      window.location = actionUrl +'?autoUser='+escape($('#booking-search-container input[name=login_name_supplied]').val())+'&autoPass='+escape($('#booking-search-container input[name=password_supplied]').val());
    });

    $('#booking-search-container input[name=login_name_supplied], #booking-search-container input[name=password_supplied]').keypress(function(event) {
      var charCode = event.charCode || event.keyCode;
      if(charCode == 13 || charCode == 3) {
        $("#booking-search-container #client-login-submit").click();
        return false;
      }
    });

		$("#background-popup").fadeIn();
		$("#booking-inner-container .center-horizon").css("display", "block");
		$("#booking-inner-container .client-login-box").css("display", "block");
		$("#booking-inner-container .cancel-box").css("display", "none");

    return false;
	});



	// booking cancellations box
	$("#booking-search-container .cancel-link a").click(function() {
    $("#background-popup").fadeIn();
	$("#booking-inner-container .center-horizon").css("display", "block");
    $("#booking-inner-container .cancel-box").css("display", "block");
    $("#booking-inner-container .client-login-box").css("display", "none");

	  $("#booking-search-container #cancel-submit").click(function() {
      window.location = _actionSite + 'bookingCancelValidate.html?referenceNumber='+escape($('#booking-search-container input[name=referenceNumber]').val())+'&lastName='+escape($('#booking-search-container input[name=lastName]').val());
    });

    $('#booking-search-container input[name=referenceNumber], #booking-search-container input[name=lastName]').keypress(function(event) {
      var charCode = event.charCode || event.keyCode;
      if(charCode == 13 || charCode == 3) {
        $("#booking-search-container #cancel-submit").click();
        return false;
      }
    });

    return false;
	});



    function _submitLevartPanel() {
      var fromValue = $('#booking-search-container input[name=fromDateActual]').val();
      var toValue = $('#booking-search-container input[name=toDateActual]').val();
      
      var startDate = new Date(fromValue.replace(/-/g, '/'));
      var endDate = new Date(toValue.replace(/-/g, '/'));
      var timeDiff = endDate - startDate;
      daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));


      var selectedValue = $('#booking-search-container input[name=selectedTab]').val();
      if (selectedValue == 'region') {
        if ($('#booking-search-container select[name=regionId]').val() == "") {
          alert('Please select a region from the list to continue.');
          return false;
        }

        if (daysDiff >= 14) {
          alert('You have selected a '+daysDiff+' night stay which is greater than the maximum of 13 days. Please search the desired property directly as the regional search is not available for long stays.');
          return false;
        }

      } else if (selectedValue == 'property') {
        var propertyToSearch = $('#booking-search-container select[name=propertyId]').val();

        if (propertyToSearch == "") {
          alert('Please select a property from the list to continue.');
          return false;
        }

        if (daysDiff >= 14 || _searchDirect == propertyToSearch) {

          var actionUrlProperty = 'http://'+ propertyToSearch + '/bookingSearchMultiple.html';
          var fromDateDay = startDate.getDate();
          var fromDateMonth = startDate.getMonth();
          var fromDateYear = startDate.getFullYear();
          var toDateDay = endDate.getDate();
          var toDateMonth = endDate.getMonth();
          var toDateYear = endDate.getFullYear();

          var inputs = '<input type="hidden" name="fromDateDay" value="'+fromDateDay+'"/>'+
            '<input type="hidden" name="fromDateMonth" value="'+fromDateMonth+'"/>'+
            '<input type="hidden" name="fromDateYear" value="'+fromDateYear+'"/>'+
            '<input type="hidden" name="fromDateMonthYear" value="'+fromDateMonth+'-'+fromDateYear+'"/>'+
            '<input type="hidden" name="toDateDay" value="'+toDateDay+'"/>'+
            '<input type="hidden" name="toDateMonth" value="'+toDateMonth+'"/>'+
            '<input type="hidden" name="toDateYear" value="'+toDateYear+'"/>'+
            '<input type="hidden" name="toDateMonthYear" value="'+toDateMonth+'-'+toDateYear+'"/>'+
            '<input type="hidden" name="room1Adults" value="'+$('#booking-search-container select[name=adults]').val()+'"/>'+
            '<input type="hidden" name="room1Children" value="'+$('#booking-search-container select[name=children]').val()+'"/>'+
            '<input type="hidden" name="rooms" value="'+$('#booking-search-container select[name=rooms]').val()+'"/>'+
            '<input type="hidden" name="gridlayout" value="1"/>';

          $('<form action="'+ actionUrlProperty +'" method="post">'+inputs+'</form>')
              .appendTo('body').submit().remove();

          return false;
        }

      } else {
        alert('Internal Error: Neither property or region tab is currently selcted.');
      }


      if (typeof loadSearchResults == 'function') { 

        // disable the submit button, change image 
        $('#booking-search-container input[type=submit]').attr('disabled', 'disabled').addClass('inactive').blur();

        // we're internal on the bookingSearchProperties page
        loadSearchResults(false);
      } else {
        
        /*
        $('#booking-search-container form input[name=fromDate], #booking-search-container form input[name=toDate]').attr('disabled', 'disabled'); 
        if (selectedValue == 'region') {
          $('#booking-search-container form select[name=propertyId]').attr('disabled', 'disabled');
        } else if (selectedValue == 'property') {
          $('#booking-search-container form select[name=regionId]').attr('disabled', 'disabled');
        }*/

        // make sure the form action is the right one
        if ($('#booking-search-container').closest('form').length > 0) {

          // we have a form underneath us, make a new form and put our bits in it
          var inputs = '';
          $("#booking-search-container input[type=hidden], #booking-search-container select").each(function(){
            if ($(this).attr('name').length)
              inputs += '<input type="hidden" name="'+ $(this).attr('name') +'" value="'+ $(this).val() +'" />';
          });

          $('<form action="'+ _actionUrl +'" method="get">'+inputs+'</form>')
              .appendTo('body').submit().remove();

          return false;
        }

        try {
          var _gaq = window._gaq || [];
          _gaq.push(['_linkByPost', document.getElementById('bookingSearch'), true]);
        } catch(e) {}

        return true;
      }

      return false;
    }


    // if we have our own form then submit it directly
    $('#booking-search-container form').submit(function() {
      return _submitLevartPanel(); 
    });

    // if theres a form already inserted before our panel
    $('form #booking-search-container input[type=submit]').click(function() {
      return _submitLevartPanel();
    });

    if ($('#booking-search-container input[name=selectedTab]').val() == 'property') {
      $("#booking-search-container div.property-tab").focus().click();
    }

  });

})(jQuery);

function closeWindows() {
	document.getElementById("background-popup").style.display = 'none';
	document.getElementById("client-login-box").style.display = 'none';
	document.getElementById("cancel-box").style.display = 'none';
}

