﻿///global variables for curencyID
var _CURRENCYIDCROATIAN = "191";
var _CURRENCYIDEU = "978";
var SerbianCountryID = "29";
var BeogradRegionID = "30";
var BeogradDestinationID = "41";

/// read tabId from cookie and select appropriate tab
function selectSearchTabFromValueInCookie() {
    var tabId = tryToReadFromCookie("searchTabId", 0);
    searchTabs.showTab(tabId);
}

/// Initialize accommodation search control
function InitializeAccommodationSearchControl() {
    /// Get the datepicker above flash   
    $("#ui-datepicker-div").css('z-index', '9999999 !important');

    if (languageIDSetting == 'en') {
        $.datepicker.setDefaults($.datepicker.regional['']);
        $.datepicker.setDefaults({ dateFormat: 'dd/mm/yy' });
    } else {
        $.datepicker.setDefaults($.datepicker.regional[languageIDSetting]);
        $.datepicker.setDefaults({ dateFormat: 'dd.mm.yy' });
    }

    $('#dateFromAccommodation').datepicker({
        onSelect: function(dateText, inst) {
            updateFromTo('dateFromAccommodation', 'dateToAccommodation');
        },
        minDate: 0
    });

    $('#dateToAccommodation').datepicker({
        onSelect: function(dateText, inst) {
            updateFromTo('dateFromAccommodation', 'dateToAccommodation');
        },
        minDate: 0
    });

    ///disable user to manually enters the dates
    $("#dateFromAccommodation").keypress(function(event) { event.preventDefault(); });
    $("#dateFromAccommodation").keydown(function(event) { event.preventDefault(); }); 		/// 'keydown' instead of 'keypress' so that it works in IE too

    $("#dateToAccommodation").keypress(function(event) { event.preventDefault(); });
    $("#dateToAccommodation").keydown(function(event) { event.preventDefault(); }); 		/// 'keydown' instead of 'keypress' so that it works in IE too
}

/// Initialize package tour search control
function InitializePackageTourSearchControl() {
    ///Get the datepicker above flash

    try {
        $("#ui-datepicker-div").css('z-index', '9999999 !important');
    } catch (e) { }

    if (languageIDSetting == 'en') {
        $.datepicker.setDefaults($.datepicker.regional['']);
        $.datepicker.setDefaults({ dateFormat: 'dd/mm/yy' });
    } else {
        $.datepicker.setDefaults($.datepicker.regional[languageIDSetting]);
        $.datepicker.setDefaults({ dateFormat: 'dd.mm.yy' });
    }

    $('#dateFromPackageTour').datepicker({
        onSelect: function(dateText, inst) {
            updateFromTo('dateFromPackageTour', 'dateToPackageTour');
        },
        minDate: 0
    });

    $('#dateToPackageTour').datepicker({
        onSelect: function(dateText, inst) {
            updateFromTo('dateFromPackageTour', 'dateToPackageTour');
        },
        minDate: 0
    });

    ///disable user to manually enters the dates
    $("#dateFromPackageTour").keypress(function(event) { event.preventDefault(); });
    $("#dateFromPackageTour").keydown(function(event) { event.preventDefault(); }); 		/// 'keydown' instead of 'keypress' so that it works in IE too

    $("#dateToPackageTour").keypress(function(event) { event.preventDefault(); });
    $("#dateToPackageTour").keydown(function(event) { event.preventDefault(); }); 		/// 'keydown' instead of 'keypress' so that it works in IE too    
}

/// implement Clear method to empty arrays
Array.prototype.Clear = function() {
    while (this.length > 0) {
        this.pop();
    }
}

/*** CATEGORY OBJECT ***/
///constructor:
function Category() {
    this.categoryId = 0;
    this.categoryName = "";
}

///this method return option element <option>...</option> for country
Category.prototype.GetOptionElement = function() {
    return "<option value='" + this.categoryId + "'>" + this.categoryName + "</option>";
}
/*** END OF CATEGORY OBJECT ***/
/*** COUNTRY OBJECT ***/
///constructor:
function Country() {
    this.countryId = 0;
    this.countryName = "";
}

///this method return option element <option>...</option> for country
Country.prototype.GetOptionElement = function() {
    return "<option value='" + this.countryId + "'>" + this.countryName + "</option>";
}
/*** END OF COUNTRY OBJECT ***/
/*** REGION OBJECT ***/
///constructor:
function Region() {
    this.regionId = 0;
    this.regionName = "";
    this.countryId = 0;
}

///this method return option element <option>...</option> for region
Region.prototype.GetOptionElement = function() {
    return "<option value='" + this.regionId + "' countryID='" + this.countryId + "'>" + this.regionName + "</option>";
}
/*** END OF REGION OBJECT ***/
/*** DESTINATION OBJECT ***/
///constructor:
function Destination() {
    this.destinationId = 0;
    this.regionId = 0;
    this.destinationName = "";
}

///this method return option element <option>...</option> for region
Destination.prototype.GetOptionElement = function() {
    return "<option value='" + this.destinationId + "' regionID='" + this.regionId + "'>" + this.destinationName + "</option>";
}
/*** END OF DESTINATION OBJECT ***/


/*** GLOBALS ***/
/// here we hold all categories we get from web service
var categoriesListPackageTour = new Array();
var categoriesListAccommodation = new Array();

/// here ve hold all countries we get from web service
var countriesListPackageTour = new Array();
var countriesListAccommodation = new Array();

/// here ve hold all regions we get from web service
var regionsListAccommodation = new Array();
var regionsListPackageTour = new Array();

/// here we hold only id's of regions that are currently visible. It's used to properly show all destinations if region is irelevant
var visibleRegionsIdListAccommodation = new Array();
var visibleRegionsIdListPackageTour = new Array();

/// here ve hold all destinations we get from web service
var destinationsListAccommodation = new Array();
var destinationsListPackageTour = new Array();


/// Function will try to find node by name in XML. If successful returns nodes text(), otherwise null
function tryToFindNodeInXml(xml, nodeName) {
    var node = xml.find(nodeName);
    if (node != null) {
        var nodeText = node.text();

        if (nodeText != null && nodeText != '') {
            return nodeText;
        }
    }
    return null;
}


/// find all categories in xml and populate categoriesList array
///     xml is XML returned from web service GetSearchFields
///     categoriesList is array in wich categories are saved
function getCategoriesFromXml(xml, categoriesList) {
    categoriesList.Clear();

    /// for each category in XML find it's name and id and create option element
    xml.find("Category").each(function() {
        var categoryXML = $(this);
        var category = new Category();

        category.categoryId = tryToFindNodeInXml(categoryXML, 'CategoryID');
        category.categoryName = tryToFindNodeInXml(categoryXML, 'CategoryName');

        if (category.categoryId != null && category.categoryName != null) {
            categoriesList.push(category);
        }
    });
}
/// populate the contents of Categories select list from array
///     categoriesSelectListID is ID of a select list in DOM wich will be populated with categories
///     categoriesList is list of categories from wich select list will be populated
function populateCategoriesSelectList(categoriesSelectListID, categoriesList) {
    var options = '<option value="0">' + irrelevantTranslationCategory + '</option>';

    $(categoriesList).each(function() {
        var category = this;
        options += category.GetOptionElement();
    });

    $("#" + categoriesSelectListID).html(options);
}



/// find all countries in xml and populate countriesList array
///     xml is XML returned from web service GetSearchFields
///     countriesList is array in wich countries are saved
function getCountriesFromXml(xml, countriesList) {
    countriesList.Clear();

    /// for each country in XML find it's name and id and create option element
    xml.find("Country").each(function() {
        var countryXML = $(this);
        var country = new Country();

        country.countryId = tryToFindNodeInXml(countryXML, 'CountryID');
        country.countryName = tryToFindNodeInXml(countryXML, 'CountryName');

        if (country.countryId != null && country.countryName != null) {
            countriesList.push(country);
        }
    });
}
/// populate the contents of Countries select list from array
///     countriesSelectListID is ID of a select list in DOM wich will be populated with countries
///     countriesList is list of countries from wich select list will be populated
function populateCountriesSelectList(countriesSelectListID, countriesList) {
    var options = '<option value="0">' + irrelevantTranslationCountry + '</option>';

    $(countriesList).each(function() {
        var country = this;
        options += country.GetOptionElement();
    });

    $("#" + countriesSelectListID).html(options);
}



/// find all regions in xml and populate countriesList array
///     xml is XML returned from web service GetSearchFields
///     regionsList is array in wich regions are saved
///     visibleRegionsList is array in wich visible regions id's are saved
function getRegionsFromXml(xml, regionsList, visibleRegionsList) {
    regionsList.Clear();
    visibleRegionsList.Clear();

    /// for each region in XML find it's name and id and create option element
    xml.find("Region").each(function() {
        var regionXML = $(this);
        var region = new Region();

        region.regionId = tryToFindNodeInXml(regionXML, 'RegionID');
        region.regionName = tryToFindNodeInXml(regionXML, 'RegionName');
        region.countryId = tryToFindNodeInXml(regionXML, 'CountryID');

        if (region.regionId != null && region.regionName != null && region.countryId != null) {
            regionsList.push(region);
            visibleRegionsList.push(region.regionId);
        }
    });
}
/// populate the contents of Regions select list from array
///     regionsSelectListID is ID of a select list in DOM wich will be populated with regions
///     regionsList is list of regions from wich select list will be populated
function populateRegionsSelectList(regionsSelectListID, regionsList) {
    var options = '<option value="0">' + irrelevantTranslationRegion + '</option>';

    $(regionsList).each(function() {
        var region = this;
        options += region.GetOptionElement();
    });

    $("#" + regionsSelectListID).html(options);
}



/// find all destinations in xml and populate destinationsList array
///     xml is XML returned from web service GetSearchFields
///     destinationsList is array in wich destinations are saved
function getDestinationsFromXml(xml, destinationsList) {
    destinationsList.Clear();

    /// for each destination in XML find it's name and id and create option element
    xml.find("Destination").each(function() {
        var destinationXML = $(this);
        var destination = new Destination();

        destination.destinationId = tryToFindNodeInXml(destinationXML, 'DestinationID');
        destination.destinationName = tryToFindNodeInXml(destinationXML, 'DestinationName');
        destination.regionId = tryToFindNodeInXml(destinationXML, 'RegionID');

        if (destination.destinationId != null && destination.destinationName != null && destination.regionId != null) {
            destinationsList.push(destination);
        }
    });
}
/// populate the contents of Destination select list from array
///     destinationsSelectListID is ID of a select list in DOM wich will be populated with destinations
///     destinationsList is list of destinations from wich select list will be populated
function populateDestinationsSelectList(destinationsSelectListID, destinationsList) {
    var options = '<option value="0">' + irrelevantTranslationDestination + '</option>';

    $(destinationsList).each(function() {
        var destination = this;
        options += destination.GetOptionElement();
    });

    $("#" + destinationsSelectListID).html(options);
}


/// Function converts strng to XML. It's used for IE6 and IE7 compatibility after ajax requests
var StringToXML = function(s) {
    var x, ie = /msie/i.test(navigator.userAgent);
    try {
        var p = ie ? new ActiveXObject("Microsoft.XMLDOM") : new DOMParser();
        p.async = false;
    } catch (e) { throw new Error("XML Parser could not be instantiated") };
    try {
        if (ie) x = p.loadXML(s) ? p : false;
        else x = p.parseFromString(s, "text/xml");
    } catch (e) { throw new Error("Error parsing XML string") };
    return x;
};


/// get search fields for accommodation search tab and populate select lists
function bindSearchFieldsToAccomodationSearchTab(objectTypeID, categoryID, countryID, regionID, destinationID) {
    $("#objectTypeSelectAccommodation").val(objectTypeID);

    /// problems with sending array to Server, using xmlGttpRequest instead jQuery
    var xmlhttp = null;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            /// parse result from server and populate fields
            //var xml = $(xmlhttp.responseText);
            var xml = $(StringToXML(xmlhttp.responseText));

            getCategoriesFromXml(xml, categoriesListAccommodation);
            populateCategoriesSelectList("categoriesSelectAccommodation", categoriesListAccommodation);
            if (categoryID > 0) {
                $("#categoriesSelectAccommodation").val(categoryID);
            }

            getCountriesFromXml(xml, countriesListAccommodation);
            populateCountriesSelectList("countriesSelectAccommodation", countriesListAccommodation);
            if (countryID > 0) {
                $("#countriesSelectAccommodation").val(countryID);
            }

            getRegionsFromXml(xml, regionsListAccommodation, visibleRegionsIdListAccommodation);
            populateRegionsSelectList("regionsSelectAccommodation", regionsListAccommodation);
            if (regionID > 0) {
                $("#regionsSelectAccommodation").val(regionID);
            }

            getDestinationsFromXml(xml, destinationsListAccommodation);
            populateDestinationsSelectList("destinationsSelectAccommodation", destinationsListAccommodation);
            if (destinationID > 0) {
                $("#destinationsSelectAccommodation").val(destinationID);
            }

            ///postavim da se automatski proba selektirati drzava Srbija i regija Beograd
            try
            {
                $("#countriesSelectAccommodation").val(SerbianCountryID);
                countriesSelectOnChangeAccommodation();
            }
            catch(err){}
            try
            {
                $("#regionsSelectAccommodation").val(BeogradRegionID);
                regionsSelectOnChangeAccommodation();
            }
            catch (err) { }
            try {
                $("#destinationsSelectAccommodation").val(BeogradDestinationID);
            }
            catch (err) { }
            
            

        }
    }

    var parameters = 'languageID=' + languageIDSetting + '&objectTypeIDList=' + objectTypeID + "&objectTypeGroupIDList=" + 3 + "&objectTypeGroupIDList=" + 4 + '&categoryIDList=' + categoryID + '&countryID=' + countryID + '&regionID=' + regionID;

    xmlhttp.open("post", "/XSLTControls/Proxy/ProxyWebService.asmx/GetSearchFields", true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(parameters);
}

/// get search fields for package tour search tab and populate select lists
function bindSearchFieldsToPackageTourSearchTab(objectTypeID, categoryID, countryID, regionID, destinationID) {
    $("#objectTypeSelectPackageTour").val(objectTypeID);

    /// problems with sending array to Server, using xmlGttpRequest instead jQuery
    var xmlhttp = null;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            /// parse result from server and populate fields
            //var xml = $(xmlhttp.responseText);
            var xml = $(StringToXML(xmlhttp.responseText));

            getCategoriesFromXml(xml, categoriesListPackageTour);
            populateCategoriesSelectList("categoriesSelectPackageTour", categoriesListPackageTour);
            if (categoryID > 0) {
                $("#categoriesSelectPackageTour").val(categoryID);
            }

            getCountriesFromXml(xml, countriesListPackageTour);
            populateCountriesSelectList("countriesSelectPackageTour", countriesListPackageTour);
            if (countryID > 0) {
                $("#countriesSelectPackageTour").val(countryID);
            }

            getRegionsFromXml(xml, regionsListPackageTour, visibleRegionsIdListPackageTour);
            populateRegionsSelectList("regionsSelectPackageTour", regionsListPackageTour);
            if (regionID > 0) {
                $("#regionsSelectPackageTour").val(regionID);
            }

            getDestinationsFromXml(xml, destinationsListPackageTour);
            populateDestinationsSelectList("destinationsSelectPackageTour", destinationsListPackageTour);
            if (destinationID > 0) {
                $("#destinationsSelectPackageTour").val(destinationID);
            }
        }
    }

    var parameters = 'languageID=' + languageIDSetting + '&objectTypeIDList=' + objectTypeID + "&objectTypeGroupIDList=" + 6 + '&categoryIDList=' + categoryID + '&countryID=' + countryID + '&regionID=' + regionID;

    xmlhttp.open("post", "/XSLTControls/Proxy/ProxyWebService.asmx/GetSearchFields", true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(parameters);
}

/// function populates search fields (from cookie or default values) in accommodation tab
function populateSearchFieldsInAccommodationTab() {
    PopulateSearchFieldsFromCookie('personsSelectAccommodation', 'dateFromAccommodation', 'dateToAccommodation', 'onlyOnSpecialOfferCheckBox');

    var searchTabID = tryToReadFromCookie("searchTabID", -1);

    /// if searchTabID is -1 or 0 then search is performed for accommodation so try to read values from cookie
    if (searchTabID == -1 || searchTabID == 0) {
        /// try to read values from cookie. If it fails return default value (second parameter)
        //objectTypeID = tryToReadFromCookie("objectTypeID", 0);
        objectTypeID = 0;
        categoryID = tryToReadFromCookie("categoryID", 0);
        countryID = tryToReadFromCookie("countryID", 0);
        regionID = tryToReadFromCookie("regionID", 0);
        destinationID = tryToReadFromCookie("destinationID", 0);
    }
    else {
        /// use default values
        objectTypeID = 0;
        categoryID = 0;
        countryID = 0;
        regionID = 0;
        destinationID = 0;
    }
    /// populate category, country, region and destination in accomodation tab
    bindSearchFieldsToAccomodationSearchTab(objectTypeID, categoryID, countryID, regionID, destinationID);
}

/// function populates search fields (from cookie or default values) in accommodation tab
function populateSearchFieldsInPackagetourTab() {
    PopulateSearchFieldsFromCookie(null, 'dateFromPackageTour', 'dateToPackageTour', 'onlyPackageToursOnSpecialOfferCheckBox');

    var searchTabID = tryToReadFromCookie("searchTabID", -1);
    objectTypeID = 0;

    /// if searchTabID is -1 or 1 then search is performed for package tour so try to read values from cookie
    if (searchTabID == -1 || searchTabID == 1) {
        categoryID = tryToReadFromCookie("categoryID", 0);
        countryID = tryToReadFromCookie("countryID", 0);
        regionID = tryToReadFromCookie("regionID", 0);
        destinationID = tryToReadFromCookie("destinationID", 0);
    } else {
        /// use default values
        categoryID = 0;
        countryID = 0;
        regionID = 0;
        destinationID = 0;
    }
    /// populate category, country, region and destination in package tour tab
    bindSearchFieldsToPackageTourSearchTab(objectTypeID, categoryID, countryID, regionID, destinationID);
}

/// function populates search fields that that are saved in cookie (date from, date to and number of persons)
function PopulateSearchFieldsFromCookie(personsSelectListID, dateFromID, dateToID, onlyOnSpecialOfferID) {
    /// defaults
    var numberOfPersons = 1;
    if (personsSelectListID != null) {
        numberOfPersons = tryToReadFromCookie("persons", 1);
        $("#" + personsSelectListID).val(numberOfPersons);
    }

    var dateFrom = new Date();
    if (dateFromID != null) {
        dateFrom.setTime(tryToReadFromCookie("from", dateFrom));
        $('#' + dateFromID).datepicker("setDate", dateFrom);
    }

    var dateTo = new Date();
    dateTo.setDate(dateTo.getDate() + 1);
    if (dateToID != null) {
        dateTo.setTime(tryToReadFromCookie("to", dateTo.getTime()));
        $('#' + dateToID).datepicker("setDate", dateTo);
    }

    var onlyOnSpecialOfferCheckBox = document.getElementById(onlyOnSpecialOfferID);

    setTimeout(function() {
        $('#' + dateFromID).datepicker("setDate", dateFrom);
        $('#' + dateToID).datepicker("setDate", dateTo);
    }, 500);

    if (onlyOnSpecialOfferCheckBox != null) {
        var onlyOnSpecialOffer = tryToReadFromCookie("onlyOnSpecialOffer", "krljb");
        if (onlyOnSpecialOffer == "true" || onlyOnSpecialOffer == "True") {
            onlyOnSpecialOfferCheckBox.checked = true;
        }
    }


}

/// function is called if object type or category in accomodation tab is changed. Request is made to the server to get new list od categories, countries, regions and destinations
function rebindSearchFieldsInAccommodationTab() {
    var objectTypeId = $("#objectTypeSelectAccommodation").val();
    var categoryId = $("#categoriesSelectAccommodation").val();
    var countryId = $("#countriesSelectAccommodation").val();
    var regionId = $("#regionsSelectAccommodation").val();
    var destinationId = $("#destinationsSelectAccommodation").val();

    bindSearchFieldsToAccomodationSearchTab(objectTypeId, categoryId, countryId, regionId, destinationId);
}

/// function is called if object type or category in package tour tab is changed. Request is made to the server to get new list od categories, countries, regions and destinations
function rebindSearchFieldsInPackageTourTab() {
    var objectTypeId = $("#objectTypeSelectPackageTour").val();
    var categoryId = $("#categoriesSelectPackageTour").val();
    var countryId = $("#countriesSelectPackageTour").val();
    var regionId = $("#regionsSelectPackageTour").val();
    var destinationId = $("#destinationsSelectPackageTour").val();

    bindSearchFieldsToPackageTourSearchTab(objectTypeId, categoryId, countryId, regionId, destinationId);
}


/// function is used to refresh regions. Regions that belong in selected country are shown
function updateRegionsList(regionsList, visibleRegionsIdList, countriesSelectListID, regionsSelectListID) {
    visibleRegionsIdList.Clear();

    var visibleRegions = new Array();
    var selectedCountryId = $("#" + countriesSelectListID).val();

    $(regionsList).each(function() {
        var region = this;
        if (selectedCountryId == 0 || region.countryId == selectedCountryId) {
            visibleRegions.push(region);
            visibleRegionsIdList.push(region.regionId);
        }
    });

    populateRegionsSelectList(regionsSelectListID, visibleRegions);
}

/// function is used to refresh destinations. Destinations that belong in selected region are shown
function updateDestinationsList(destinationsList, visibleRegionsIdList, regionsSelectListID, destinationsSelectListID) {
    var selectedRegionId = $("#" + regionsSelectListID).val();
    var visibleDestinations = new Array();

    $(destinationsList).each(function() {
        var destination = this;
        if ((selectedRegionId == 0 && $.inArray(destination.regionId, visibleRegionsIdList) >= 0) || destination.regionId == selectedRegionId) {
            visibleDestinations.push(destination);
        }
    });

    populateDestinationsSelectList(destinationsSelectListID, visibleDestinations);
}


function redirectSearchControl(address) {
    var url = address;
    ///check settings for frame
    var LinkLocation, SearchResultsAddress;
    var LinkLocationElement = $("#LinkLocationSettingAccommodation");
    if (LinkLocationElement != null) {
        LinkLocation = LinkLocationElement.val();
    }
    var SearchResultsAddressElement = $("#SearchResultsAddressSettingAccommodation");
    if (SearchResultsAddressElement != null) {
        SearchResultsAddress = SearchResultsAddressElement.val();
    }
    if (SearchResultsAddress != '') {
        var prefix = '?';
        if (SearchResultsAddress.indexOf('?') != -1) {
            prefix = '&';
        }
        url = SearchResultsAddress + prefix + 'itravelURL=' + UrlEncode(url);
    }

    if (LinkLocation != '') {
        switch (LinkLocation) {
            case 'parent':
                parent.location = url;
                break;
            case 'top':
                window.top.location = url;
                break;
            default:
                document.location = url;
                break;
        }
    }
    else {
        document.location = url;
    }
}

/// function is called on show entire accommodation button click
function showEntireAccommodationOfferClick(searchResultsURL) {

    var fromDate = new Date();
    var fromTicks = GetTicksFromDate(fromDate);
    var toDate = new Date();
    toDate.setDate(toDate.getDate() + 1);
    var toTicks = GetTicksFromDate(toDate);
    /// set accommodation type group id: 3 = private accommodation, 4 = hotels

    //var url = "/Accommodation/SearchResults.aspx";
    //url += "?searchTabID=0";
    var url = searchResultsURL;
    if (searchResultsURL.indexOf('?') != -1) {
        url += "&searchTabID=0";
    }
    else {
        url += "?searchTabID=0";
    }
    
    url += "&ignorePriceAndAvailability=1";
    url += "&categoryID=0";
    url += "&countryID=0";
    url += "&regionID=0";
    url += "&destinationID=0";
    url += "&objectTypeID=0";
    url += getVariableForQueryString("persons", "personsSelectAccommodation");

    var accommodationTypeGroupID = "3,4";
    url += "&objectTypeGroupID=" + accommodationTypeGroupID;
    url += "&languageID=" + languageIDSetting;

    // Save all info into a cookie so that the info can be restored on user return
    saveQueryStringInCookie(url);
    //document.location = url;
    redirectSearchControl(url);
}

/// function is called on search button click in accommodation tab
function searchAccommodationClick(searchResultsURL) {
    //var url = "/Accommodation/SearchResults.aspx";
    var url = searchResultsURL;
    if (searchResultsURL.indexOf('?') != -1) {
        url += "&searchTabID=0";
    }
    else {
        url += "?searchTabID=0";
    }

    url += getVariableForQueryString("categoryID", "categoriesSelectAccommodation");
    url += getVariableForQueryString("countryID", "countriesSelectAccommodation");
    url += getVariableForQueryString("regionID", "regionsSelectAccommodation");
    url += getVariableForQueryString("destinationID", "destinationsSelectAccommodation");
    url += getVariableForQueryString("objectTypeID", "objectTypeSelectAccommodation");
    url += getVariableForQueryString("persons", "personsSelectAccommodation");
    url += getVariableForQueryString("numberOfStars", "numberOfStarsSelectAccommodation");
    url += getVariableForQueryString("priceFrom", "priceFromInputAccommodation");
    url += getVariableForQueryString("priceTo", "priceToInputAccommodation");
    url += getVariableForQueryString("balcony", "balconyInputAccommodation");
    url += getVariableForQueryString("priceType", "priceTypeSelectAccommodation");
    url += getVariableForQueryStringAsDateTicks("from", "dateFromAccommodation");
    url += getVariableForQueryStringAsDateTicks("to", "dateToAccommodation");
    url += "&onlyOnSpecialOffer=" + document.getElementById("onlyOnSpecialOfferCheckBox").checked;

    /// set accommodation type group id: 3 = private accommodation, 4 = hotels
    //var accommodationTypeGroupID = "3,4";
    //url += "&objectTypeGroupID=" + accommodationTypeGroupID;
    url += getVariableForQueryString("objectTypeGroupID", "accommodationTypeGroupID");
    url += "&languageID=" + languageIDSetting;
    url += "&currencyID=" + currencyIDFromLanguage(languageIDSetting);

    // Save all info into a cookie so that the info can be restored on user return
    saveQueryStringInCookie(url);

    redirectSearchControl(url);
}


/// function is called on show all package tours button click
function showAllPackageToursClick(searchResultsURL) {

    var fromDate = new Date();
    var fromTicks = GetTicksFromDate(fromDate);
    var toDate = new Date();
    toDate.setDate(toDate.getDate() + 7);
    var toTicks = GetTicksFromDate(toDate);
    /// set accommodation type group id: 3 = private accommodation, 4 = hotels

//    var url = "/Accommodation/PackageTourSearchResults.aspx";
    //    url += "?searchTabID=1";
    var url = searchResultsURL;
    if (searchResultsURL.indexOf('?') != -1) {
        url += "&searchTabID=0";
    }
    else {
        url += "?searchTabID=0";
    }

    var accommodationTypeGroupID = "6";
    url += "&objectTypeGroupID=" + accommodationTypeGroupID;
    url += "&languageID=" + languageIDSetting;
    url += "&currencyID=" + currencyIDFromLanguage(languageIDSetting);

    // Save all info into a cookie so that the info can be restored on user return
    saveQueryStringInCookie(url);
    //    document.location = url;
    redirectSearchControl(url);
}

/// function is called on search button click in package tour tab
function searchPackageTourClick(searchResultsURL) {
    //var url = "/Accommodation/PackageTourSearchResults.aspx";
    //url += "?searchTabID=1";
    var url = searchResultsURL;
    if (searchResultsURL.indexOf('?') != -1) {
        url += "&searchTabID=1";
    }
    else {
        url += "?searchTabID=1";
    }

    url += getVariableForQueryString("categoryID", "categoriesSelectPackageTour");
    url += getVariableForQueryString("countryID", "countriesSelectPackageTour");
    url += getVariableForQueryString("regionID", "regionsSelectPackageTour");
    url += getVariableForQueryString("destinationID", "destinationsSelectPackageTour");
    url += getVariableForQueryString("objectTypeID", "objectTypeSelectPackageTour");
    url += getVariableForQueryString("numberOfStars", "numberOfStarsSelectPackageTour");
    url += getVariableForQueryString("priceFrom", "priceFromInputPackageTour");
    url += getVariableForQueryString("priceTo", "priceToInputPackageTour");
    url += getVariableForQueryString("balcony", "balconyInputPackageTour");
    url += getVariableForQueryString("priceType", "priceTypeSelectPackageTour");
    url += getVariableForQueryStringAsDateTicks("from", "dateFromPackageTour");
    url += getVariableForQueryStringAsDateTicks("to", "dateToPackageTour");
    url += "&onlyOnSpecialOffer=" + document.getElementById("onlyPackageToursOnSpecialOfferCheckBox").checked;

    /// set accommodation type group id: 6 = package tours
    var accommodationTypeGroupID = "6";
    url += "&objectTypeGroupID=" + accommodationTypeGroupID;
    url += "&languageID=" + languageIDSetting;
    url += "&currencyID=" + currencyIDFromLanguage(languageIDSetting);

    // Save all info into a cookie so that the info can be restored on user return
    saveQueryStringInCookie(url);
    //    document.location = url;
    redirectSearchControl(url);
}


/// if 'elementId' exists in DOM returns string "&variableName=elementValue"
///     variableName is name of a variable that will appear in query string
///     elementId id ID of an element to look for in DOM.
function getVariableForQueryString(variableName, elementId) {
    var element = $("#" + elementId);
    if (element != null) {
        var elementValue = element.val();
        if (elementValue != null && elementValue != "") {
            return "&" + variableName + "=" + elementValue;
        }
    }
    return "";
}
/// if elementId exists in DOM returns string "&variableName=ticks"
///     variableName is name of a variable that will appear in query string
///     elementId id ID of an element to look for in DOM. It must contain a date.
function getVariableForQueryStringAsDateTicks(variableName, elementId) {
    var element = $("#" + elementId);
    if (element != null) {
        var elementValue = element.val();
        if (elementValue != null && elementValue != "") {
            var dateValue = element.datepicker("getDate");

            // ticks = number of miliseconds since 01.01.1970.
            var ticks = GetTicksFromDate(dateValue);
            return "&" + variableName + "=" + ticks;
        }
    }
    return "";
}

/// function converts date to ticks
function GetTicksFromDate(dateValue) {
    var ticks = dateValue.getTime() - (dateValue.getTimezoneOffset() * 60 * 1000);
    return ticks;
}

/// function saves all variables from query string in cookie
///     url is string from wich variables from query string will be extracted and saved in cookie
function saveQueryStringInCookie(url) {
    try {
        var querystring = url.substring(url.indexOf('?') + 1);
        var parameters = querystring.split('&');

        var activeUntil = (new Date()).getTime() + 1000 * 60 * 30;
        var activeUntilDate = new Date();
        activeUntilDate.setTime(activeUntil);

        var i;
        for (i = 0; i < parameters.length; i++) {
            document.cookie = parameters[i] + "; expires=" + activeUntilDate.toString() + "; path=/";
        }
    }
    catch (a) {

    }
}

/// function tries to read parameterName from cookie. If it succeddes returns that value, otherwise returns default value.
///     parameterName is name of a variable to look for in a cookie
///     defaultValue if value that will be returned if parameterName is not found in cookie
function tryToReadFromCookie(parameterName, defaultValue) {
    if (document.cookie != null && document.cookie != "") {
        var cookieValues = document.cookie.split(";");

        for (i = 0; i < cookieValues.length; i++) {
            var pair = cookieValues[i].split('=');
            if (pair.length > 1) {
                pair[0] = pair[0].trim();
                pair[1] = pair[1].trim();

                if (pair[0].toLowerCase() == parameterName.toLowerCase()) {
                    return pair[1];
                }
            }
        }
    }
    /// parameterName not found, return default value
    return defaultValue;
}




/*** EVENT HANDLERS ***/

/// function is called on objectTypeChange in accommodation tab to reload the allowed categories, countries, regions and destinations!
function objectTypeOnChangeAccommodation() {
    rebindSearchFieldsInAccommodationTab();
}
/// function is called on categoriesSelectOnChange in accommodation tab to reload the allowed categories, countries, regions and destinations!
function categoriesSelectOnChangeAccommodation() {
    rebindSearchFieldsInAccommodationTab();
}
/// function is called on categoriesSelectOnChange in package tour tab to reload the allowed categories, countries, regions and destinations!
function categoriesSelectOnChangePackageTour() {
    rebindSearchFieldsInPackageTourTab();
}
/// function is called on countriesSelectOnchange in accommodation tab and it hides the appropritate regions and destinations
function countriesSelectOnChangeAccommodation() {
    updateRegionsList(regionsListAccommodation, visibleRegionsIdListAccommodation, "countriesSelectAccommodation", "regionsSelectAccommodation");
    updateDestinationsList(destinationsListAccommodation, visibleRegionsIdListAccommodation, "regionsSelectAccommodation", "destinationsSelectAccommodation");
}
/// function is called on countriesSelectOnchange in package tour tab and it hides the appropritate regions and destinations
function countriesSelectOnChangePackageTour() {
    updateRegionsList(regionsListPackageTour, visibleRegionsIdListPackageTour, "countriesSelectPackageTour", "regionsSelectPackageTour");
    updateDestinationsList(destinationsListPackageTour, visibleRegionsIdListPackageTour, "regionsSelectPackageTour", "destinationsSelectPackageTour");
}
/// function is called on regionsSelectOnChange in accommodation tab and hides the required destinations.
function regionsSelectOnChangeAccommodation() {
    updateDestinationsList(destinationsListAccommodation, visibleRegionsIdListAccommodation, "regionsSelectAccommodation", "destinationsSelectAccommodation");
}
/// function is called on regionsSelectOnChange in package tour tab and hides the required destinations.
function regionsSelectOnChangePackageTour() {
    updateDestinationsList(destinationsListPackageTour, visibleRegionsIdListPackageTour, "regionsSelectPackageTour", "destinationsSelectPackageTour");
}

/// function will read period and packageTourId from periods drop down list and will redirect page to package tour details with these parameters in query string
function redirectToPackageTourDetailWithSelectedPeriod(packageTourID, currencyID, detailsURL) {
    var periodsSelectID = "periodsSelect_" + packageTourID;

    var period = $("#" + periodsSelectID).val();
    var numberOfDays = $("#" + periodsSelectID + " option:selected").attr("numberOfDays");

    var url = detailsURL;
    var prefix = "?";
    if (url.indexOf('?') != '-1') {
        prefix = "&";
    }
    url += prefix + "languageID=" + languageIDSetting + "&packageTourID=" + packageTourID + "&period=" + period + "&tab=reservationsTab";

    if (numberOfDays != undefined && numberOfDays != null) {
        var numberOfNights = numberOfDays - 1;
        url += "&numberOfDays=" + numberOfNights;
    }

    if (currencyID != undefined && currencyID != null && currencyID != "") {
        url += "&currencyID=" + currencyID;
    }

    document.location = url;
}

///function will return currencyID from languageID
function currencyIDFromLanguage(languageID) {
    switch (languageID) {
        case "hr":
            return _CURRENCYIDCROATIAN;
            break;
        default:
            return _CURRENCYIDEU;
            break;
    }
}
