/**
 * Holiday search form
 *
 * @author          Malcolm Clark
 * @modifiedby      $LastChangedBy: Yuin $
 * @copyright       Copyright Flight Centre Ltd. All rights reserved.
 * @version         $Revision: 6295 $ 
 * @lastmodified    $Date: 2011-11-25 09:32:00 +1000 (Fri, 25 Nov 2011) $
 * @requires        jQuery, jQuery.cookie
 */
;RTW.TOURS = 
{
    destinations: {},
    defaults: {},
	currentMode: "",
	priceQueryElement: "",
	searchMapEntry: "",
	flightType: {
		"Round The World": "round-the-world",
		"Flights": "flights",
		"Scenic Route": "multi-stop",
		"One Way": "one-way",
		"Business%22,%22First": "business"
	},
	doUpdate: false,
	
	starterPackagesDropDown: '<option value="City Intros">City Intros</option>',
	
	toursDropDown:	'<option value="Youth">18-35 style</option>' +
					'<option value="Families">Family Tours</option>' +
					'<option value="Festivals">Festivals</option>' +
					'<option value="Overland">Overland Trips</option>' +
					'<option value="Special">Special Interest (eg cookery, photography)</option>' +
					'<option value="Sporting">Sporting and Active (eg cycling)</option>' +
					'<option value="Volunteering">Volunteering</option>' +
					'<option value="Walking">Walking & Trekking</option>' +
					'<option value="Rainforest_Ecotours">Wildlife & Nature</option>' +
					'<option value="Late Getaways">Late Getaways</option>' +
					'<option value="Small Group">Special Offers</option>',
	
	// Yuin - 18/11/11 - Change hotel star ratings to be consistent with main menu query strings
	hotelsDropDown: '<option value="2~3">Budget Hotel un-graded or 2* - 3*</option>' + // value must have a comma separated list of numbers, representing stars
					'<option value="3~4">Standard Hotel - 3* - 4*</option>' +
					'<option value="4~7">Luxury Hotel 4* - 5*+</option>' +
					'<option value="Hostel">Hostel</option>' +
					'<option value="Lodge">Lodge</option>',
	// hotelsDropDown: '<option value="2,2.5,3">Budget Hotel un-graded or 2* - 3*</option>' + // value must have a comma separated list of numbers, representing stars
	// 				'<option value="3,3.5,4">Standard Hotel - 3* - 4*</option>' +
	// 				'<option value="4,4.5,5,5.5,6,6.5">Luxury Hotel 4* - 5*+</option>' +
	// 				'<option value="Hostel">Hostel</option>' +
	// 				'<option value="Lodge">Lodge</option>',
	flightsDropDown:'<option value="Round The World">Round the World</option>' +
					'<option value="Scenic Route">Multi-stop</option>' +
					'<option value="One Way">One Way</option>' +
					'<option value="Business%22,%22First">Business Class</option>',
	
	// Yuin - 18/11/11 - To point back to dropdown menu option values
	flightSelOptions: {
		"round-the-world": "Round The World",
		"multi-stop": "Scenic Route",
		"one-way": "One Way",
		"business": "Business%22,%22First"
	},

	/* LG: Mapping between search and product fields
	  // Other fields can be added, but are not atm.
	  // Values are not normaly in use
	  // Product_selection is set to the main value. For some specific selections, JS will set it
	  // Ex: Adventure - mainly it is "Other", but for Overland Trips, Late Gateways, or Special Offers, it is different
	*/
	searchMap: {
		// "round-the-world": {
		"flights": {
			productCategory: "Air Transportation",
			page: {
				"list": {
					name: "list" 
				},
				"under-1000": {
					name: "under-1000",
					other: {
						name: "advertised_from_price",
						value: "between 0 ~ 1000"
					}
				},
				"budget": {
					name: "budget",
					other: {
						name: "advertised_from_price",
						value: "between 1000~1500, between 1500~2000, > 2000"
					}
				},
				"continental": {
					name: "continental",
					productSelection: "Other"
				},
				"round-the-world": {
					name: "round-the-world",
					productSelection: "Round The World"
				},
				"multi-stop": {
					name: "multi-stop",
					productSelection: "Scenic Route"
				},
				"one-way": {
					name: "one-way",
					productSelection: "One Way"
				},
				"business": {
					name: "business",
					other: {
						name: "booking_class",
						value: "Business,First"
					}
				}
			}
		},
		"places-to-stay": {
			productCategory: "Accommodation",
			path: '/places-to-stay/list/&query=product_category+is+"Accommodation"',
			page: {
				"list": {
					name: "list",
					productSelection: "Hotel",
					other: {
						name: "star_rating",
						value: "2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7"
					}
				}
			}
		},
		"activities": {
			productCategory: "Tour", // What about "Activities"?? If Activities are used, no need for duration??
			path: '/activities/list/&query=product_category+is+"Tour"',
			page: {
				"list": {
					name: "list",
					other: {
						name: "product_selection", // 
						value: "day tour" // This value is used for building the search string
					}
				}
			}
		},
		"adventure": {
			productCategory: "Tour",
			path: '/adventure/list/&query=product_category+is+"Tour"',
			page: {
				"deals": {
					name: "deals",
					other: {
						name: "holiday_experience", // Most used. Other is "Traveller Type"
						value: ""
					}
				},
				"late-getaways": {
					name: "late-getaways",
					productSelection: "Last Minute"
				}
			}
		},
		"city-intros": {
			productCategory: "Accommodation",
			path: '/city-intros/list/&query=product_category+is+"Accommodation"',
			page: {
				"list": {
					name: "list",
					other: {
						name: "holiday_experience",
						value: "Short Breaks - Other" // This value is used for building the search string
					}
				}
			}
		},
		"travel": {
			productCategory: "travel", // LG: There should not be Inspiration category, but some other field. Which?
			path: '/city-intros/list/&query=product_category+is+"Accommodation"',
			page: {
				"list": {
					name: "list",
					other: {
						name: "holiday_experience",
						value: "Short Breaks - Other" // This value is used for building the search string
					}
				}
			}
		}
	},
	
    init: function() 
    {
		$(document).ready(function() {
			// No result message
			if ($('#searchResults').children().size() === 0) {
				$('#searchResults').append("<div class='noResultsMessage'><p>Sorry, we don't currently have anything on the site in that category for your chosen destination.</p><p>Either search again under a different destination or product category (and we understand that may not be ideal if you have your heart set on going to a particular place) or better still, give us a call on 0800 707 6010 and tell us what you were looking for and we'll do a search for you.</p></div>");
			} else {
				$('.noResultsMessage').remove();
			}

			// Yuin - 05/12/11 - "No results" function for landing pages
			if ($('#page_container .content').children().size()===0) {
				$('#page_container .content').append("<div class='noResultsMessage'><p>Sorry, we don't currently have anything on the site in that category for your chosen destination.</p><p>Either search again under a different destination or product category (and we understand that may not be ideal if you have your heart set on going to a particular place) or better still, give us a call on 0800 707 6010 and tell us what you were looking for and we'll do a search for you.</p><p>&nbsp;</p></div>");		// Yuin - 24/11/11 - Dummy text. To change
				$('.page_navigation').remove();
			} else {
				$('.noResultsMessage').remove();
			}

			// Pagination Plugin
			if($('#page_container').length) {
				$('#page_container').pajinate({
					items_per_page : 5,
					num_page_links_to_display : 5,
					nav_label_first : '<<',
					nav_label_last : '>>',
					nav_label_prev : 'Previous',
					nav_label_next : 'Next'
				});
			}
		});

		this.$tourSearchForm = $('#holidays_search_form_page');
		this.$byDestination = this.$tourSearchForm.find('select[name="byDestination"]');	// yuin - 14/11/11 - "Region"
		this.$byRegion = this.$tourSearchForm.find('select[name="byRegion"]');				// yuin - 14/11/11 - "Country"
		this.$byExperience = this.$tourSearchForm.find('select[name="byExperience"]');		// yuin - 14/11/11 - "Flight/Aventure/Accommodation"
		this.$submitButton = this.$tourSearchForm.find('div.InputButton img');
		
  //       this.setupForm();
		// this.setupCurrentMode();
        FCL.SIGNALS.send('RTW.TOURS', 'init');
    },

    /** 
     * Bind form events and load contintent data
     */    
    setupForm: function()
    {    
        var JSON = /*RTW.TOURS.environment() + */"/wps/wcm/myconnect/roundtheworldexperts.co.uk/global/destinations/continents?callback=";

		$.getJSON(JSON, function(data) 
        {
            RTW.TOURS.destinations = data;
            RTW.TOURS.setupContinents(); 
			RTW.TOURS.setupParameterSelection();
        });
		
		this.$byDestination.bind('change', function(event) 
        {
            RTW.TOURS.updateRegions($(this).val());
        });
        
        this.$tourSearchForm.bind('submit', function(event) 
        {
            event.preventDefault();
            RTW.TOURS.validate();
        }); 
		
		this.$submitButton.bind('click', function(event)
		{
			$('#holidays_search_form_page').submit();
		});
// ***********************************************************************************************           
// Yuin - 18/11/11 - Retaining product selection accordingly (Working so far)
// ***********************************************************************************************           
var firstPath = window.location.pathname;
var firstPathSplit = firstPath.split('/');

// Yuin - 18/11/11,21/11/11 - TEST ****************************************************
switch(firstPathSplit[1]){	// depending on categories product search to respond accordingly
	case "flights":
		// var JSON = /*RTW.TOURS.environment() + */"/wps/wcm/myconnect/roundtheworldexperts.co.uk/global/destinations/continents?callback=";
		var flightsMatch = window.location.href.match(/round-the-world|multi-stop|one-way|business|list/i);	// matching front part of url
		
		if(firstPathSplit.length < 3 || (window.location.href.indexOf("overview") != -1 && window.location.href.indexOf("price+between") != -1)){
			$.cookie('RTW.TOURS.COOKIE', null);	// clear cookie if overview pages or ALL general searches
		}
		else if ((flightsMatch != null && window.location.href.indexOf("overview") != -1) || (window.location.href.indexOf("destination") != -1 && window.location.href.indexOf("overview") != -1)){
			var flightOption = this.flightSelOptions[flightsMatch[0]];
			setTimeout( function() { $('select[name="byExperience"]').children('option[value="'+ flightOption +'"]').attr('selected', 'selected'); }, 300 );

			$.getJSON(JSON, function(data){		// Get all destinations under continents page on WCM
            	// To match href to all continents
				var regionSplit = window.location.pathname.replace(/\+/g,' ').replace(/%22/g,'');
				var regionMatch = regionSplit.match(/Asia|North Asia|Central Asia|South East Asia|Africa|North Africa|East Africa|West Africa|Southern Africa|Indian Subcontinent|India|Nepal|Sri Lanka|Latin America|Central America|Caribbean|South America|Australasia|Australia|New Zealand|North America|Canada|United States|Middle East|Pacific Nations/i);

				RTW.TOURS.updateRegions(regionMatch[0]);
				setTimeout( function() { $('select[name="byDestination"]').children('option[value="'+ regionMatch[0] +'"]').attr('selected', 'selected'); }, 300 );
			});	
		}
		else{
			this.defaults = $.parseJSON($.cookie('RTW.TOURS.COOKIE'));
			if ( this.defaults != null ) {
				setTimeout( function() { RTW.TOURS.setSelectedIfDefault('byDestination'); }, 1000 );
				setTimeout( function() { RTW.TOURS.setSelectedIfDefault('byRegion'); }, 1037 );		// not ideal - slight flickering change
				setTimeout( function() { RTW.TOURS.setSelectedIfDefault('byExperience'); }, 1000 );
			}
		}	
		break;
	case "adventure":  // These categories needs destinations update
	case "places-to-stay":
		// var JSON = /*RTW.TOURS.environment() + */"/wps/wcm/myconnect/roundtheworldexperts.co.uk/global/destinations/continents?callback=";
		// var adventureMatch = window.location.href.match(/(adventure)\/list|/i)	// matching front part of url
		var adventureQMatch = window.location.href.match(/Youth|Families|Festivals|Overland|Special|Sporting|Volunteering|Walking|Rainforest_Ecotours|Late Getaways|Small Group/i)			// matching adventure subcategories
								|| window.location.href.match(/2~3|3~4|4~7|Hostel|Lodge/i);	// matching places to stay subcategories
		if(firstPathSplit.length < 3){
			$.cookie('RTW.TOURS.COOKIE', null);	// clear cookie if overview pages or ALL general searches
		}
		else if (adventureQMatch != null && window.location.href.indexOf("overview") != -1){		// 17/11/11 - working but not including region updates
			var adventureOption = this.flightSelOptions[adventureQMatch[0]];
			setTimeout( function() { $('select[name="byExperience"]').children('option[value="'+ adventureQMatch[0] +'"]').attr('selected', 'selected'); }, 300 );
			
			// To update Region 
			$.getJSON(JSON, function(data){		// Get all destinations under continents page on WCM
            	// To match href to all continents 1
            	var dataContinents = '"'+data.continents+'"';
            	var allContinents = dataContinents.replace(/,/g,'|').replace(/"/g,''); //.replace(/ /g,'+');
            	var allRegions = '/'+allContinents+'/i';
				var modContinents = window.location.pathname.replace(/\+/g,' ');
				//To match href to all continents 3
				var cityQMatch = modContinents.match(allRegions);
			setTimeout( function() { $('select[name="byDestination"]').children('option[value="'+ cityQMatch[0] +'"]').attr('selected', 'selected'); }, 300 );
			});	
		}
		else if (window.location.href.indexOf("destination") != -1 && window.location.href.indexOf("overview") != -1){	// To update regions
			$.getJSON(JSON, function(data){		// Get all destinations under continents page on WCM
            	// To match href to all continents
				var regionSplit = window.location.pathname.replace(/\+/g,' ').replace(/%22/g,'');
				var regionMatch = regionSplit.match(/Asia|North Asia|Central Asia|South East Asia|Africa|North Africa|East Africa|West Africa|Southern Africa|Indian Subcontinent|India|Nepal|Sri Lanka|Latin America|Central America|Caribbean|South America|Australasia|Australia|New Zealand|North America|Canada|United States|Middle East|Pacific Nations/i);
				RTW.TOURS.updateRegions(regionMatch[0]);
				setTimeout( function() { $('select[name="byDestination"]').children('option[value="'+ regionMatch[0] +'"]').attr('selected', 'selected'); }, 300 );
			});	
		}
		else{
			this.defaults = $.parseJSON($.cookie('RTW.TOURS.COOKIE'));
			if ( this.defaults != null ) {
				setTimeout( function() { RTW.TOURS.setSelectedIfDefault('byDestination'); }, 1000 );
				setTimeout( function() { RTW.TOURS.setSelectedIfDefault('byRegion'); }, 1037 );		// not ideal - slight flickering change
				setTimeout( function() { RTW.TOURS.setSelectedIfDefault('byExperience'); }, 1000 );
			}
		}	
		break;
	case "city-intros": 	// These categories do not have "byExperience" field
	case "activities":
		// var adventureQMatch = window.location.href.match(/Youth|Families|Festivals|Overland|Special|Sporting|Volunteering|Walking|Rainforest_Ecotours|Late Getaways|Small Group/i);	// matching places to stay subcategories
		var JSON = /*RTW.TOURS.environment() + */"/wps/wcm/myconnect/roundtheworldexperts.co.uk/global/destinations/continents?callback=";

		if(firstPathSplit.length < 3){
			$.cookie('RTW.TOURS.COOKIE', null);	// clear cookie if overview pages or ALL general searches
		}
		else if (window.location.href.indexOf("destination") != -1 && window.location.href.indexOf("overview") != -1){
			$.getJSON(JSON, function(data){		// Get all destinations under continents page on WCM
            	// To match href to all continents 1
            	var allContinents = '"'+data.continents+'"';
            	var test1 = allContinents.replace(/,/g,'|').replace(/"/g,''); //.replace(/ /g,'+');
            	var allRegions = '/'+test1+'/i';
				var regionSplit = window.location.pathname.replace(/\+/g,' ').replace(/%22/g,'');
				var regionMatch = regionSplit.match(/Asia|North Asia|Central Asia|South East Asia|Africa|North Africa|East Africa|West Africa|Southern Africa|Indian Subcontinent|India|Nepal|Sri Lanka|Latin America|Central America|Caribbean|South America|Australasia|Australia|New Zealand|North America|Canada|United States|Middle East|Pacific Nations/i);

				RTW.TOURS.updateRegions(regionMatch[0]);
				setTimeout( function() { $('select[name="byDestination"]').children('option[value="'+ regionMatch[0] +'"]').attr('selected', 'selected'); }, 300 );
			});	
		}
		else{
			this.defaults = $.parseJSON($.cookie('RTW.TOURS.COOKIE'));
			if ( this.defaults != null ) {
				setTimeout( function() { RTW.TOURS.setSelectedIfDefault('byDestination'); }, 1000 );
				setTimeout( function() { RTW.TOURS.setSelectedIfDefault('byRegion'); }, 1037 );		// not ideal - slight flickering change
			}
		}	
		break;
	default:
		break;
}
// Yuin - 18/11/11 - end of TEST ****************************************************
	
    },
	
	setupParameterSelection: function() {		
		if ( RTW.UTIL.$_GET.continent !== "undefined" ) { 
			var element = this.$byDestination.children("[value = " + RTW.UTIL.$_GET.continent + "]");
			if ( $(element).val() ) {		
				$(element).attr("selected", "selected");
				RTW.TOURS.updateRegions(RTW.UTIL.$_GET.continent);
				RTW.TOURS.doUpdate = true;
			}
		}
		
		if ( RTW.UTIL.$_GET.category !== "undefined" ) { 
			var element = this.$byExperience.children("[value = " + RTW.UTIL.$_GET.category + "]");
			if ( $(element).val() ) {			
				$(element).attr("selected", "selected");
				RTW.TOURS.doUpdate = true;
			}
		}
	},
	
	setupParameterRegionSelection: function() {
		if ( RTW.UTIL.$_GET.country !== "undefined" ) { 

			var element = this.$byRegion.children("[value = " + RTW.UTIL.$_GET.country + "]");
			if ( $(element).val() ) {
				$(element).attr("selected", "selected");
				RTW.TOURS.doUpdate = true;
			}
		}
	},
	
	setupCurrentMode: function() {
		// var sub = window.location.href.match(/(round-the-world)\/(under-1000|budget|continental|round-the-world|one-way|multi-stop|business|list|overview)/i);
		// var sub = window.location.href.match(/(flights)\/(under-1000|budget|continental|one-way|round-the-world|multi-stop|business|list|overview)?/i);
		// var sub = window.location.href.match(/(flights)\/(budget|continental|tickets|list)\/(under-1000|round-the-world|multi-stop|one-way|business|)/i);	// yuin - 14/11/11
		var sub = window.location.href.match(/(flights)\/(budget|continental|tickets|list)\/(under-1000|round-the-world|multi-stop|one-way|business|)/i)
				|| window.location.href.match(/(flights)\/*$/);	// LG: 14/11/11 Did not want to introduce more and more subsets. This caters for the landing page
		
		// if (sub && sub.length > 2) {
		if (sub && sub.length > 1) {
			// var second = (sub[2]==="overview")?"flights":sub[2];
			// var second = (sub.length > 2)?(sub[2]+'/'+sub[3]):sub[2];	// yuin - 14/11/11
			//var second = (sub[3]==="")?sub[2]:(sub[2]+'/'+sub[3]);		// yuin - 14/11/11 - to cater for shorter urls
			var second = (!sub[3])?sub[2]:(sub[2]+'/'+sub[3]);		// LG: 14/11/11 - changed check to catch "undefined" as well. Otherwise it returns "/undefined/undefined" in case of landing page (.../flights)
			second = (typeof second==="undefined") ? "list": second; //if second is undefined, change for list (as listing page)
			
			var priceParam = window.location.href.match(/price[\s\+]+between[\s\+]+(\d|~|\u007e|%7e)+/i); // TODO: refactor to be more robust

			if (priceParam && priceParam.length > 0) {
				this.priceQueryElement = "+and+" + priceParam[0];
			}
			
			this.currentMode = '/' + sub[1]+'/'+ second + '/&query=product_category+is+"Air+Transportation"'+this.priceQueryElement;			

			this.searchMapEntry = "flights";
			$("#byExperience").append(RTW.TOURS.flightsDropDown);
			$("#byExperienceHeader").html("Flight Type:");
		} 
		else if (window.location.href.indexOf("adventure") != -1) {
				this.currentMode = '/adventure/deals/&query=product_category+is+"Tour"';
				this.searchMapEntry = "adventure";
				$("#byExperience").append(RTW.TOURS.toursDropDown);
				$("#byExperienceHeader").html("Adventure Type:");
		} 
		else if (window.location.href.indexOf("places-to-stay") != -1) {	
				this.currentMode = this.searchMap["places-to-stay"].path;	// yuin - 15/11/11 - fix syntax
				this.searchMapEntry = "places-to-stay";
				$("#byExperience").append(RTW.TOURS.hotelsDropDown);	// OLD CODES: $("#typesListS").append(RTW.TOURS.hotelsDropDown);
				$("#byExperienceHeader").html("Accommodation Type:");
		} 
		else if (window.location.href.indexOf("activities") != -1) {
				this.currentMode = this.searchMap.activities.path;
				this.searchMapEntry = "activities";
				$("#byExperienceHeader").parent().remove();
		} 
		else if (window.location.href.indexOf("city-intros") != -1) {
				this.currentMode = this.searchMap["city-intros"].path;		// yuin - 15/11/11 - fix syntax
				this.searchMapEntry = "city-intros";
				$("#byExperienceHeader").parent().remove();
		} 
		else if (window.location.href.indexOf("travel") != -1) {
				this.currentMode = this.searchMap["travel"].path;
				this.searchMapEntry = "travel";
				$("#byExperienceHeader").parent().remove();
				//$(".FormDropdown .Heading").text()[]
		} 
		else {
				this.currentMode = '/adventure/deals/&query=product_category+is+"Tour"';
				this.searchMapEntry = "";
				$("#byExperience").append(RTW.TOURS.starterPackagesDropDown);
				$("#byExperienceHeader").html("Holiday Type:");
		}
	},
    
    /**
     * Every time the form is used the state of the form is saved in a cookie
     * If this cookie exists, extract the defaults and save them to ET.EVENTS,
     * then for the select fields that are not dynamic, set them to their previously
     * selected value
     */
    loadFormDefaults: function()
    {
        if($.cookie('RTW.TOURS.COOKIE') != null)
        {
            this.defaults = JSON.parse($.cookie('RTW.TOURS.COOKIE'));
            this.setSelectedIfDefault('byDestination');
            this.setSelectedIfDefault('byExperience');
        }
    },

    
    /**
     * JSON AJAX request to get all continents
     * We replace Oceania Australia with Australia & South Pacific for usability
     */
    setupContinents: function() 
    {
        var destinations = [];
        var continents = RTW.TOURS.destinations.continents;
        var options = '';
        
        for (var i=0; i < continents.length; i++) 
        {
            destinations[i] = continents[i];
        };
 
        for (var i=0; i < continents.length; i++) 
        {
            options += '<option value="'+destinations[i]+'">'+destinations[i]+'</option>'; 
        }
        
        this.$byDestination.append(options);
        //$('this.$byDestination option[value="Oceania and Australia"]').text('Australia & South Pacific');
        
        //this.loadFormDefaults();
    },

    /**
     * If a default field value exists from a previous form instance and its not blank 
     * (has not been set already), set the field name to the default value
     */
    setSelectedIfDefault: function(fieldName)
    {
        //TODO: Remove this old code
        // This is prone to crash in IE6
        try
        {
            var defaultVar = this.defaults[fieldName];
			if(typeof(defaultVar) != 'undefined' && defaultVar != '' && defaultVar != null)
            {
                var $selectedOption = this.$tourSearchForm.find('select[name="'+ fieldName +'"]').children('option[value="'+  defaultVar +'"]').attr('selected', 'selected');
                var $selectedOptionParent = $selectedOption.parent();
                $selectedOptionParent.trigger('change');
                this.defaults[fieldName] = '';
            }
        }
        catch(e)
        {
            // Reset this field to its blank state to avoid confusion
             this.$tourSearchForm.find('select[name="' + fieldName +'"]').val('');
        }
    },
	
	/**
     * Using the supplied contitent, modify it and it to execute a JSON AJAX which will return
     * the list of countries in byCountry for that continent.
     */
    updateRegions: function(strDestination) 
    {
        _this = this;
        //TODO: Remove this old code (Yuin - 22/11/11 - these codes are being used!)
        this.$byRegion.attr('disabled', true).val('');
        var strDestination = strDestination.toLowerCase().split(' ').join('');

        if (strDestination == 'all')
        {
            //$byCountry.attr('disabled', true);
                this.$byRegion.empty()
                    .append('<option value="">All Countries</option>')
                    //.append(options)
                    .attr('disabled', true)
                    .val('all');
            return;
        }

        var JSON = /*RTW.TOURS.environment() + */'/wps/wcm/myconnect/roundtheworldexperts.co.uk/global/destinations/'+strDestination+'?callback=';
        $.getJSON(JSON, function(data) 
        {
            if (data.countries.length > 0) 
            {
                RTW.TOURS.destinations = data;
                var arrList = [];
                var objCountries = RTW.TOURS.destinations.countries.sort();
                
                // RTW.TOURS.setSelectedIfDefault('byCountry');
                //RTW.TOURS.setSelectedIfDefault('byRegion');		// yuin - 16/11/11 - to correct select name for "Country"
            };
			
			if (strDestination == 'all')
			{
				RTW.TOURS.$byRegion.empty()
						 .append('<option value="">All Countries</option>')
						 .append(options)
						 .attr('disabled', true)
						 .val('');	// original code
				return;
			}
			
			var regions = RTW.TOURS.destinations.countries;
			var options = '';
			
			for (var i=0; i < regions.length; i++) 
			{
				  options += '<option value="'+regions[i]+'">'+regions[i]+'</option>'; 
			};

			RTW.TOURS.$byRegion.empty()
					 .append('<option value="">All Countries</option>')
					 .append(options)
					 .attr('disabled', false)
					 .val('all')		// yuin - 16/11/11 - To make "Country" (byRegion) option to update when "All Countries" is selected
					 .show();
					 
			RTW.TOURS.setupParameterRegionSelection();
			if ( RTW.TOURS.doUpdate ) { RTW.TOURS.$tourSearchForm.submit(); }
			//RTW.TOURS.setSelectedIfDefault('byRegion');
			
        });    
    },
    
    /**
	 * Basically, we need at least one field filled out before we can search
	*/
    validate: function() 
    {
        var byDestination = this.$byDestination.val();
        var byExperience = this.$byExperience.val();
        var byRegion = this.$byRegion.val();
        
		// check if checkbox ticked
		this.buildQueryString(byExperience, byRegion, byDestination);
    },
    
    /**
     * Based on a combination of field selections, build the search string
     */
    buildQueryString: function(byExperience, byRegion, byDestination) 
    {
        var query='';
        var extra='';
        var sort='+sort+weighting+price-+';
		var exp="";
        
        if (byRegion!='' && byRegion != 'all' ) {
            query='+and+destination+is+"'+byRegion+'"';
            //extra='&region='+byRegion;
        } else if (byDestination !="" && byDestination != 'all') {
            query = '+and+destination+is+"'+byDestination+'"';
        };
        
		/* Yuin - 22/11/11 - to cater for all cases of "byExperience = all" including "flights", "adventure", "places-to-stay" **************************/
        if (byExperience!='') {


 			if (this.currentMode.match(/city-intros|activities/i)) {
				query 	+= '+and+'+this.searchMap[this.searchMapEntry].page["list"].other.name
						+'+like+"'+this.searchMap[this.searchMapEntry].page["list"].other.value+'"';
			} 
			else if (this.currentMode.match(/flights/i)) {
				var flight = this.currentMode.match(/(flights)\/(budget|continental|tickets|list)\/(under-1000|round-the-world|multi-stop|one-way|business)/i)
					|| this.currentMode.match(/(flights)\/(budget|list)/i);	// Yuin: 22/11/11 
				
				if (byExperience.match(/(Round The World|Scenic Route|One Way)/i)) {
					this.currentMode = this.currentMode.replace(flight[0],'flights/tickets/'+this.flightType[byExperience]);
					query += '+and+product_selection+like+"' + byExperience +'"';
				}
				else if(byExperience.match(this.flightSelOptions['business'])){
					this.currentMode = this.currentMode.replace(flight[0],'flights/tickets/business');
					query += '+and+booking_class+like+"' + byExperience +'"';
				}
			} 
			else if (this.currentMode.match(/places-to-stay/i)) {
				if (byExperience.match(/hostel|lodge/i)) {
					query += '+and+product_selection+is+"' + byExperience + '"';
				} else {
					// Yuin - 18/11/11 - to set query string to "between" for fields with star ratings
					query += '+and+product_selection+is+"hotel"+' + 'star_rating+between+' + byExperience;
				} 
			} 
			else if (this.currentMode.match(/adventure/i)) {
				if ( byExperience === "Late Getaways" ) {
					this.currentMode = this.currentMode.replace(/deals/,"late-getaways");
					query += '+and+product_selection+like+"' + this.searchMap.adventure.page["late-getaways"].productSelection + '"';
				} else if ( exp = byExperience.match(/(Overland|Small Group)/i) ) {
					query += '+and+product_selection+like+"'+exp[1]+'"';
				} else if (  exp = byExperience.match(/(Youth|Families)/i) ) {
					query += '+and+travellers+like+"'+exp[1]+'"';
				} else {
					query += '+and+'+this.searchMap[this.searchMapEntry].page["deals"].other.name+'+like+"'+byExperience+'"';
				}
			} 
			else {
				query += '+and+product_selection+like+"' + byExperience + '"+and+'
						+this.searchMap[this.searchMapEntry].page["list"].other.name+'+like+"'+this.searchMap[this.searchMapEntry].page["list"].other.value+'"';
			}

// console.log('this.currentMode: '+this.currentMode);

		};
		// /* Yuin - 22/11/11 - to cater for all cases of "byExperience = all" including "flights", "adventure", "places-to-stay" **************************/

   //          if ( byExperience == "all") {
			// 	// LG: this is added for product categories that only need 2 search fields
			// 	// Yuin - 18/11/11 - Need to cater/merge this with "flights", "adventures", "places to stay"?
			// 	if (this.currentMode.match(/city-intros|activities/i)) {
			// 		query 	+= '+and+'+this.searchMap[this.searchMapEntry].page["list"].other.name
			// 				+'+like+"'+this.searchMap[this.searchMapEntry].page["list"].other.value+'"';
			// 	}
			// } else {
				
			// 	// Round the World
			// 	// if (this.currentMode.match(/round-the-world/i)) {
			// 	if (this.currentMode.match(/flights/i)) {
			// 		// Because of the new file structure, if it is a "flight-type" page, the url has to change, rather than adding to the query
			// 		// var flight = this.currentMode.match(/(round-the-world\/)(round-the-world|one-way|multi-stop|business|list)/i);
			// 		// var flight = this.currentMode.match(/(flights\/)(round-the-world|one-way|multi-stop|business|list)/i);
			// 		// LG 14/11/11: We need to separate 1. "flights/tickets/(round-the-world|multi-stop|etc.)" pages from 2. "flights/list", and "flights/budget" pages
			// 		var flight = this.currentMode.match(/(flights\/)(list|budget)/i);
			// 		if (!flight) { // means did not find flights/list
			// 			flight = this.currentMode.match(/(flights\/tickets\/)(round-the-world|one-way|multi-stop|business)/i);
			// 		}

			// 		if (flight && flight.length > 2) {
			// 			var re = new RegExp(flight[1]+flight[2]);
			// 			// LG 14/11/11: in all cases the resulting url will have a form of "flights/tickets/{byExperience}", so I hard coded it. This way it combines cases 1 and 2 above
			// 			this.currentMode = this.currentMode.replace(re,'flights/tickets/'+this.flightType[byExperience]); 
			// 		} 

			// 		if (byExperience.match(/Business|First/i)) {
			// 				query += '+and+booking_class+like+"' + byExperience +'"';
			// 		} else {
			// 			query += '+and+product_selection+like+"' + byExperience +'"';
			// 		}
			// 	} else if (this.currentMode.match(/places-to-stay/i)) {

			// 		if (byExperience.match(/hostel|lodge/i)) {
			// 			query += '+and+product_selection+is+"' + byExperience + '"';
			// 		} else {
			// 			// // LG: 15/11/11 JS does not like object notation accessing propertiy names having "-", so it was erroring here
			// 			// query += '+and+product_selection+is+"' + this.searchMap["places-to-stay"].page["list"].productSelection + '"';
			// 			// var stars = byExperience.split(',');
			// 			// var starRating = "";
			// 			// for (var i=0; i < stars.length; i++) {
			// 			// 	if (i===0) {
			// 			// 		starRating += '"'+stars[i]+' star"';
			// 			// 	} else {
			// 			// 		starRating += ',"'+stars[i]+' star"';
			// 			// 	}
			// 			// }
			// 			// // LG: 15/11/11 Same as above, changed access to the property "place-to-stay"
			// 			// query += (stars.length)?"+and+"+this.searchMap["places-to-stay"].page["list"].other.name+"+like"+starRating:"";

			// 			// Yuin - 18/11/11 - to set query string to "between" for fields with star ratings
			// 			query += '+and+product_selection+is+"hotel"+' + 'star_rating+between+' + byExperience;
			// 		} 
			// 	} else if (this.currentMode.match(/adventure/i)) {
			// 		if ( byExperience === "Late Getaways" ) {
			// 			this.currentMode = this.currentMode.replace(/deals/,"late-getaways");
			// 			query += '+and+product_selection+like+"' + this.searchMap.adventure.page["late-getaways"].productSelection + '"';
			// 		} else if ( exp = byExperience.match(/(Overland|Small Group)/i) ) {
			// 			query += '+and+product_selection+like+"'+exp[1]+'"';
			// 		} else if (  exp = byExperience.match(/(Youth|Families)/i) ) {
			// 			query += '+and+travellers+like+"'+exp[1]+'"';
			// 		} else {
			// 			query += '+and+'+this.searchMap[this.searchMapEntry].page["deals"].other.name+'+like+"'+byExperience+'"';
			// 		}
			// 	} else {
			// 		query += '+and+product_selection+like+"' + byExperience + '"+and+'
			// 				+this.searchMap[this.searchMapEntry].page["list"].other.name+'+like+"'+this.searchMap[this.searchMapEntry].page["list"].other.value+'"';
			// 	}
			// }
        // };

        /* Yuin - 17/11/11 ***********************************************************************************/
        // Set cookies
        var holidaysCookie = {};
        this.$tourSearchForm.find('select').each(function()
        {
            holidaysCookie[$(this).attr('name')] = $(this).val();
        });
        this.$tourSearchForm.find('input').each(function()
        {
            holidaysCookie[$(this).attr('name')] = $(this).attr('checked');   
        });

		var firstPath = window.location.pathname;
		var firstPathSplit = firstPath.split('/');
        
        // Save field values so we can re-create its selections when next used
		// $.cookie('RTW.TOURS.COOKIE', JSON.stringify(holidaysCookie), { path: window.location.pathname  });
		$.cookie('RTW.TOURS.COOKIE', JSON.stringify(holidaysCookie), { path: "/"+firstPathSplit[1]+"/"  });	// Yuin - 18/11/11 - cookie to apply to main categories (Flights/Adventure/...) only
		// $.cookie('RTW.TOURS.COOKIE', JSON.stringify(holidaysCookie), { path: firstPathSplit[0]  });		// only update the specific path
		
		//var cityTours = 'product_selection+is+"Holiday+Package"';
		if ( query == '' ) { "first 20" }
 
        window.location.href = RTW.TOURS.currentMode + query + sort + extra;
        // window.location.href = RTW.TOURS.currentMode + query + sort + extra + '/&destination=' + byDestination + '=region=' + byRegion + '=experience=' + byExperience;	// Yuin - to append dropdownmenu selection to back of url to retain selection after search
        /* ORIGINAL codes ***********************************************************************************/

    },
        
    toggleLabel: function()
    {
        if ($('#toolTip').is(':hidden'))
        {
            $('#toolTip').show();
        }
        else
        {
            $('#toolTip').hide();
        }
    },
    
    /*Jquery pagination to simulate Sitecat*/
    paginate: function()
    {
        //TODO: Refactor
        try
        {
            $('#searchresults').pajinate(
            {
                items_per_page : 12,
                nav_label_prev: '&lt;&lt;&nbsp;Previous',
                nav_label_next: 'Next&nbsp;&gt;&gt;',
                nav_label_first: '',
                nav_label_last: '',
                nav_panel_id: '.viewAll',
                num_page_links_to_display: 12
            })
        }catch(e){}
    }
};
RTW.TOURS.init();
