/************************************************
* Initialise Date Pickers
************************************************/
$('document').ready(function($) {
  //Initialise date Picker

  Date.format = 'dd-mm-yyyy';


  $.dpConst.CAL_TITLE = 'Return Date:' ;

  //Initiate Date Picker
  //$(function(){ jQuery('input.date-pick').datePicker({clickInput:true});} ); //End datePicker initiation

  $(function(){ jQuery('#startDate').datePicker({clickInput:true,sCaltitle:'Departure Date'});} ) ; //End datePicker initiation
  $(function(){ jQuery('#search_return_date').datePicker({clickInput:true,sCaltitle:'Return Date'});} ) ; //End datePicker initiation


    //Bind events to set start and end dates
    jQuery('#startDate').bind(
    		'dpClosed',
    		function(e, selectedDates)
    		{
    			var d = selectedDates[0];
    			if (d) {
    				d = new Date(d);
    				$('#search_return_date').dpSetStartDate(d.addDays(1).asString());
    			}
    			callCounter();
    		}
    	);

    	jQuery('#search_return_date').bind(
    		'dpClosed',
    		function(e, selectedDates)
    		{
    			var d = selectedDates[0];
    			if (d) {
    				d = new Date(d);
    				$('#startDate').dpSetEndDate(d.addDays(-1).asString());
    			}
    			callCounter();
    		}
    	);



});





/************************************************
* Form Validation
*************************************************/

function searchFormValidation() {
  //what type of search is being performed

  //if search Type is 1 then just run the search it's no problem
    var nErrors = 0 ;
    var sMsg = 'Sorry you MUST fill in a departure date along with a return date, alternatively fill in the departure date, and leave the return date blank.' ;
    oDte = document.getElementById('startDate') ;
    oRetDte = document.getElementById('search_return_date') ;
    if ( (oRetDte.value!=='' && oRetDte.value!='-Any date-') && (oDte.value=='' ||oDte.value=='-Any date-')) {
      nErrors = 1 ;

      alert(sMsg) ;
      return false;
    }

    return callResultsPreLoader();

}



/*************************************************
* GLOBAL ACTIVITYBREAKS SEARCH FORM
**************************************************/

function toggleHotels(sAccomVal) {
  if (sAccomVal=='1') {
    $('#hotel-rating').css('display','block') ;
    $('#search_hotel_rating_label').css('opacity',1) ;
    $('#hotel-rating').css('opacity',1) ;
  } else {
    document.getElementById('search_hotel_rating').options[0].selected = 'selected';
    $('#hotel-rating').css('display','none') ;
  }
}


/************************************************************************************************************
* AJAX FUNCTIONALITY BELOW THIS LINE
*************************************************************************************************************/
//GLOBALS

//create a form object
var formobj = document.getElementById('main_search_form');  //contains ID of the search form


//only allow ajax calls to happen if the processing of the previousl call has occured
var goodToGo = true ;
var setFalseBy = '';
var bChangeCountry = false;

/**
* If either country / destination / activity / sub activity are selected we need to re populates the others
* instead of that simply re-populate them all, but with a seperate AJAX call for each to help with speed.
*/
function callDropDownChange(bChange) {
  bChangeCountry = (bChange == null) ? false : true;

  if (bChangeCountry == true) {
    document.getElementById('search_destination_id').selectedIndex = 0;
  }

  //First put up a little 'busy' icon
  showWorkingAnim();

  //put a tiny pause on each update.
  callDestinationChange();

  setTimeout("callCountryChange()",200);

  setTimeout("callActivityChange()",50);
  setTimeout("callSubActivityChange()",50);
  setTimeout("callTravellerFilter()",50);

  //This last one clears the busy icon
  setTimeout("callCountProducts()",350);

}//end function callDropDownChange

//Launches the Product Counter only
function callCounter() {
  //First put up a litlle 'busy' icon
  showWorkingAnim() ;
  //This last one clear the busy icon
  callCountProducts();
}

/**
 * @access public
 * @return void
 **/

/*************************************************
* GLOBAL ACTIVITYBREAKS SEARCH FORM
**************************************************/

/**
* When a country is selected
* @param int country id
*/
function callDestinationChange() {

  $('#performAction').val('getDestinationList');

  //our ajax object gets the form values for us so we needn't build a long url oursleves.
  var aFormVars = $('#main_search_form').serializeArray();

  var errorMsg = '<h2>Ooops</h2><p>Either I couldn\'t find out what cities are available or I couldn\'t get a list of activities.<br />Please try again.</p>' ;

  if (goodToGo == true ) {
    $.post('/ajax/MainSearchForm',aFormVars, repopulateDestinations,"json");
  }
  $('#performAction').val('');
}//end function



function callCountryChange() {
  $('#performAction').val('getCountryId');
  //our ajax object gets the form values for us so we needn't build a long url oursleves.
 var aFormVars = $('#main_search_form').serializeArray();
 var errorMsg = '<h2>Ooops</h2><p>Either I couldn\'t find out what country that\'s in<br /> or I couldn\'t get a list of activities</p><p>Please try again</p>' ;
 if (goodToGo == true ) {
   $.post('/ajax/MainSearchForm',aFormVars,repopulateCountry,'json');
 }
  $('#performAction').val('');
}//end function

function callActivityChange() {
  $('#performAction').val('getActivities');
  //our ajax object gets the form values for us so we needn't build a long url oursleves.
 var aFormVars = $('#main_search_form').serializeArray();
 var errorMsg = '<h2>Ooops</h2><p>Sorry, I wasn\'t able to get the list of available activity types</p>' ;
 if (goodToGo == true ) {
   $.post('/ajax/MainSearchForm',aFormVars,repopulateActivity,'json');
 }
  $('#performAction').val('');
}//end function


/*************************************************
* GLOBAL ACTIVITYBREAKS SEARCH FORM
**************************************************/

function callSubActivityChange() {
  $('#performAction').val('getSubActivities');
  //our ajax object gets the form values for us so we needn't build a long url oursleves.
 var aFormVars = $('#main_search_form').serializeArray();
 var errorMsg = '<h2>Ooops</h2><p>Sorry, I wasn\'t able to get the list of activities</p>'
 if (goodToGo == true ) {
   $.post('/ajax/MainSearchForm',aFormVars,repopulateSubActivity,'json');
 }
   $('#performAction').val('');
}//end function




function callTravellerFilter() {
  $('#performAction').val('travellerFilter');
  //our ajax object gets the form values for us so we needn't build a long url oursleves.
 var aFormVars = $('#main_search_form').serializeArray();
 var errorMsg = '<h2>Ooops</h2><p>Sorry, something went a bit wrong there. Please refresh the page and try again</p>' ;
 if (goodToGo == true ) {
   $.post('/ajax/travellerFilter',aFormVars,repopulateTravellers,'json');
 }
   $('#performAction').val('');
}//end function   callTravellerFilter();


function callCountProducts() {
  $('#performAction').val('countProducts');
  //our ajax object gets the form values for us so we needn't build a long url oursleves.
 var aFormVars = $('#main_search_form').serializeArray();
     aFormVars.push({name : 'output', value:'countonly'});

 var errorMsg = '<h2>Ooops</h2><p>Sorry, It was taking me too long to count how many holidays match your criteria</p><p>You can still go ahead click search to see what\'s available though.</p>' ;

 $.post('/ajax/MainSearchForm',aFormVars,showTotalCount,'json');
 // ajaxObj.call('action=MainSearchForm'+form_vars,showTotalCount);
}

function callResultsPreLoader() {
  if($('#sidecontainer').length>=1) {
   $('#sidecontainer').hide();
  }
  if($('#lm-skyscraper').length) {
    $('#lm-skyscraper').hide();
  }

  $('#search_text_header').html('Holiday') ;
  $('#search_text_p').addClass('normal');
  $('#search_text_p').html('... for your chosen holiday');

  //position the search-loading div to centre of screen.
  //screenHeight = YAHOO.util.Dom.getViewportHeight();
  var screenHeight = $(window).height();

  newY = (screenHeight/3)
  $('#search-loading').css('top',newY + 'px') ;
  $('#search-loading').css('display','block');
  $('#main_search_form').css('display','none');

  //wait 1.5 seconds before doing the pre-load
  var ajaxcaller = window.setTimeout("callResultsAJAX()",1500);
  alphaMode(0);
  return false;
}

  /**
   *
   * @access public
   * @return void
   **/


function callResultsAJAX(){

  //set the timeout to 60 seconds and that's loads.
  var errorMsg = '<h2>Ooops</h2><p>I\'m sorry. Something went a bit wrong there.<br />Please try again.</p>' ;
  //reset performAction
  $('input[name="performAction"]').val('');
  //reset Loading
  $('input[name="loading"]').val('');
  var aFormVars = $('#main_search_form').serializeArray();
      aFormVars.push({name : 'bAjaxPreLoader', value:'1'});
  var sExtraUrl = formVarsToFriendlyURL(aFormVars) ;
  //clean_form_vars = cleanQueryString(form_vars) ;
  $.getJSON('/ajax/Search/',aFormVars,jumpToResults);
}

function formVarsToFriendlyURL(aFields) {
  var sUrl = '';
  jQuery.each(aFields, function(i, aFields){
    if (aFields.value!='' && aFields.name!='' && aFields.value.substr(0,4)!='-Any' && aFields.value.substr(0,4)!='-any' && aFields.value.substr(0,4)!='E.G. ' && aFields.value !='Don\'t mind') {
      sUrl+= (aFields.name + "/"+aFields.value+'/');
    }
  });
  return sUrl ;
}

/**
* remove any form option that weren't completed from the query string
* remove any options that were merely required by the preLoader or ajax counter
**/
function cleanQueryString(query) {

  var newQuery = '' ;
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    if (vars[i]!='') {
      var pair = vars[i].split("=");
      //Make sure its not empty and Not an -Any option
      if (pair[1] != '' && pair[0]!='loading' && pair[0]!='undefined' && pair[0]!='performAction' && (pair[1].indexOf("-Any")==-1) && (pair[1].indexOf("-any")==-1) && (pair[1].indexOf("-Don't mind")==-1) && (pair[1].indexOf('Airport Code e.g. LGW')==-1) && (pair[1].indexOf('yyyy')==-1) ) {
        newQuery+= '&' + pair[0] +'='+pair[1] ;
      }
    }
  }

   return newQuery ;
}


/**********************************
* GLOBAL ACTIVITYBREAKS SEARCH FORM
**********************************/

function jumpToResults(aResult){
    //remove any error func calls
    //now jump to results
    var aFormVars = $('#main_search_form').serializeArray();
    var sExtraUrl = formVarsToFriendlyURL(aFormVars) ;
    //sQueryString = cleanQueryString(sFormVars) ;
    location.href = '/search/'+sExtraUrl ;
    return true;
}



/**
* REPOPULATE THE SELECT DROP DOWNS
**/

function repopulateDestinations(aResponse) {
  goodToGo = false ;
  setFalseBy = 'destinations';
  aDests = aResponse['aDestinations'] ;

  if (aDests =='null' || aDests==null || aDests=='' || typeof(aDests)=='undefined') {
    goodToGo = true ;
    return;
  }

  //first empty the old destination list.
  objDest = document.getElementById('search_destination_id')
  oldDest = $('#search_destination_id').val();
  //set a new value of empty
  $('#search_destination_id').val('')

  //empty the old list
  while (1 < objDest.options.length) {
    objDest.options[(objDest.options.length - 1)] = null;
  }
  if (aDests && typeof(aDests)!='undefined') {
    var selectedIndex = 0;
    var selIndex = 0;
    objDest.options[0] = new Option("-Any Region-", "", false, false);
    var i=0 ;
    for (destId in aDests) {
		  if (aDests[destId] != '' && aDests[destId] != 'undefined' ) {
	     objDest.options[i+1] = new Option(aDests[destId], destId, false, false);

		  }

		  //selected index ?
		  if (destId == oldDest) {
        selectedIndex = destId
        selIndex = i+1
		  }
		  //increment our counter
		  i = i + 1 ;
	  }//end for

	  selectedIndex = selectedIndex==0 ? '' : selectedIndex ;
	  objDest.value = selectedIndex

    if (selectedIndex==0) {
      toggleElements('destination_display','destination_options') ;
    }

  }//end if != undefined
  goodToGo = true ;
  popAllFields();
}//end function


function repopulateCountry(aResponse) {
  if (bChangeCountry == false) {
    bChangeCountry = true;
    return false;
  }

  goodToGo = false ;
  setFalseBy = 'country';
  //first empty the old destination list.
  aResponse['nCountryId'] = aResponse['nCountryId']==0 ? '' : aResponse['nCountryId'] ;

  if (aResponse['nCountryId']>=1) {
    $('#search_destination_id').removeAttr('disabled');
  }else {
    $('#search_destination_id').attr('disabled','true');
  }
  $('#search_country_id').val(aResponse['nCountryId']);

  goodToGo = true ;
  popAllFields();
}//end function


function repopulateTravellers(aResponse) {
  return;
  if ( typeof(aResponse)=='undefined' || (aResponse['max_children'] == '' && aResponse['max_adults'] == '') ) {
    return false;
  }
  var sResponse = '';

  goodToGo = false ;
  setFalseBy = 'Travellers';
  //first empty the old destination list.
  //oAdults = document.getElementById('num_adults') ;
  //oChild = document.getElementById('num_children') ;

  //get original values
  nAdults = oAdults.value;
  nChildren = oChild.value;

  //empty the old lists
  while (1 < oAdults.options.length) {
		  oAdults.options[(oAdults.options.length - 1)] = null ;
	}

  while (1 < oChild.options.length) {
		  oChild.options[(oChild.options.length - 1)] = null ;
	}

	//now refill
  var adultSelectedIndex = 0;
  oAdults.options[0] = new Option("-Adults-", "", false, false);

  var j=0 ;
  if (aResponse['max_adults']>=1) {
    for (j=1; j<=aResponse['max_adults']; j++) {
      valuestring = j==1 ? j+' Adult' : j+' Adults';
      if (j==nAdults) {
        adultSelectedIndex = j;
      }
  	  oAdults.options[j] = new Option(valuestring, j, false, false);
  	}
    oAdults.selectedIndex = adultSelectedIndex ;
  }

  var childSelectedIndex = 0 ;
    oChild.options[0] = new Option("-Children-", "", false, false);

  var c=0 ;
  if (aResponse['max_children']>=1) {
    for (c=1; c<=aResponse['max_children']; c++) {
      childvaluestring = c==1 ? c+' Child' : c+' Children';
      if (c==nChildren) {
        childSelectedIndex = c;
      }
  	  oChild.options[c] = new Option(childvaluestring, c, false, false);

  	}
  	oChild.selectedIndex = childSelectedIndex ;
  }



  goodToGo = true ;
  popAllFields();

}//end function repopulateTravellers

/*************************************************
* GLOBAL ACTIVITYBREAKS SEARCH FORM
**************************************************/

function repopulateActivity(aResponse) {

  goodToGo = false ;
  setFalseBy = 'activity';

  if (aResponse['aActivities'] =='null' || aResponse['aActivities'] ==null) {
    goodToGo = true ;
    //set sub-category selector to disabled
    $('#search_sub_category_id').attr('disabled','true');
    popAllFields();
    return;
  }

  //first empty the old list.
  objPkg = document.getElementById('search_category_id') ;
  oldPkg = objPkg.value ;


  if (aResponse && typeof(aResponse)!='undefined') {
    //empty the old list
    while (1 < objPkg.options.length) {
		  objPkg.options[(objPkg.options.length - 1)] = null ;
	  }

    var selectedIndex = 0;
    objPkg.options[0] = new Option("-Any Activity Type-", "", false, false);
    var j=0 ;
    var activityinner = '';
    aActivities = aResponse['aActivities'] ;
    for (pkgId in aActivities) {
		  if (aActivities[pkgId] != '' && aActivities[pkgId] != 'undefined' ) {
	      objPkg.options[j+1] = new Option(aActivities[pkgId], pkgId, false, false);
		   }

		   //increment our counter
		   j = j + 1 ;
		   //selected index ? Do this after incrementing to take accout of the zero option -Select-
		   if (pkgId == oldPkg) {
         selectedIndex = j ;
		   }
	   }//end for


     objPkg.selectedIndex = selectedIndex ;



    //If selected index is zero then that means the new list does not have what was previously selected
    // so we need to ensure that we are dispalying the drop down so that a new choice can be made.
    if (selectedIndex==0 || j==0) {
      $('#search_sub_category_id').attr('disabled','true');
    } else {
      $('#search_sub_category_id').removeAttr('disabled');
    }

  }//end if
  goodToGo = true ;
  popAllFields();
}//end function


function repopulateSubActivity(aResponse) {
  goodToGo = false ;
  setFalseBy = 'subActivities';
  if (aResponse['aSubActivities'] =='null' || aResponse['aSubActivities'] ==null) {
    popAllFields();
    goodToGo = true ;
    return;
  }
  //first empty the old list.
  objPkg = document.getElementById('search_sub_category_id') ;

  oldPkg = objPkg.value ;

  if (oldPkg=='') {
    oldPkg = 0;
  }

  originalSubCat ='';
  var selectedIndex = 0;
  if (aResponse && typeof(aResponse)!='undefined') {
    //empty the old list
    while (1 < objPkg.options.length) {
		  objPkg.options[(objPkg.options.length - 1)] = null ;
	  }

    objPkg.options[0] = new Option("-Any Activity-", "", false, false);
    var j=0 ;
    aActivities = aResponse['aSubActivities'] ;
    for (pkgId in aActivities) {
		  if (aActivities[pkgId] != '' && aActivities[pkgId] != 'undefined' ) {
	      objPkg.options[j+1] = new Option(aActivities[pkgId], pkgId, false, false);
		   }

		   //increment our counter
		   j = j + 1 ;
		   //selected index ? Do this after incrementing to take accout of the zero option -Select-
		   if (pkgId == oldPkg && oldPkg!=0) {
         selectedIndex = j ;
		   }
	   }//end for

     objPkg.selectedIndex = selectedIndex ;


    //If selected index is zero then that means the new list does not have what was previously selected
    // so we need to ensure that we are dispalying the drop down so that a new choice can be made.
    if (selectedIndex==0) {
    //toggleElements('category_display','category_options') ;
    }
  }//end if
  popAllFields();
  goodToGo = true ;
}

/*************************************************
* GLOBAL ACTIVITYBREAKS SEARCH FORM
**************************************************/

function showWorkingAnim() {
  $('#product-counter').css('display','block');
  $('#product-counter').html('<span class="large">Searching..</span><img src="/img/ajax/aj-loader-sml.gif" alt="Loading: the system is busy working something out for you" width="16" height="16" />');
}

function showTotalCount(aResponse) {

  var sHtml  = '';
  if (aResponse['nCount'] == null || typeof(aResponse)=='undefined' || parseInt(aResponse['nCount'])<=0) {
    //No Number return so just hide the layer
    $('input.search-button').css('display','none' ) ;
  } else {
    $('input.search-button').css('display','inline' );
  }
    sHtml = aResponse['nCount']+' breaks found'+(aResponse['nCount']==0 ? '<br />Try Again' : '')  ;

  $('#product-counter').html(sHtml);
}


/**********************************************************
*
* NON AJAX Functions
*
***********************************************************/
/**
 * @access public
 * @return void
 **/
function popAllFields(){
  popField('search_country_name',document.getElementById('search_country_id'));
  popField('search_destination_name',document.getElementById('search_destination_id'));
  popField('search_category_name',document.getElementById('search_category_id'));
  popField('search_sub_category_name',document.getElementById('search_sub_category_id'));
}


function popField(sField,oObj) {
  newVal = oObj.options[oObj.selectedIndex].text ;
  newVal2 = newVal.replace('&','and') ;
  newVal2 = newVal2.replace('\/','') ;
  newVal3 = newVal2.replace(/\s/gi, "-");
  newVal4 = newVal3.toLowerCase();
  document.getElementById(sField).value = (newVal4) ;
}


function disallowDates(date) {
    var dCurrent = new Date();
    var today = new Date(dCurrent.getFullYear(), dCurrent.getMonth(), dCurrent.getDate());
    if (date.getTime() < today.getTime())
      return true
    else
      return false
}

function setStartDayDate() {

  var startdate = document.getElementById('start_date').value ;
  if (startdate != '') {
    var aStartDate = startdate.split('-');
    var start_date       = aStartDate[2] + '-' + aStartDate[1] + '-' + aStartDate[0] ;
    document.getElementById('show_date').innerHTML = start_date ;
  }
}

function setReturnDayDate() {

  var retdate = document.getElementById('search_return_date').value ;
  if (retdate != '') {
    var aRetDate = retdate.split('-');
    var retdate       = aRetDate[2] + '-' + aRetDate[1] + '-' + aRetDate[0] ;
    document.getElementById('show_return_date').innerHTML = retdate ;
  }
}


/**
* Simple function to toggle the className of an element thus allowing it to be hidden or dispalyed
*/
function toggleElements(elOff,elOn) {
  $(elOff).addClass('hidden').removeClass('nothidden');
  $(elOn).addClass('nothidden').removeClass('hidden');
}



function insertOption(obj,val,opt) {
  if (obj.selectedIndex >= 0) {
    var elOptNew = document.createElement('option');
    elOptNew.text = opt;
    elOptNew.value = val;
    obj.selectedIndex = 0;
    var elOptOld = obj.options[obj.selectedIndex];
    try {
      obj.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
    }
    catch(ex) {
      obj.add(elOptNew, obj.selectedIndex); // IE only
    }
  }

}


function toggleAdvOpts() {
  oObj = document.getElementById('search-advanced-options') ;
  oLink = document.getElementById('adv-search-toggle') ;
  oHideLink = document.getElementById('adv-search-hide') ;
  curState = oObj.style.display;
  if (curState!='block') {
    oObj.style.display = 'block' ;
    oLink.style.display = 'none' ;
    oHideLink.style.display = 'block' ;
  } else {
    oObj.style.display = 'none';
    oLink.style.display = 'block' ;
    oHideLink.style.display = 'none' ;
    //reset adv options
    $('#search_accommodation').val("") ;
    $('#search_hotel_rating').val("Don't mind") ;
    //document.getElementById('search_duration').value="nights" ;
    $('#datecloseness').val(0) ;
    $('#num_adults').val("");
    $('#num_children').val("");
    oLink.innerText = 'Advanced Search' ;
  }

}



function resetDte(sId){
  oObj = document.getElementById(sId)
  oObj.value='-Any date-';
  callCounter();
}


// This listener just activates the autoComplete when everything loads
 //YAHOO.util.Event.addListener(window,'load',initAutoComplete);
 //YAHOO.util.Event.addListener(window,'load',initSearchBoxToolTips);