/* Minification failed. Returning unminified contents.
(1936,15-16): run-time error JS1014: Invalid character: `
(1936,16-17): run-time error JS1195: Expected expression: .
(1936,27-30): run-time error JS1004: Expected ';': div
(1936,36-37): run-time error JS1004: Expected ';': {
(1936,47-48): run-time error JS1014: Invalid character: `
(1936,48-49): run-time error JS1195: Expected expression: )
(1940,5-6): run-time error JS1002: Syntax error: }
(1941,34-35): run-time error JS1004: Expected ';': {
(1943,99-100): run-time error JS1014: Invalid character: `
(1943,101-102): run-time error JS1193: Expected ',' or ')': {
(1943,122-123): run-time error JS1195: Expected expression: ,
(1943,145-146): run-time error JS1014: Invalid character: `
(1943,146-147): run-time error JS1195: Expected expression: )
(1947,122-123): run-time error JS1014: Invalid character: `
(1947,124-125): run-time error JS1193: Expected ',' or ')': {
(1947,152-153): run-time error JS1195: Expected expression: ,
(1947,182-183): run-time error JS1014: Invalid character: `
(1947,183-184): run-time error JS1195: Expected expression: )
(1970,1-2): run-time error JS1002: Syntax error: }
(1972,57-58): run-time error JS1004: Expected ';': {
 */
/// Version   : 1.0
/// Created   : 04/03/2016
/// Creator   : VH
/// Updated   : 04/03/2016
/// Update By : VH


function SearchProduct(_$search, _type) {
    this._$search = _$search;
    this._type = _type;
    this._country = null;
    this. _fromPlace; 
    this._fromSubPlace;
    this._toPlace;
    this._toSubPlace;
    this._roundTrip;
    this._departTime;
    this._returnTime;
    this._pax = 0;
    this._company;
    this._locationFrom = [];
    this._locationTo = [];
    this._placesList = [];
    this._subplacesList = [];
    this._mapping = [];
    this._searchMode = 'AdvanceSearchMode';
    this._isAdvanceMode = true;

    this.Initialize = function () {

        //load all data for autocomplete textbox from place
        this.GetAllVisibleRoutes();

        //ddlCountry on change event listener
        this._$search.find("#ddlCountry" + this._type).on("change", $.proxy(function (e) {
            this._$search.find("input[id*='txtFromPlaceBasic']").val('');
            this._$search.find("input[id*='txtFromPlaceBasic']").next("pre").text('');
            this._$search.find("input[id*='txtToPlaceBasic']").val('');
            this._$search.find("input[id*='txtToPlaceBasic']").next("pre").text('');

            this._$search.find("input[id*='hiddenFromPlace']").val(0);
            this._$search.find("input[id*='hiddenFromSubPlace']").val(0);
            this._$search.find("input[id*='hiddenToPlace']").val(0);
            this._$search.find("input[id*='hiddenToSubPlace']").val(0);

            this._country = $(e.target).val();

            this.GetPickUpPoints();
            this.GetPickUpSubPoints();
            this.GetDropOffPoints();
            this.GetDropOffSubPoints();
            //this.GetAllVisibleRoutes();
            
        },this));

        //ddlFromPlace on change event listener
        this._$search.find("#ddlFromPlace" + this._type).on("change", $.proxy(function (e) {
            this.GetPickUpSubPoints();
            this.GetDropOffPoints();
            this.GetDropOffSubPoints();
        },this));

        //ddlFromSubPlace on change event listener

        this._$search.find("#ddlFromSubPlace" + this._type).on("change", $.proxy(function (e) {
            this.GetDropOffPoints();
            this.GetDropOffSubPoints();
        },this));

        //ddlToPlace on change event listener
        this._$search.find("#ddlToPlace" + this._type).on("change", $.proxy(function (e) {
            this.GetDropOffSubPoints();
        },this));

        //One or Two Ways radio button on click event listener
        this._$search.find("#TripType" + this._type).on("click", $.proxy(function (e) {
            if ($(e.target).val() == "1") {
                this._$search.find("[id*='dpDepartureDate']").datepicker("setEndDate", null);
                this._$search.find("[id*='dpReturnDate']").val(''),
                this._$search.find("[id*='dvReturnDate']").hide();
            } else {
                this._$search.find("[id*='dpReturnDate']").datepicker("setStartDate", !this._$search.find("[id*='dpDepartureDate']").val() ? '+0d' : this._$search.find("[id*='dpDepartureDate']").val());
                this._$search.find("[id*='dvReturnDate']").show();
            }
        },this));

        //called in document ready
        //Setup DropDownList, Suggestion-AutoComplete-TextBox, Mode
        this.EnableBloodHound(true);
        this.EnableBloodHound(false);

        var mode = readCookie(this._searchMode);
        if (mode) {
            this._isAdvanceMode = (mode === 'true');
        }
        else {
            createCookie(this._searchMode, this._isAdvanceMode, 60);
        }

        if (this._isAdvanceMode == true) {
            this._$search.find("a[id*='aBasic']").show();
            this._$search.find("div[class*='advance-mode']").show();

            this._$search.find("a[id*='aAdvance']").hide();
            this._$search.find("div[class*='basic-mode']").hide();
        }
        else {
            this._$search.find("a[id*='aAdvance']").show();
            this._$search.find("div[class*='basic-mode']").show();

            this._$search.find("a[id*='aBasic']").hide();
            this._$search.find("div[class*='advance-mode']").hide();
        }

        this._$search.find("input[id*='hiddenSearchMode']").val(this._isAdvanceMode);

        var sp = this;


        // Setup DatePicker
        setupDepartReturnDatePicker(this._$search.find("[id*='dpDepartureDate']"), this._$search.find("[id*='dpReturnDate']"));
     
    };
    
    //ddlToPlace on change event listener
    this._$search.find("#aBasic" + this._type).on("click", $.proxy(function (e) {
        this.SwitchSearchMode(e.target, false);
    },this));

    //ddlToPlace on change event listener
    this._$search.find("#aAdvance" + this._type).on("click", $.proxy(function (e) {
        this.SwitchSearchMode(e.target, true);
    },this));

    ////////////////////Advance Mode Search methods//////////////////
    //Get From Place
    this.GetPickUpPoints = function () {
        if (!this._$search.find("select[id*='ddlCountry']").val()) {
            ResetDropdownList(this._$search.find("select[id*='ddlFromPlace']"), 'Origin');
            return;
        }
        this._country = this._$search.find("select[id*='ddlCountry']").val();

        var sp = this;
        $.getJSON(this._$search.find("input[id*='hdApiPickUp']").val() + "?country=" + this._country, null,
       function (data) {
           ResetDropdownList(sp._$search.find("select[id*='ddlFromPlace']"), 'Origin');
           $.each(data, function (i,obj) {
               sp._$search.find("select[id*='ddlFromPlace']").append($("<option />").val(obj.Id).text(obj.LocalName));
           });
       });
    }

    //Get From Sub Place
    this.GetPickUpSubPoints = function () {
        if (!this._$search.find("select[id*='ddlFromPlace']").val()) {
            ResetDropdownList(this._$search.find("select[id*='ddlFromSubPlace']"), 'Any Origin Sub Location');
            return;
        }

        this._country = this._$search.find("select[id*='ddlCountry']").val();
        this._fromPlace = this._$search.find("select[id*='ddlFromPlace']").val();
        var sp = this;
        $.getJSON(this._$search.find("input[id*='hdApiPickUpSubPlace']").val() + "?country=" + this._country + "&placeId=" + this._fromPlace, null,
            function (data) {
                ResetDropdownList(sp._$search.find("select[id*='ddlFromSubPlace']"), 'Any Origin Sub Location');
                $.each(data, function (i, obj) {
                    sp._$search.find("select[id*='ddlFromSubPlace']").append($("<option />").val(obj.Id).text(obj.SubPlaceLocalName));
                });
            });
    }
    //Get To Place
    this.GetDropOffPoints = function () {
        if (!this._$search.find("select[id*='ddlFromPlace']").val()) {
            ResetDropdownList(this._$search.find("select[id*='ddlToPlace']"), 'Destination');
            return;
        }

        this._country = this._$search.find("select[id*='ddlCountry']").val();
        this._fromPlace = this._$search.find("select[id*='ddlFromPlace']").val();
        this._fromSubPlace = this._$search.find("select[id*='ddlFromSubPlace']").val();
        var sp = this;
        $.getJSON(this._$search.find("input[id*='hdApiDropOff']").val() + "?country=" + this._country + "&fromplaceId=" + this._fromPlace + "&fromSubPlaceId=" + this._fromSubPlace, null,
       function (data) {
           ResetDropdownList(sp._$search.find("select[id*='ddlToPlace']"), 'Destination');
           $.each(data, function (i, obj) {
               sp._$search.find("select[id*='ddlToPlace']").append($("<option />").val(obj.Id).text(obj.LocalName));
           });
       });
    }

    //Get To Sub Place
    this.GetDropOffSubPoints = function () {
        if (!this._$search.find("select[id*='ddlFromPlace']").val() || !this._$search.find("select[id*='ddlToPlace']").val()) {
            ResetDropdownList(this._$search.find("select[id*='ddlToSubPlace']"), 'Any Destination Sub Location');
            return;
        }

        this._country = this._$search.find("select[id*='ddlCountry']").val();
        this._fromPlace = this._$search.find("select[id*='ddlFromPlace']").val();
        this._fromSubPlace = this._$search.find("select[id*='ddlFromSubPlace']").val();
        this._toPlace = this._$search.find("select[id*='ddlToPlace']").val();
        var sp = this;
        $.getJSON(this._$search.find("input[id*='hdApiDropOffSubPlace']").val() + "?country=" + this._country + "&fromplaceId=" + this._fromPlace + "&fromSubPlaceId=" + this._fromSubPlace + "&toPlaceId=" + this._toPlace, null,
       function (data) {
           ResetDropdownList(sp._$search.find("select[id*='ddlToSubPlace']"), 'Any Destination Sub Location');
           $.each(data, function (i, obj) {
               sp._$search.find("select[id*='ddlToSubPlace']").append($("<option />").val(obj.Id).text(obj.SubPlaceLocalName));
           });
       });
    }

    //Reset dropdown list
    function ResetDropdownList(ddl, text) {
        $(ddl).empty();
        $(ddl).append($("<option />").val("").text(text));
    }

    ////////////////////Basic Mode Search methods//////////////////
    //Get all Place
    this.GetAllPlaces = function () {
        //if (!this._country) { return; }

        var sp = this;
        $.getJSON(this._$search.find("input[id*='hdApiBasic']").val() + "?country=" + this._country, null,
        function (data) {
           
           sp._placesList = [];
           //ResetDdlFromPlace();
           $.each(data, function () {
               var obj = {};
               obj.id = this.Id;
               obj.name = this.LName;
               obj.subId = 0;
               sp._placesList.push(obj);
               //_locationFrom.push(obj);
           });

           var result = sp._mapping.map(function (item) {
               return item['FP'];
           });
           result = unique(result);

           sp._placesList.sort(function (a, b) {
               return (a.name > b.name) ? 1 : -1;
           });

           //alert(result + ' - ' + result.length);
           $.each(sp._placesList, function () {
               if (result.indexOf(this.id) >= 0) {
                   sp._locationFrom.push(this);
               }
           });

           //alert(JSON.stringify(_locationFrom));
           //EnableTypeAHead(true);

           sp.fromLocationBloodhound.local = sp._locationFrom;
           sp.fromLocationBloodhound.initialize(true);
           //var autocomplete = $('#txtFromPlaceBasic').typeahead();
           //autocomplete.data('typeahead').source = _locationFrom; //where newSource is your own array
           //$('#txtFromPlaceBasic').typeahead({ source: _locationFrom });

           //EnableTypeAHead(true);
           //_locationFrom.concat(_placesList);
           //alert(JSON.stringify(_locationFrom) + JSON.stringify(_placesList));
       });
    }

    //Get all SubPlace
    this.GetAllSubPlaces = function () {
        //if (!this._country) { return; }
        this._subplacesList = [];
        var sp = this;
        $.getJSON(this._$search.find("input[id*='hdApiBasicSubPlace']").val() + "?country=" + this._country, null,
        function (data) {
            //ResetDdlFromPlace();
            
           $.each(data, function () {
               var obj = {};
               obj.id = this.PlaceId;
               obj.name = this.LName;
               obj.subId = this.Id;
               sp._subplacesList.push(obj);
               //_locationFrom.push(obj);
           });

           var result = sp._mapping.map(function (item) {
               return item['FSP'];
           });

           result = unique(result);

           sp._subplacesList.sort(function (a, b) {
               return (a.name > b.name) ? 1 : -1;
           });

           //alert(sp + ' - ' + result.length);
           $.each(sp._subplacesList, function () {
               if (result.indexOf(this.subId) >= 0) {
                   sp._locationFrom.push(this);
               }
           });

           sp.fromLocationBloodhound.local = sp._locationFrom;
           sp.fromLocationBloodhound.initialize(true);

           //EnableTypeAHead();x
           //alert(JSON.stringify(_subplacesList));
       });
    }

    //Get all visible routes
    this.GetAllVisibleRoutes = function () {
        //if (!this._country) { return; }
        this._mapping = [];

        $.getJSON(this._$search.find("input[id*='hdApiVisible']").val() + "?country=" + this._country, null,
        $.proxy(function (data) {
           this._mapping = data;
           this._locationFrom = [];
           this._locationTo = [];
           this._placesList = [];
           this._subplacesList = [];

           this.GetAllPlaces();
           this.GetAllSubPlaces();
       },this));
    }

    //Handle if js libs failed to load: reload the page
    if (typeof Bloodhound === "undefined" && !window.location.href.includes("reload=1")) {
        window.location = window.location.href + "?reload=1";
    }

    this.fromLocationBloodhound = new Bloodhound({
        datumTokenizer: function (obj) { return Bloodhound.tokenizers.whitespace(obj.name); },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: this._locationFrom, //$.map(_locationFrom, function (state) { return { value: state }; })
        //identify: function (obj) { return obj.id + obj.subId; },
        sorter: $.proxy(function (a, b) {
            //get input text
            var InputString = this._$search.find("input[id*='txtFromPlaceBasic']").val();

            //move exact matches to top
            if (InputString == a.name) { return -1; }
            if (InputString == b.name) { return 1; }

            //close match without case matching
            if (InputString.toLowerCase() == a.name.toLowerCase()) { return -1; }
            if (InputString.toLowerCase() == b.name.toLowerCase()) { return 1; }

            if ((InputString != a.name) && (InputString != b.name)) {
                if (a.name < b.name) {
                    return -1;
                }
                else if (a.name > b.name) {
                    return 1;
                }
                else return 0;
            }
        },this),
    });

    this.toLocationBloodhound = new Bloodhound({
        datumTokenizer: function (obj) { return Bloodhound.tokenizers.whitespace(obj.name); },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        local: this._locationTo,
        sorter: $.proxy(function (a, b) {
            //get input text
            var InputString = this._$search.find("input[id*='txtToPlaceBasic']").val();

            //move exact matches to top
            if (InputString == a.name) { return -1; }
            if (InputString == b.name) { return 1; }

            //close match without case matching
            if (InputString.toLowerCase() == a.name.toLowerCase()) { return -1; }
            if (InputString.toLowerCase() == b.name.toLowerCase()) { return 1; }

            if ((InputString != a.name) && (InputString != b.name)) {
                if (a.name < b.name) {
                    return -1;
                }
                else if (a.name > b.name) {
                    return 1;
                }
                else return 0;
            }
        },this),
    });

    this.EnableBloodHound = function (isFromPlaceSelected) {
        //var bloodHound = isFromPlaceSelected ? fromLocationBloodhound : toLocationBloodhound;
        var id = isFromPlaceSelected ? this._$search.find("input[id*='txtFromPlaceBasic']") : this._$search.find("input[id*='txtToPlaceBasic']");

        var sp = this;
        $(id).typeahead({
            hint: false,
            highlight: true,
            //minLength: 1,
            minLength: 0,
        },
        {
            display: function (str) {
                var locationName = str.name;
                if (str.subId != 0) {
                    $.each(sp._placesList, function (i, place) {

                        if (place.id == str.id) {
                            locationName += ', ' + place.name;
                            return;
                        }
                    });
                }
                return locationName;
            },
            //display: 'name',
            limit: 999,
            source: isFromPlaceSelected ? sp.BloodhoundSearchWithDefaultsFromPlace : sp.BloodhoundSearchWithDefaultsToPlace,
            //templates: {
            //    notFound: ['<div class="tt-suggestion"><strong class="tt-highlight" style="color:red;">No result found.</strong></div>']
            //}
        })
        .on('typeahead:selected', function (object, datum) {
            sp.TypeAHeadSelected(datum, isFromPlaceSelected);
        })
        .on('typeahead:autocompleted', function (object, datum) {
            sp.TypeAHeadSelected(datum, isFromPlaceSelected);
        })
        .on('keypress', function () {
            //alert('1');
            // event not trigger on typeahead:opened typeahead:closed
            sp._$search.find('div.tt-menu').animate({
                scrollTop: 0
            }, 1);
        });
    }

    this.BloodhoundSearchWithDefaultsFromPlace = $.proxy(function (q, sync) {
        if (q === '') {
            sync(this.fromLocationBloodhound.index.all());
        } else {
            this.fromLocationBloodhound.search(q, sync);
        }
    }, this);

    this.BloodhoundSearchWithDefaultsToPlace = $.proxy(function (q, sync) {
        if (q === '') {
            sync(this.toLocationBloodhound.index.all());
        } else {
            this.toLocationBloodhound.search(q, sync);
        }
    }, this);

    this.TypeAHeadSelected = function (datum, isFromPlaceSelected) {
        var placeId = datum.id;
        var subPlaceId = datum.subId;

        if (isFromPlaceSelected) {
            this.FilterLocationAfterSelect(placeId, subPlaceId);

            // Reset ToSubPlace
            this._$search.find("[id*='hiddenFromPlace']").val(placeId);
            this._$search.find("[id*='hiddenFromSubPlace']").val(subPlaceId);

            this._$search.find("input[id*='txtToPlaceBasic']").typeahead('val', '');
            //$('#txtToPlaceBasic').val('');
            //$("#txtToPlaceBasic").next("pre").text('');
        }
        else {
            this._$search.find("[id*='hiddenToPlace']").val(placeId);
            this._$search.find("[id*='hiddenToSubPlace']").val(subPlaceId);
        }

        //console.log(obj);
        //alert(JSON.stringify(_locationTo));
        console.log(JSON.stringify(datum));
    }

    this.FilterLocationAfterSelect = function (fromPlaceId, fromSubPlaceId) {
        var sp = this;
        sp._locationTo = [];
        // Filter ToPlace result
        result = sp._mapping.filter(function (obj) {
            if (fromSubPlaceId == 0)
                return obj.FP == fromPlaceId;
            else
                return obj.FP == fromPlaceId && obj.FSP == fromSubPlaceId;
        })
        .map(function (item) {
            return item['TP'];
        });

        result = unique(result);

        //console.log(JSON.stringify(result));
        $.each(sp._placesList, function () {
            if (result.indexOf(this.id) >= 0) {
                sp._locationTo.push(this);
            }
        });

        //alert(JSON.stringify(_locationTo));

        // Filter ToSubPlace result
        result = sp._mapping.filter(function (obj) {
            if (fromSubPlaceId == 0)
                return obj.FP == fromPlaceId;
            else
                return obj.FP == fromPlaceId && obj.FSP == fromSubPlaceId;
        })
        .map(function (item) {
            return item['TSP'];
        });

        result = unique(result);

        //console.log(JSON.stringify(result));

        $.each(sp._subplacesList, function () {
            if (result.indexOf(this.subId) >= 0) {
                sp._locationTo.push(this);
            }
        });

        //alert(JSON.stringify(_locationTo));

        sp.toLocationBloodhound.local = sp._locationTo;
        sp.toLocationBloodhound.initialize(true);
        //$("#txtToPlaceBasic").data('typeahead').source = _locationTo;
    }

    //////////////////////////////////////////////////////////////

        
    // switch to basic/advance mode
    this.SwitchSearchMode = function (element, mode) {
        if (mode) {
            this._$search.find("a[id*='aBasic']").show();
            this._$search.find("div[class*='advance-mode']").show();

            this._$search.find("a[id*='aAdvance']").hide();
            this._$search.find("div[class*='basic-mode']").hide();
        }
        else {
            this._$search.find("a[id*='aAdvance']").show();
            this._$search.find("div[class*='basic-mode']").show();

            this._$search.find("a[id*='aBasic']").hide();
            this._$search.find("div[class*='advance-mode']").hide();
        }

        createCookie(this._searchMode, mode, 60);
        this._$search.find("input[id*='hiddenSearchMode']").val(mode);
    }

    // get unique list
    function unique(array) {
        return $.grep(array, function (el, index) {
            return index === $.inArray(el, array);
        });
    }

    // #### not using ####
    // Enable TypeAHead
    this.EnableTypeAHead = function (isFromPlaceSelected) {
        //states = new Bloodhound({
        //    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
        //    queryTokenizer: Bloodhound.tokenizers.whitespace,
        //    //local: _placesList, //[{ id: 1, name: 'dog' }, { id: 2, name: 'pig' }], //
        //    identify: function (obj) { return obj.name; },
        //    prefetch: _placesList
        //});

        var location = isFromPlaceSelected ? this._locationFrom : this._locationTo;
        var id = isFromPlaceSelected ? this._$search.find("input[id*='txtFromPlaceBasic']") : this._$search.find("input[id*='txtToPlaceBasic']");

        $(id).typeahead({
            hint: false,
            highlight: true,
            minLength: 1,
            // Override default css classes, e.g. default is tt-input for ez-tt-input.
            //classNames: {
            //    input: 'ez-tt-input', hint: 'ez-tt-hint',
            //    menu: 'ez-tt-menu', suggestion: 'ez-tt-suggestion',
            //    cursor: 'ez-tt-cursor', highlight: 'ez-tt-highlight'
            //}
        },
        {
            name: 'name',
            limit: 10,
            display: 'name',
            source: substringMatcher(location),
            templates: {
                notFound: ['<div class="tt-suggestion"><strong class="tt-highlight" style="color:red;">No result found.</strong></div>']
            }
        })
        .on('typeahead:selected', function (obj, suggestion) {
            var placeId = 0;
            var subPlaceId = 0;

            // Remove place from subplace
            if (suggestion.indexOf(", ") >= 0)
                suggestion = suggestion.substring(0, suggestion.lastIndexOf(", "));

            // Get place & subplace id
            $.each(location, function (i, str) {
                if (suggestion == str.name) {
                    placeId = str.id;
                    subPlaceId = str.subId;
                }
            });

            //alert(JSON.stringify(_placesList));

            if (isFromPlaceSelected) {
                this.FilterLocationAfterSelect(placeId, subPlaceId);

                // Reset ToSubPlace
                this._$search.find("input[id*='txtToPlaceBasic']").val('');
                this._$search.find("input[id*='txtToPlaceBasic']").next("pre").text('');
                this._$search.find("[id*='hiddenFromPlace']").val(placeId);
                this._$search.find("[id*='hiddenFromSubPlace']").val(subPlaceId);
            }
            else {
                this._$search.find("[id*='hiddenToPlace']").val(placeId);
                this._$search.find("[id*='hiddenToSubPlace']").val(subPlaceId);
            }

            //console.log(obj);
            //alert(JSON.stringify(_locationTo));
            console.log(suggestion + ' ' + placeId + ' ' + subPlaceId);
        });
    }

    // TypeAHead Matching function
    var substringMatcher = function (strs) {
        return function findMatches(q, cb) {
            var matches, substringRegex;
            var sp = this;
            // An array that will be populated with substring matches.
            matches = [];

            // Regex used to determine if a string contains the substring `q`.
            substrRegex = new RegExp(q, 'i');
            var locationName = '';

            // Iterate through the pool of strings and for any string that
            // contains the substring `q`, add it to the `matches` array.
            $.each(strs, function (i, str) {
                if (substrRegex.test(str.name)) {
                    locationName = str.name;
                    if (str.subId != 0) {
                        $.each(sp._placesList, function (i, place) {

                            if (place.id == str.id) {
                                locationName += ', ' + place.name;
                                return;
                            }
                        });
                    }
                    matches.push(locationName);
                }
            });

            cb(matches);
        };
    };

    //One or Two Ways radio button on click event listener
    this._$search.find("[id*='rbtnTripType']").on("click", $.proxy(function (e) {
        if ($(e.target).val() == "1") {
            //this._$search.find("[id*='dpDepartureDate']").datepicker("setEndDate", null);
            this._$search.find("[id*='dpReturnDate']").val(''),
            this._$search.find("[id*='dvReturnDate']").hide();
        } else {
            //this._$search.find("[id*='dpReturnDate']").datepicker("setStartDate", !this._$search.find("[id*='dpDepartureDate']").val() ? '+0d' : this._$search.find("[id*='dpDepartureDate']").val());
            this._$search.find("[id*='dvReturnDate']").show();
        }
    }, this));

};;
$(document).ready(function () {
    var bus = 'Bus';
    var ferry = 'Ferry';
    var train = 'Train';
    var busdaypass = 'BusDayPass';
    var trainluxury = 'TrainLuxury';
    var ferryDarmawisataPelni = 'ferrydarmawisatapelni';
    var flight = 'Flight';
    var trainroundtripcharter = 'TrainRoundTripCharter';
    const isCwForm = $('input[name="CwSelectedRoute"]').length !== 0;
    var defaultDepartLocation = (typeof cttLocation === 'undefined' ? null : cttLocation);
    var defaultArrivalLocation = (typeof cttArrivalLocation === 'undefined' ? null : cttArrivalLocation);
    InitProductSearchPanel(1, bus, defaultDepartLocation);
    InitProductSearchPanel(2, ferry, defaultDepartLocation, defaultArrivalLocation);
    InitProductSearchPanel(5, train);
    InitProductSearchPanel(1056, ferryDarmawisataPelni);  
    InitDayPassSearchPanel(9, busdaypass);
    InitDayPassSearchPanel(11, flight);
    InitProductSearchPanel(13, trainluxury);
    InitProductSearchPanel(17, trainroundtripcharter);
    //InitTrainLuxurySearchPanel(13, trainluxury);        

    ResetLocationError(bus, ferry, train);
    $("div[id^='fromPlaceDropdown'] .place[data-placeid='422'], div[id^='fromPlaceDropdown'] .place[data-placeid='428']").addClass("bold");

    if ($('#SearchMode').length > 0 && $('#SearchMode').val() === "1") {
        ////this for agent site
        AdvancedSearchMode(bus);
    }
    // CW change to reduce server process
    if (isCwForm) {
        if ($('input[name="CwSelectedRoute"]:checked').val() === "1") {
            $("#hdnFSP_Bus").val(536); $("#hdnTSP_Bus").val(32);
            $("#hdnFSPU_Bus").val("queenstreetbusterminal"); $("#hdnTSPU_Bus").val("johorbahrujblarkinterm");
            $("#hdnFPU_Bus").val("singapore"); $("#hdnTPU_Bus").val("johor");
            $("#hdnOrigin_Bus").val("Queen Street Bus Terminal, Singapore"); $("#hdnDestination_Bus").val("Johor Bahru (JB Larkin Term.), Johor");
            $("#hdnFP_Bus").val(4); $("#hdnTP_Bus").val(7);
            $("#hdnFC_Bus").val(1); $("#hdnTC_Bus").val(2);
        }
        else {
            $("#hdnTSP_Bus").val(536); $("#hdnFSP_Bus").val(32);
            $("#hdnTSPU_Bus").val("queenstreetbusterminal"); $("#hdnFSPU_Bus").val("johorbahrujblarkinterm");
            $("#hdnTPU_Bus").val("singapore"); $("#hdnFPU_Bus").val("johor"); 
            $("#hdnDestination_Bus").val("Queen Street Bus Terminal, Singapore"); $("#hdnOrigin_Bus").val("Johor Bahru (JB Larkin Term.), Johor");
            $("#hdnTP_Bus").val(4); $("#hdnFP_Bus").val(7);
            $("#hdnTC_Bus").val(1); $("#hdnFC_Bus").val(2);
        }
        $('input[name="CwSelectedRoute"]').change(function () {            
            if (this.value === "1") {
                $("#hdnFSP_Bus").val(536); $("#hdnTSP_Bus").val(32);
                $("#hdnFSPU_Bus").val("queenstreetbusterminal"); $("#hdnTSPU_Bus").val("johorbahrujblarkinterm");
                $("#hdnFPU_Bus").val("singapore"); $("#hdnTPU_Bus").val("johor");
                $("#hdnOrigin_Bus").val("Queen Street Bus Terminal, Singapore"); $("#hdnDestination_Bus").val("Johor Bahru (JB Larkin Term.), Johor");
                $("#hdnFP_Bus").val(4); $("#hdnTP_Bus").val(7);
                $("#hdnFC_Bus").val(1); $("#hdnTC_Bus").val(2);
            }
            else {
                $("#hdnTSP_Bus").val(536); $("#hdnFSP_Bus").val(32);
                $("#hdnTSPU_Bus").val("queenstreetbusterminal"); $("#hdnFSPU_Bus").val("johorbahrujblarkinterm");
                $("#hdnTPU_Bus").val("singapore"); $("#hdnFPU_Bus").val("johor");
                $("#hdnDestination_Bus").val("Queen Street Bus Terminal, Singapore"); $("#hdnOrigin_Bus").val("Johor Bahru (JB Larkin Term.), Johor");
                $("#hdnTP_Bus").val(4); $("#hdnFP_Bus").val(7);
                $("#hdnTC_Bus").val(1); $("#hdnFC_Bus").val(2);
            }
        });
    }
});

function InitProductSearchPanel(productId, productType, defaultLocation, defaultArrivalLocation) {
    _isAdvancedMode = false;
    _isRoundTrip = true;
    const isCwForm = $('input[name="CwSelectedRoute"]').length !== 0;
    const isPangkorFerry = $('#hdnPangkorFerryFPN').length !== 0 && productType === 'Ferry';
    const isSungaiPetani = $('#hdnSungaiPetaniFPN').length !== 0 && productType === 'Bus';
    const isCTTTerminalPurabaya = $('#hdnCTTTerminalPurabayaFPN').length !== 0 && productType === 'Bus';
    const isKioskThaiNguyen = $('#hdnKioskThaiNguyenFPN').length !== 0 && productType === 'Bus';
    //#region Setting up Basic/Advanced search toggle
    if (_isAdvancedMode == true) {
        $('#aBasic_' + productType).show();
        $('#originAdvancedMode_' + productType).show();
        $('#destinationAdvancedMode_' + productType).show();

        $('#aAdvanced_' + productType).hide();
        $('#originBasicMode_' + productType).hide();
        $('#destinationBasicMode_' + productType).hide();
        $('.' + productType + '.swap').addClass('advanced-mode');
    }
    else {
        $('#aAdvanced_' + productType).show();
        $('#originBasicMode_' + productType).show();
        $('#destinationBasicMode_' + productType).show();

        $('#aBasic_' + productType).hide();
        $('#originAdvancedMode_' + productType).hide();
        $('#destinationAdvancedMode_' + productType).hide();
        $('.' + productType + '.swap').removeClass('advanced-mode');
    }

    //Day Pass feature
    if (productType == 'Bus') {
        $('#busdaypass-search-form').hide();
    }
    if (productType == 'Train') {
        $('#trainluxury-search-panel-box-div').hide();
        $('#trainroundtripcharter-search-panel-box-div').hide();
    }
    if (productType == 'ferrydarmawisatapelni') {
        $('#ferrydarmawisatapelni-search-option-div').hide();
    }
    $('#aBasic_' + productType).click(function () {

       
        $('#aAdvanced_' + productType).show();
        $('#originBasicMode_' + productType).show();
        $('#destinationBasicMode_' + productType).show();

        $('#aBasic_' + productType).hide();
        $('#originAdvancedMode_' + productType).hide();
        $('#destinationAdvancedMode_' + productType).hide();

        var fromCountryId = parseInt($('#originBasicMode_' + productType).attr('data-countryid'));
        var fromPlaceId = parseInt($('#originBasicMode_' + productType).attr('data-placeid'));
        var fromSubPlaceId = parseInt($('#originBasicMode_' + productType).attr('data-subplaceid'));
        var toCountryId = parseInt($('#destinationBasicMode_' + productType).attr('data-countryid'));
        var toPlaceId = parseInt($('#destinationBasicMode_' + productType).attr('data-placeid'));
        var toSubPlaceId = parseInt($('#originBasicMode_' + productType).attr('data-subplaceid'));

        var origin = $('#txtSearchOrigin_' + productType).val();
        var destination = $('#txtSearchDestination_' + productType).val();
        if (fromCountryId != 0)
            $('#hdnOrigin_' + productType).val(origin);
        else
            $('#hdnOrigin_' + productType).val('');

        if (toCountryId != 0)
            $('#hdnDestination_' + productType).val(destination);
        else
            $('#hdnDestination_' + productType).val('');

        $('#hdnFC_' + productType).val(fromCountryId);
        $('#hdnFP_' + productType).val(fromPlaceId);
        $('#hdnFSP_' + productType).val(fromSubPlaceId);
        $('#hdnTC_' + productType).val(toCountryId);
        $('#hdnTP_' + productType).val(toPlaceId);
        $('#hdnTSP_' + productType).val(toSubPlaceId);

        //$('.country-avail > .swap').removeClass('advanced-mode');
        $('.' + productType + '.swap').removeClass('advanced-mode');
        $('#locationError_' + productType).text('');
        _isAdvancedMode = false;
    });

    $('#aAdvanced_' + productType).click(function () {
        AdvancedSearchMode(productType);
    });


    //#endregion

    //#region Setting up Basic search (Typeahead Bloodhound plugin)
    var sp_fpBloodhound = new Bloodhound({
        datumTokenizer: function (datum) {
            return Bloodhound.tokenizers.whitespace(datum.value);
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: "/api/place?productId=#PROD&query=#QUERY",
            filter: function (response) {
                $('#txtSearchOrigin_' + productType).parent().siblings('.loading-spinner').hide();
                return response;
            },
            replace: function (url, query) {
                $('#txtSearchOrigin_' + productType).parent().siblings('.loading-spinner').show();
                url = url.replace("#PROD", encodeURIComponent(productId));

                if (isPangkorFerry) {
                    var fromPlaceName = $('#hdnPangkorFerryFPN').val();
                    if (query == '') {
                        url = url.replace("#QUERY", encodeURIComponent(fromPlaceName));
                    } else {
                        url = url.replace("#QUERY", encodeURIComponent(query));
                    }
                } else if (isSungaiPetani) {
                    var fromPlaceName = $('#hdnSungaiPetaniFPN').val();
                    if (query == '') {
                        url = url.replace("#QUERY", encodeURIComponent(fromPlaceName));
                    } else {
                        url = url.replace("#QUERY", encodeURIComponent(query));
                    }
                } else if (isCTTTerminalPurabaya) {
                    var fromPlaceName = $('#hdnCTTTerminalPurabayaFPN').val();
                    url = url.replace("#QUERY", encodeURIComponent(fromPlaceName));
                } else if (isKioskThaiNguyen) {
                    var fromPlaceName = $('#hdnKioskThaiNguyenFPN').val();
                    if(query == '') {
                        url = url.replace("#QUERY", encodeURIComponent(fromPlaceName));
                    } else {
                        url = url.replace("#QUERY", encodeURIComponent(query));
                    }
                } else {
                    url = url.replace("#QUERY", encodeURIComponent(query));
                }

                return url;
            },
            cache: false,
            ajax: {
                error: function (jqXHR) {
                    $('#txtSearchOrigin_' + productType).parent().siblings('.loading-spinner').hide();
                    engine.clear();
                }
            }
        },
        sorter: function (a, b) {
            //get input text
            var InputString = $(Selector).val();

            //move exact matches to top
            if (InputString == a.value) { return -1; }
            if (InputString == b.value) { return 1; }

            //close match without case matching
            if (InputString.toLowerCase() == a.value.toLowerCase()) { return -1; }
            if (InputString.toLowerCase() == b.value.toLowerCase()) { return 1; }

            if ((InputString != a.value) && (InputString != b.value)) {

                if (a.value < b.value) {
                    return -1;
                }
                else if (a.value > b.value) {
                    return 1;
                }
                else return 0;
            }
        }
    });

    var sp_tpBloodhound = new Bloodhound({
        datumTokenizer: function (datum) {
            return Bloodhound.tokenizers.whitespace(datum.value);
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        remote: {
            url: "/api/place?productId=#PROD&query=#QUERY&fromCountryId=#FROM_C&fromPlaceId=#FROM_P&fromSubPlaceId=#FROM_SP",
            filter: function (response) {
                $('#txtSearchDestination_' + productType).parent().siblings('.loading-spinner').hide();
                return response;
            },
            replace: function (url, query) {
                $('#txtSearchDestination_' + productType).parent().siblings('.loading-spinner').show();

                var strCurrentCountryID = $('#hdnFC_' + productType).val();
                var intCurrentPlaceID = $('#hdnFP_' + productType).val();
                var intCurrentSubPlaceID = $('#hdnFSP_' + productType).val();

                url = url.replace("#PROD", encodeURIComponent(productId))
                        .replace("#QUERY", encodeURIComponent(query))
                        .replace("#FROM_C", encodeURIComponent(strCurrentCountryID))
                        .replace("#FROM_P", encodeURIComponent(intCurrentPlaceID))
                        .replace("#FROM_SP", encodeURIComponent(intCurrentSubPlaceID));
                return url;
            },
            cache: false,
            ajax: {
                error: function (jqXHR) {
                    $('#txtSearchDestination_' + productType).parent().siblings('.loading-spinner').hide();
                    engine.clear();
                }
            }
        },
        sorter: function (a, b) {
            //get input text
            var InputString = $(Selector).val();

            //move exact matches to top
            if (InputString == a.value) { return -1; }
            if (InputString == b.value) { return 1; }

            //close match without case matching
            if (InputString.toLowerCase() == a.value.toLowerCase()) { return -1; }
            if (InputString.toLowerCase() == b.value.toLowerCase()) { return 1; }

            if ((InputString != a.value) && (InputString != b.value)) {

                if (a.value < b.value) {
                    return -1;
                }
                else if (a.value > b.value) {
                    return 1;
                }
                else return 0;
            }
        }
    });

    sp_fpBloodhound.initialize();
    sp_tpBloodhound.initialize();

    InitSearchOriginTypeahead();
    InitSearchDestinationTypeahead();

    function InitSearchOriginTypeahead() {
        // debugger;
        // var vMsg = "Product Type : " + productType + "\n" + "Product ID : " + productId + "\n";
        // alert(vMsg);
        $('#txtSearchOrigin_' + productType)
            .typeahead(
            {
                hint: false,
                highlight: true,
                minLength: 0,
                autoselect: true
            },
            {
                name: 'fromPlace',
                limit: 999,
                displayKey: function (place) {
                    if (place == null)
                        return 'Place not found!';
                    if (place.spid == 0)
                        return place.pn;
                    else
                        return place.spn + ", " + place.pn;
                },
                source: sp_fpBloodhound.ttAdapter(),
                templates: {
                    suggestion: function (place) {
                        if (place.spid == 0)
                            return '<div data-placename="' + place.pn.toLowerCase() + '" class="tt-place"><i class="icon-map-pin"></i><div class="tt-suggestion-optionval with-icon"><span class="place-name">' + place.pn + ',</span><span class="country-name"> ' + place.ctn + '</span>' + ((place.ip == true) ? '<span class="badge tt-popular">' + JsCommonLabel.SearchIntellisense_Suggestion_Label_Popular + '</span>' : '') + '</div></div>';
                        else
                            return '<div data-placename="' + place.spn.toLowerCase() + ", " + place.pn.toLowerCase() + '" class="tt-subplace"><i class="fa fa-map-marker"></i><div class="tt-suggestion-optionval with-icon"><span class="place-name">' + place.spn + ", " + place.pn + ',</span><span class="country-name"> ' + place.ctn + '</span>' + ((place.ip == true) ? '<span class="badge tt-popular">' + JsCommonLabel.SearchIntellisense_Suggestion_Label_Popular + '</span>' : '') + '</div></div>';
                    }
                }
            }
        )
            .bind('typeahead:select', function (object, datum) {
            searchPanelSetLocation(datum);
            InitSearchDestinationTypeahead();

            $('#txtSearchDestination_' + productType).focus();
        })
        .on('keypress', function (e) {
            if (e.which == 13) {
                if ($(this).siblings('.tt-menu').find('.tt-suggestion').length)
                    $(this).siblings('.tt-menu').find('.tt-suggestion:first-child').trigger('click');
                e.preventDefault();
            }
        })
        .on('blur', function (e) {
            var query = $(this).val().toLowerCase();
            if (!$(this).siblings('.tt-menu').find('.tt-suggestion[data-placename="' + query + '"]').length)
                $(this).siblings('.tt-menu').find('.tt-suggestion:first-child').trigger('click');
            else if ($(this).siblings('.tt-menu').find('.tt-suggestion:first-child[data-placename]').data('placename') === query)
                $(this).siblings('.tt-menu').find('.tt-suggestion:first-child').trigger('click');
            e.preventDefault();
        })
        .on('click', function () {
            $(this).select();
        })
        .on('focus', function () {
            if ($("#hdfIsTnGApp").length)
            {
                $([document.documentElement, document.body]).animate({
                    scrollTop: $("#from-title-label-" + productType).offset().top
                }, 500);
            }
        });
    }

    function InitSearchDestinationTypeahead() {
        $('#txtSearchDestination_' + productType).typeahead(
            {
                hint: false,
                highlight: true,
                minLength: 0,
                autoselect: true
            },
            {
                name: 'toPlace',
                limit: 999,
                displayKey: function (place) {
                    if (place == null)
                        return 'Place not found!';
                    if (place.spid == 0)
                        return place.pn;
                    else
                        return place.spn + ", " + place.pn;
                },
                source: sp_tpBloodhound.ttAdapter(),
                templates: {
                    suggestion: function (place) {
                        if (place.spid == 0)
                            return '<div data-placename="' + place.pn.toLowerCase() + '" class="tt-place"><i class="icon-map-pin"></i><div class="tt-suggestion-optionval with-icon"><span class="place-name">' + place.pn + ',</span><span class="country-name"> ' + place.ctn + '</span>' + ((place.ip == true) ? '<span class="badge tt-popular">' + JsCommonLabel.SearchIntellisense_Suggestion_Label_Popular + '</span>' : '') + '</div></div>';
                        else
                            return '<div data-placename="' + place.spn.toLowerCase() + ", " + place.pn.toLowerCase() + '" class="tt-subplace"><i class="fa fa-map-marker"></i><div class="tt-suggestion-optionval with-icon"><span class="place-name">' + place.spn + ", " + place.pn + ',</span><span class="country-name"> ' + place.ctn + '</span>' + ((place.ip == true) ? '<span class="badge tt-popular">' + JsCommonLabel.SearchIntellisense_Suggestion_Label_Popular + '</span>' : '') + '</div></div>';
                    }
                }
            }
        )
        .on('typeahead:select', function (object, datum) {
            var placenNameDisplay = "";
            if (datum.spid == 0)
                placenNameDisplay = datum.pn;
            else
                placenNameDisplay = datum.spn + ", " + datum.pn;
            $('#hdnDestination_' + productType).val(placenNameDisplay);

            $('#hdnTC_' + productType).val(datum.ctid);
            $('#hdnTP_' + productType).val(datum.pid);
            $('#hdnTSP_' + productType).val(datum.spid);
            $('#hdnTPU_' + productType).val(datum.pusn);
            $('#hdnTSPU_' + productType).val(datum.spusn);

            $('#destinationBasicMode_' + productType).attr('data-countryid', datum.ctid);
            $('#destinationBasicMode_' + productType).attr('data-placeid', datum.pid);
            $('#destinationBasicMode_' + productType).attr('data-subplaceid', datum.spid);

            $('#txtSearchDestination_' + productType).removeClass('is-error');
            $('#txtSearchDestination_' + productType).attr('title', $('#hdnDestination_' + productType).val());

            //$('#hdnTC_' + productType).change();
        })
        .on('keypress', function (e) {
            if (e.which == 13) {
                if ($(this).siblings('.tt-menu').find('.tt-suggestion').length)
                    $(this).siblings('.tt-menu').find('.tt-suggestion:first-child').trigger('click');
                e.preventDefault();
            }
        })
        .on('blur', function (e) {
            var query = $(this).val().toLowerCase();
            if (!$(this).siblings('.tt-menu').find('.tt-suggestion[data-placename="' + query + '"]').length)
                $(this).siblings('.tt-menu').find('.tt-suggestion:first-child').trigger('click');
            else if ($(this).siblings('.tt-menu').find('.tt-suggestion:first-child[data-placename]').data('placename') === query)
                $(this).siblings('.tt-menu').find('.tt-suggestion:first-child').trigger('click');
            e.preventDefault();
        })
        .on('click', function () {
            $(this).select();
        })
        .on('focus', function () {
            if ($("#hdfIsTnGApp").length) {
                $([document.documentElement, document.body]).animate({
                    scrollTop: $("#to-title-label-" + productType).offset().top
                }, 500);
            }
        });
    }    
    function searchPanelSetLocation(datum) {
        var placenNameDisplay = "";
        if (datum.spid == 0)
            placenNameDisplay = datum.pn;
        else
            placenNameDisplay = datum.spn + ", " + datum.pn;

        $('#hdnOrigin_' + productType).val(placenNameDisplay);
        $('#hdnDestination_' + productType).val('');
        $('#txtSearchDestination_' + productType).typeahead('val', '');

        $('#hdnTC_' + productType).val('0');
        $('#hdnTP_' + productType).val('0');
        $('#hdnTSP_' + productType).val('0');

        $('#hdnFC_' + productType).val(datum.ctid);
        $('#hdnFP_' + productType).val(datum.pid);
        $('#hdnFSP_' + productType).val(datum.spid);
        $('#hdnFPU_' + productType).val(datum.pusn);
        $('#hdnFSPU_' + productType).val(datum.spusn);

        $('#originBasicMode_' + productType).attr('data-countryid', datum.ctid);
        $('#originBasicMode_' + productType).attr('data-placeid', datum.pid);
        $('#originBasicMode_' + productType).attr('data-subplaceid', datum.spid);
        $('#destinationBasicMode_' + productType).attr('data-countryid', 0);
        $('#destinationBasicMode_' + productType).attr('data-placeid', 0);
        $('#destinationBasicMode_' + productType).attr('data-subplaceid', 0);

        $('#txtSearchOrigin_' + productType).removeClass('is-error');
        $('#txtSearchOrigin_' + productType).attr('title', $('#hdnOrigin_' + productType).val());

        $('#txtSearchDestination_' + productType).typeahead('destroy');
        sp_tpBloodhound.clear();
        sp_tpBloodhound.initialize();
    }
    //#endregion
    function searchPanelSetArrivalLocation(datum) {
        var placenNameDisplay = "";
        if (datum.spid == 0)
            placenNameDisplay = datum.pn;
        else
            placenNameDisplay = datum.spn + ", " + datum.pn;
        $('#hdnDestination_' + productType).val(placenNameDisplay);

        $('#hdnTC_' + productType).val(datum.ctid);
        $('#hdnTP_' + productType).val(datum.pid);
        $('#hdnTSP_' + productType).val(datum.spid);
        $('#hdnTPU_' + productType).val(datum.pusn);
        $('#hdnTSPU_' + productType).val(datum.spusn);

        $('#destinationBasicMode_' + productType).attr('data-countryid', datum.ctid);
        $('#destinationBasicMode_' + productType).attr('data-placeid', datum.pid);
        $('#destinationBasicMode_' + productType).attr('data-subplaceid', datum.spid);

        $('#txtSearchDestination_' + productType).removeClass('is-error');
        $('#txtSearchDestination_' + productType).attr('title', $('#hdnDestination_' + productType).val());
    }
    //#region Setting up Datepicker
    $('#dpDepartureDate_' + productType).datepicker().on('changeDate', function (selected) {

        $('#dpReturnDate_' + productType).val('');
        $('#dpDepartureDate_' + productType).removeClass('is-error');
        $('#dpReturnDate_' + productType).datepicker("setStartDate", !$('#dpDepartureDate_' + productType).val() ? '+0d' : $('#dpDepartureDate_' + productType).val());
    }).on('clearDate', function (selected) {
        $('#dpReturnDate_' + productType).datepicker('setStartDate', null);
    });

    $('#dpReturnDate_' + productType).datepicker().on('changeDate', function (selected) {
        $('#dpReturnDate_' + productType).removeClass('is-error');
    })

    //when page is ready, set the return start date    
    $('#dpReturnDate_' + productType).datepicker("setStartDate", !$('#dpDepartureDate_' + productType).val() ? '+0d' : $('#dpDepartureDate_' + productType).val());

    //if (productType === 'TrainLuxury') {
    //    $('#hdnTC_TrainLuxury').change(function (event) {
    //        var params = { FromPlaceID: 1, FromSubPlaceID: 2, ToPlaceID: 3, ToSubPlaceID: 4 };

    //        $.ajax({                
    //            url: "trainluxury/getavailabledates",
    //            data: params,
    //            beforeSend: function () {
    //                //show spinner
    //                $('#dpDepartureDate_' + productType).parent().siblings('.loading-spinner').show();
    //            },
    //            success: function (result) {
    //                var x = [];
    //                x = result;
    //                $('#dpDepartureDate_' + productType).parent().siblings('.loading-spinner').hide();
    //                $('#dpDepartureDate_TrainLuxury').datepicker('setDatesDisabled', result);
    //                var gg = null;
    //            },
    //            error: function (err) {
    //                console.log(err);
    //                $('#dpDepartureDate_' + productType).parent().siblings('.loading-spinner').hide();
    //            }
    //        });
    //    });        
    //}

    //#endregion

    //#region Setting up Trip type selector
    $('input:radio[data-product=' + productType + ']').click(function () {
      
        if ($(this).val() === "1") {
            $('#dpDepartureDate_' + productType).datepicker("setEndDate", null);
            $('#dpReturnDate_' + productType).val(''),
            $('#dvReturnDate_' + productType).hide();
            $('#busdaypass-search-form').hide();
            $('#trainluxury-search-panel-box-div').hide();
            $('#trainroundtripcharter-search-panel-box-div').hide();
            $('#ferrydarmawisatapelni-search-panel-box-div').hide();
            $('#ferrydarmawisatapelni-search-option-div').hide();
            $('#' + productType + '-search-panel-box-div').show();
            $('#' + productType + '-location-error-div').show();
            $('#' + productType + '-search-option-div').show();
            _isRoundTrip = false;
        } else if ($(this).val() === "DayPass") {
            $('#busdaypass-search-form').show();
            $('#' + productType + '-search-panel-box-div').hide();
            $('#' + productType + '-location-error-div').hide();
            $('#' + productType + '-search-option-div').hide();         
        } else if ($(this).val() === "TrainLuxury") {
            $('#trainluxury-search-panel-box-div').show();
            $('#' + productType + '-search-panel-box-div').hide();
            $('#' + productType + '-location-error-div').hide();
            $('#' + productType + '-search-option-div').hide();
            $('#trainroundtripcharter-search-panel-box-div').hide();
            //$('#hdnSubProductType_' + productType).val('TrainLuxury');
            _isRoundTrip = false;            
        } else if ($(this).val() === "TrainRoundTripCharter") {
            $('#trainroundtripcharter-search-panel-box-div').show();
            $('#trainluxury-search-panel-box-div').hide();
            $('#' + productType + '-search-panel-box-div').hide();
            $('#' + productType + '-location-error-div').hide();
            $('#' + productType + '-search-option-div').hide();            
        } else if ($(this).val() === "DarmawisataPelni") {
            $('#ferrydarmawisatapelni-search-panel-box-div').show();
            $('#' + productType + '-search-panel-box-div').hide();
            $('#' + productType + '-location-error-div').hide();
            $('#' + productType + '-search-option-div').hide();
            $('#ferrydarmawisatapelni-search-option-div').show();
        }
        else {
            $('#dpReturnDate_' + productType).datepicker("setStartDate", !$('#dpDepartureDate_' + productType).val() ? '+0d' : $('#dpDepartureDate_' + productType).val());
            $('#dvReturnDate_' + productType).show();
            $('#' + productType + '-search-panel-box-div').show();
            $('#' + productType + '-location-error-div').show();
            $('#' + productType + '-search-option-div').show();
            $('#busdaypass-search-form').hide();
            $('#trainluxury-search-panel-box-div').hide();
            $('#trainroundtripcharter-search-panel-box-div').hide();
            $('#ferrydarmawisatapelni-search-panel-box-div').hide();
            $('#ferrydarmawisatapelni-search-option-div').hide();
            _isRoundTrip = true;
        }
    });
    //#endregion

    //#region Setting up Advanced Search
    $(document).on('click', '#fromPlaceDropdown_' + productType + ' .place', function () {
        var countryId = $(this).attr('data-countryid');
        var placeId = $(this).attr('data-placeid');
        var countryName = $(this).attr('data-countryname');
        var placeName = $(this).attr('data-placename');
        var defaultcountryName = $(this).attr('default-countryname');
        var defaultplaceName = $(this).attr('default-placename');
        var uniquePlaceName = $(this).attr('data-uniqueplacename');
        var uniqueSubPlaceName = $(this).attr('data-uniquesubplacename');

        if (parseInt($('#hdnFC_' + productType).val()) != countryId ||
            parseInt($('#hdnFP_' + productType).val()) != placeId) {
            $('#selectedFromPlace_' + productType).html(placeName + ', ' + countryName);
            $('#selectedFromPlace_' + productType).attr('title', placeName + ', ' + countryName);

            $('#originAdvancedMode_' + productType).attr('data-countryid', countryId);
            $('#originAdvancedMode_' + productType).attr('data-placeid', placeId);

            $('#selectedFromPlace_' + productType).parent().removeClass('is-error');

            $('#hdnOrigin_' + productType).val(defaultplaceName + ', ' + defaultcountryName);
            $('#hdnFC_' + productType).val(countryId);
            $('#hdnFP_' + productType).val(placeId);
            $('#hdnFPU_' + productType).val(uniquePlaceName);

            PrepareFromSubPlaceSelector(productId, productType);
            //PrepareToPlaceSelector(productId, productType);
            //PrepareToSubPlaceSelector(productId, productType);
        }

        if (productType.toLowerCase() == 'train') {
            var indoMaxDepartureDate = new Date();
            indoMaxDepartureDate.setDate(indoMaxDepartureDate.getDate() + 90);
            if (countryId == "90") {
                $('#ddlPax_Train').children('option:gt(3)').hide();
                if ($('#ddlPax_Train').val() > 4) {
                    $('#ddlPax_Train').prop('selectedIndex', 3);
                }
                $('#dpDepartureDate_Train').datepicker("setEndDate", indoMaxDepartureDate);
                $('#dpReturnDate_Train').datepicker("setEndDate", indoMaxDepartureDate);
            }
            else {
                $('#ddlPax_Train').children('option').show();
                $('#dpDepartureDate_Train').datepicker("setEndDate", null);
                $('#dpReturnDate_Train').datepicker("setEndDate", null);
            }
        }

        if (productType.toLowerCase() == 'ferry') {
            var indoMaxDepartureDate = new Date();
            indoMaxDepartureDate.setDate(indoMaxDepartureDate.getDate() + 90);
            if (countryId == "90") {
                $('#ddlPax_Ferry').children('option:gt(3)').hide();
                if ($('#ddlPax_Ferry').val() > 4) {
                    $('#ddlPax_Ferry').prop('selectedIndex', 3);
                }
                $('#dpDepartureDate_Ferry').datepicker("setEndDate", indoMaxDepartureDate);
                $('#dpReturnDate_Ferry').datepicker("setEndDate", indoMaxDepartureDate);
            }
            else {
                $('#ddlPax_Ferry').children('option').show();
                $('#dpDepartureDate_Ferry').datepicker("setEndDate", null);
                $('#dpReturnDate_Ferry').datepicker("setEndDate", null);
            }
        }

        //if (productType.toLowerCase() == 'bus') {
        //    if ($('#hdnCurrentCountry').val() !== 'ID') {
        //        if (countryId == "90") {
        //            $('#bus-tickettype-box').show();
        //        }
        //        else {
        //            $('#rbBusDayPass').parent().show();
        //            $('#bus-tickettype-box').hide();
        //            $('#hdnTicketType_Bus').val('1');
        //            $('#bus-tickettype').text(JsCommonMsg.BusTickets);
        //            $('#btnBusTicket').tab('show');
        //        }
        //    }
        //}
    });

    $(document).on('click', '#fromSubPlaceDropdown_' + productType + ' .place', function () {
        var countryId = $(this).attr('data-countryid');
        var placeId = $(this).attr('data-placeid');
        var subplaceId = $(this).attr('data-subplaceid');
        var countryName = $(this).attr('data-countryname');
        var placeName = $(this).attr('data-placename');
        var subplaceName = $(this).attr('data-subplacename');
        var uniquePlaceName = $(this).attr('data-uniqueplacename');
        var uniqueSubPlaceName = $(this).attr('data-uniquesubplacename');
        var defaultsubplaceName = $(this).attr('default-subplacename');
        var defaultcountryName = $(this).attr('default-countryname');
        var defaultplaceName = $(this).attr('default-placename');

        if (parseInt($('#hdnFC_' + productType).val()) != countryId ||
            parseInt($('#hdnFP_' + productType).val()) != placeId ||
            parseInt($('#hdnFSP_' + productType).val()) != subplaceId) {
            $('#selectedFromSubPlace_' + productType).html(subplaceName);
            $('#selectedFromSubPlace_' + productType).attr('title', subplaceName);
            $('#originAdvancedMode_' + productType).attr('data-countryid', countryId);
            $('#originAdvancedMode_' + productType).attr('data-placeid', placeId);
            $('#originAdvancedMode_' + productType).attr('data-subplaceid', subplaceId);

            $('#selectedFromPlace_' + productType).parent().removeClass('is-error');

            $('#hdnOrigin_' + productType).val(defaultsubplaceName + ', ' + defaultplaceName + ', ' + defaultcountryName);
            $('#hdnFC_' + productType).val(countryId);
            $('#hdnFP_' + productType).val(placeId);
            $('#hdnFSP_' + productType).val(subplaceId);
            $('#hdnFPU_' + productType).val(uniquePlaceName);
            $('#hdnFSPU_' + productType).val(uniqueSubPlaceName);

            //PrepareToPlaceSelector(productId, productType);
            //PrepareToSubPlaceSelector(productId, productType);
        }
    });

    $(document).on('click', '#toPlaceDropdown_' + productType + ' .place', function () {
        var countryId = $(this).attr('data-countryid');
        var placeId = $(this).attr('data-placeid');
        var countryName = $(this).attr('data-countryname');
        var placeName = $(this).attr('data-placename');
        var defaultcountryName = $(this).attr('default-countryname');
        var defaultplaceName = $(this).attr('default-placename');
        var uniquePlaceName = $(this).attr('data-uniqueplacename');
        var uniqueSubPlaceName = $(this).attr('data-uniquesubplacename');

        if (parseInt($('#hdnTC_' + productType).val()) != countryId ||
            parseInt($('#hdnTP_' + productType).val()) != placeId) {
            $('#selectedToPlace_' + productType).html(placeName + ', ' + countryName);
            $('#selectedToPlace_' + productType).attr('title', placeName + ', ' + countryName);

            $('#destinationAdvancedMode_' + productType).attr('data-countryid', countryId);
            $('#destinationAdvancedMode_' + productType).attr('data-placeid', placeId);

            $('#selectedToPlace_' + productType).parent().removeClass('is-error');

            $('#hdnDestination_' + productType).val(defaultplaceName + ', ' + defaultcountryName);
            $('#hdnTC_' + productType).val(countryId);
            $('#hdnTP_' + productType).val(placeId);
            $('#hdnTPU_' + productType).val(uniquePlaceName);

            PrepareToSubPlaceSelector(productId, productType);
        }
    });

    $(document).on('click', '#toSubPlaceDropdown_' + productType + ' .place', function () {
        var countryId = $(this).attr('data-countryid');
        var placeId = $(this).attr('data-placeid');
        var subplaceId = $(this).attr('data-subplaceid');
        var countryName = $(this).attr('data-countryname');
        var placeName = $(this).attr('data-placename');
        var subplaceName = $(this).attr('data-subplacename');
        var uniquePlaceName = $(this).attr('data-uniqueplacename');
        var uniqueSubPlaceName = $(this).attr('data-uniquesubplacename');

        var defaultcountryName = $(this).attr('default-countryname');
        var defaultplaceName = $(this).attr('default-placename');
        var defaultsubplaceName = $(this).attr('default-subplacename');

        if (parseInt($('#hdnTC_' + productType).val()) != countryId ||
            parseInt($('#hdnTP_' + productType).val()) != placeId ||
            parseInt($('#hdnTSP_' + productType).val()) != subplaceId) {
            $('#selectedToSubPlace_' + productType).html(subplaceName);
            $('#selectedToSubPlace_' + productType).attr('title', subplaceName);

            $('#destinationAdvancedMode_' + productType).attr('data-countryid', countryId);
            $('#destinationAdvancedMode_' + productType).attr('data-placeid', placeId);
            $('#destinationAdvancedMode_' + productType).attr('data-subplaceid', subplaceId);

            $('#selectedToPlace_' + productType).parent().removeClass('is-error');

            $('#hdnDestination_' + productType).val(defaultsubplaceName + ', ' + defaultplaceName + ', ' + defaultcountryName);
            $('#hdnTC_' + productType).val(countryId);
            $('#hdnTP_' + productType).val(placeId);
            $('#hdnTSP_' + productType).val(subplaceId);
            $('#hdnTPU_' + productType).val(uniquePlaceName);
            $('#hdnTSPU_' + productType).val(uniqueSubPlaceName);
        }
    });

    //sort fromPlaceSelector place name 
    $('#fromPlaceDropdown_' + productType).children('ol').each(function () {
        $(this).children('li').sort(SortByContent).appendTo(this);
    });

    $(document).on('click', '[data-toggle="custom-action"]', function () {
        $('#txtSearchOrigin_Bus').focus();
        var currentLanguage = $('#airport-suggest').attr('data-language');
        if (currentLanguage == 'id') {
            $('#txtSearchOrigin_Bus').val('bandara');
        }
        else {
            $('#txtSearchOrigin_Bus').val('airport');
        }
        $('#txtSearchOrigin_Bus').trigger('input');
        $('txtSearchOrigin_Bus')
            .typeahead(
                {
                    hint: false,
                    highlight: true,
                    minLength: 0,
                    autoselect: true
                },
                {
                    name: 'fromPlace',
                    limit: 999,
                    displayKey: function (place) {
                        if (place == null)
                            return 'Place not found!';
                        if (place.spid == 0)
                            return place.pn;
                        else
                            return place.spn + ", " + place.pn;
                    },
                    source: sp_fpBloodhound.ttAdapter(),
                    templates: {
                        suggestion: function (place) {
                            if (place.spid == 0)
                                return '<div data-placename="' + place.pn.toLowerCase() + '" class="tt-place"><i class="icon-map-pin"></i><div class="tt-suggestion-optionval with-icon"><span class="place-name">' + place.pn + ',</span><span class="country-name"> ' + place.ctn + '</span>' + ((place.ip == true) ? '<span class="badge tt-popular">' + JsCommonLabel.SearchIntellisense_Suggestion_Label_Popular + '</span>' : '') + '</div></div>';
                            else
                                return '<div data-placename="' + place.spn.toLowerCase() + ", " + place.pn.toLowerCase() + '" class="tt-subplace"><i class="fa fa-map-marker"></i><div class="tt-suggestion-optionval with-icon"><span class="place-name">' + place.spn + ", " + place.pn + ',</span><span class="country-name"> ' + place.ctn + '</span>' + ((place.ip == true) ? '<span class="badge tt-popular">' + JsCommonLabel.SearchIntellisense_Suggestion_Label_Popular + '</span>' : '') + '</div></div>';
                        }
                    }
                }
            )
            .bind('typeahead:select', function (object, datum) {
                searchPanelSetLocation(datum);
                InitSearchDestinationTypeahead();

                $('#txtSearchDestination_' + productType).focus();
            })
            .on('click', function () {
                $(this).select();
            })
        $('#originBasicMode_Bus').children().children().siblings('.loading-spinner').hide();
    });

    //#endregion
    //$(document).on('typeahead:select', '#txtSearchOrigin_Bus', function () {
    //    var FromCountry = $('#hdnFC_Bus').val();
    //    if ($('#hdnCurrentCountry').val() !== 'ID') {
    //        if (FromCountry == "90") {
    //            $('#bus-tickettype-box').show();
    //        }
    //        else {
    //            $('#rbBusDayPass').parent().show();
    //            $('#bus-tickettype-box').hide();
    //            $('#hdnTicketType_Bus').val('1');
    //            $('#bus-tickettype').text(JsCommonMsg.BusTickets);
    //            $('#btnBusTicket').tab('show');
    //        }
    //    }
    //});
    $(document).on('typeahead:select', '#txtSearchOrigin_Train', function () {
        var FromCountry = $('#hdnFC_Train').val();
        var indoMaxDepartureDate = new Date();
        indoMaxDepartureDate.setDate(indoMaxDepartureDate.getDate() + 90);
        if (FromCountry == "90") {
            //$('#ddlPax_Train').hide();
            //$('#ddlPax_Train').siblings().hide();
            //$('#divInfantPax_Train').parent().removeClass("hide");
            //$('#dpDepartureDate_Train').datepicker("setEndDate", indoMaxDepartureDate);
            //$('#dpReturnDate_Train').datepicker("setEndDate", indoMaxDepartureDate);
            $('#ddlPax_Train').children('option:gt(3)').hide();
            if ($('#ddlPax_Train').val() > 4) {
                $('#ddlPax_Train').prop('selectedIndex', 3);
            }
            $('#dpDepartureDate_Train').datepicker("setEndDate", indoMaxDepartureDate);
            $('#dpReturnDate_Train').datepicker("setEndDate", indoMaxDepartureDate);
        }
        else {
            //$('#divInfantPax_Train').parent().addClass("hide");
            $('#ddlPax_Train').children('option').show();
            $('#dpDepartureDate_Train').datepicker("setEndDate", null);
            $('#dpReturnDate_Train').datepicker("setEndDate", null);
        }
        //$('#divInfantPax_Train').parent().addClass("hide");
        //$('#dpDepartureDate_Train').datepicker("setEndDate", null);
        //$('#dpReturnDate_Train').datepicker("setEndDate", null);
    });
    $(document).on('typeahead:select', '#txtSearchOrigin_Ferry', function () {
        var FromCountry = $('#hdnFC_Ferry').val();
        var indoMaxDepartureDate = new Date();
        indoMaxDepartureDate.setDate(indoMaxDepartureDate.getDate() + 90);
        if (FromCountry == "90") {
     
            $('#ddlPax_Ferry').children('option:gt(3)').hide();
            if ($('#ddlPax_Ferry').val() > 4) {
                $('#ddlPax_Ferry').prop('selectedIndex', 3);
            }
            $('#dpDepartureDate_Ferry').datepicker("setEndDate", indoMaxDepartureDate);
            $('#dpReturnDate_Ferry').datepicker("setEndDate", indoMaxDepartureDate);
        }
        else {
            //$('#divInfantPax_Train').parent().addClass("hide");
            $('#ddlPax_Ferry').children('option').show();
            $('#dpDepartureDate_Ferry').datepicker("setEndDate", null);
            $('#dpReturnDate_Ferry').datepicker("setEndDate", null);
        }
    });
    //#region Setting up Origin/Destination Swap button
    $('#commonSearchForm_' + productType + ' .swap a').click(function () {
        var isValid = true;

        var FC = $('#hdnFC_' + productType).val();
        var FP = $('#hdnFP_' + productType).val();
        var FSP = $('#hdnFSP_' + productType).val();
        var FPU = $('#hdnFPU_' + productType).val();
        var FSPU = $('#hdnFSPU_' + productType).val();
        var TC = $('#hdnTC_' + productType).val();
        var TP = $('#hdnTP_' + productType).val();
        var TSP = $('#hdnTSP_' + productType).val();
        var TPU = $('#hdnTPU_' + productType).val();
        var TSPU = $('#hdnTSPU_' + productType).val();

        var fromCountryId = 0;
        var fromPlaceId = 0;
        var fromSubPlaceId = 0;
        var toCountryId = 0;
        var toPlaceId = 0;
        var toSubPlaceId = 0;

        if (_isAdvancedMode) {
            fromCountryId = $('#originAdvancedMode_' + productType).attr('data-countryid');
            fromPlaceId = $('#originAdvancedMode_' + productType).attr('data-placeid');
            fromSubPlaceId = $('#originAdvancedMode_' + productType).attr('data-subplaceid');
            toCountryId = $('#destinationAdvancedMode_' + productType).attr('data-countryid');
            toPlaceId = $('#destinationAdvancedMode_' + productType).attr('data-placeid');
            toSubPlaceId = $('#destinationAdvancedMode_' + productType).attr('data-subplaceid');

            if (fromCountryId == 0 || fromPlaceId == 0) {
                $('#selectedFromPlace_' + productType).parent().addClass('is-error');
                isValid = false;
            }

            if (toCountryId == 0 || toPlaceId == 0) {
                $('#selectedToPlace_' + productType).parent().addClass('is-error');
                isValid = false;
            }
        }
        else {
            fromCountryId = $('#originBasicMode_' + productType).attr('data-countryid');
            fromPlaceId = $('#originBasicMode_' + productType).attr('data-placeid');
            fromSubPlaceId = $('#originBasicMode_' + productType).attr('data-subplaceid');
            toCountryId = $('#destinationBasicMode_' + productType).attr('data-countryid');
            toPlaceId = $('#destinationBasicMode_' + productType).attr('data-placeid');
            toSubPlaceId = $('#destinationBasicMode_' + productType).attr('data-subplaceid');

            if (fromCountryId == 0 || fromPlaceId == 0) {
                $('#txtSearchOrigin_' + productType).addClass('is-error');
                isValid = false;
            }

            if (toCountryId == 0 || toPlaceId == 0) {
                $('#txtSearchDestination_' + productType).addClass('is-error');
                isValid = false;
            }
        }

        if (isValid) {
            var bs_FP = $('#txtSearchOrigin_' + productType).val();
            var bs_TP = $('#txtSearchDestination_' + productType).val();
            var as_FP = $('#selectedFromPlace_' + productType).html();
            var as_FSP = $('#selectedFromSubPlace_' + productType).html();
            var as_TP = $('#selectedToPlace_' + productType).html();
            var as_TSP = $('#selectedToSubPlace_' + productType).html();
            var origin = $('#hdnOrigin_' + productType).val();
            var destination = $('#hdnDestination_' + productType).val();

            if (_isAdvancedMode) {
                $('#selectedFromPlace_' + productType).html(as_TP);
                $('#selectedFromSubPlace_' + productType).html(as_TSP);
                $('#selectedToPlace_' + productType).html(as_FP);
                $('#selectedToSubPlace_' + productType).html(as_FSP);

                $('#originAdvancedMode_' + productType).attr('data-countryid', toCountryId);
                $('#originAdvancedMode_' + productType).attr('data-placeid', toPlaceId);
                $('#originAdvancedMode_' + productType).attr('data-subplaceid', toSubPlaceId);
                $('#destinationAdvancedMode_' + productType).attr('data-countryid', fromCountryId);
                $('#destinationAdvancedMode_' + productType).attr('data-placeid', fromPlaceId);
                $('#destinationAdvancedMode_' + productType).attr('data-subplaceid', fromSubPlaceId);

                //Swapping subplaces dropdown items
                var toSubPlaces = $('#toSubPlaceDropdown_' + productType).children();
                var fromSubPlaces = $('#fromSubPlaceDropdown_' + productType).children();
                $('#toSubPlaceDropdown_' + productType).append(fromSubPlaces);
                $('#fromSubPlaceDropdown_' + productType).append(toSubPlaces);
            }
            else {
                $('#originBasicMode_' + productType).attr('data-countryid', toCountryId);
                $('#originBasicMode_' + productType).attr('data-placeid', toPlaceId);
                $('#originBasicMode_' + productType).attr('data-subplaceid', toSubPlaceId);
                $('#destinationBasicMode_' + productType).attr('data-countryid', fromCountryId);
                $('#destinationBasicMode_' + productType).attr('data-placeid', fromPlaceId);
                $('#destinationBasicMode_' + productType).attr('data-subplaceid', fromSubPlaceId);

                $('#txtSearchOrigin_' + productType).val(bs_TP);
                $('#txtSearchDestination_' + productType).val(bs_FP);
            }

            $('#hdnOrigin_' + productType).val(destination);
            $('#hdnDestination_' + productType).val(origin);

            $('#hdnFC_' + productType).val(TC);
            $('#hdnFP_' + productType).val(TP);
            $('#hdnFSP_' + productType).val(TSP);
            $('#hdnFPU_' + productType).val(TPU);
            $('#hdnFSPU_' + productType).val(TSPU);
            $('#hdnTC_' + productType).val(FC);
            $('#hdnTP_' + productType).val(FP);
            $('#hdnTSP_' + productType).val(FSP);
            $('#hdnTPU_' + productType).val(FPU);
            $('#hdnTSPU_' + productType).val(FSPU);
        }
        else
            TriggerShakeAnimation($(".search-wrap"));
    });
    //#endregion

    //#region Form validation before submit for common search panel
    $('form#commonSearchForm_' + productType).submit(function (e) {
        isValid = true;
        $('#locationError_' + productType).text('');
        //check for origin & destination search box
        var fromCountryId = 0;
        var fromPlaceId = 0;
        var fromSubPlaceId = 0;
        var toCountryId = 0;
        var toPlaceId = 0;
        var toSubPlaceId = 0;
        var fromPlaceText = "";
        var toPlaceText = "";
        if (_isAdvancedMode) {
            fromCountryId = $('#originAdvancedMode_' + productType).attr('data-countryid');
            fromPlaceId = $('#originAdvancedMode_' + productType).attr('data-placeid');
            toCountryId = $('#destinationAdvancedMode_' + productType).attr('data-countryid');
            toPlaceId = $('#destinationAdvancedMode_' + productType).attr('data-placeid');

            if (fromCountryId == 0 || fromPlaceId == 0) {
                $('#selectedFromPlace_' + productType).parent().addClass('is-error');
                isValid = false;
            }

            if (toCountryId == 0 || toPlaceId == 0) {
                $('#selectedToPlace_' + productType).parent().addClass('is-error');
                isValid = false;
            }
        }
        else {
            fromCountryId = $('#originBasicMode_' + productType).attr('data-countryid');
            fromPlaceId = $('#originBasicMode_' + productType).attr('data-placeid');
            fromSubPlaceId = $('#originBasicMode_' + productType).attr('data-subplaceid');
            toCountryId = $('#destinationBasicMode_' + productType).attr('data-countryid');
            toPlaceId = $('#destinationBasicMode_' + productType).attr('data-placeid');
            toSubPlaceId = $('#destinationBasicMode_' + productType).attr('data-subplaceid');
            fromPlaceText = $('#txtSearchOrigin_' + productType).val();
            toPlaceText = $('#txtSearchDestination_' + productType).val();
            if (fromCountryId == 0 || fromPlaceId == 0 || fromPlaceText === "") {
                $('#txtSearchOrigin_' + productType).addClass('is-error');
                isValid = false;
            }

            if (toCountryId == 0 || toPlaceId == 0 || toPlaceText === "") {
                $('#txtSearchDestination_' + productType).addClass('is-error');
                isValid = false;
            }
            //check either same place
            if (productType != 'Ferry' && fromPlaceId === toPlaceId) {
                if (fromCountryId === toCountryId) {
                    if (fromSubPlaceId == 0 || toSubPlaceId == 0) {
                        $('#txtSearchOrigin_' + productType).addClass('is-error');
                        $('#txtSearchDestination_' + productType).addClass('is-error');
                        $('#locationError_' + productType).text(JsErrorMsg.Msg1);
                        isValid = false;
                    }
                }
            }
        }

        //Get current on-screen roundtrip or one trip
        if ($('input:radio[data-product=' + productType + ']:checked').val() === "1" || $('#ddlTripType').val() === "1") {
            _isRoundTrip = false;
        } else {
            _isRoundTrip = true;
        }

        //checking departure/return date field
        if (_isRoundTrip && ($('#dpReturnDate_' + productType).val() === ''
            || (new Date($('#dpReturnDate_' + productType).val()) < new Date($('#dpDepartureDate_' + productType).val())))) {
            $('#dpReturnDate_' + productType).addClass('is-error');
            isValid = false;
        }
        if ($('#dpDepartureDate_' + productType).val() === '') {
            $('#dpDepartureDate_' + productType).addClass('is-error');
            isValid = false;
        }
        AF('pba', 'event', { eventType: 'EVENT', eventName: 'search', eventValue: { 'fromplace': fromPlaceText, 'toplace': toPlaceText, 'depart_date': $('#dpDepartureDate_' + productType).val(), 'return_date': $('#dpReturnDate_' + productType).val(), 'product': productType } });


        if (!isValid && !isCwForm) {
            TriggerShakeAnimation($(".search-wrap"));
            e.preventDefault();
        }
    });
    //#endregion
    $('form#carForm').submit(function (e) {
        AF('pba', 'event', { eventType: 'EVENT', eventName: 'search', eventValue: { 'pickup_place': $('#ddlFromPlaceBasicCar').val(), 'depart_date': $('#ddPickUpDateCar').val(), 'return_date': $('#ddReturnDateCar').val(), 'product': 'car' } });
    });
    //#region Setting up Origin/Destination Swap button for brief search panel
    $('#modify-search .swap a').click(function (e) {
        if (!$('#txtSearchOrigin_' + productType).length)
            return false;

        e.stopImmediatePropagation();
        e.preventDefault();

        var isValid = true;

        var FC = $('#hdnFC_' + productType).val();
        var FP = $('#hdnFP_' + productType).val();
        var FSP = $('#hdnFSP_' + productType).val();
        var FPU = $('#hdnFPU_' + productType).val();
        var FSPU = $('#hdnFSPU_' + productType).val();
        var TC = $('#hdnTC_' + productType).val();
        var TP = $('#hdnTP_' + productType).val();
        var TSP = $('#hdnTSP_' + productType).val();
        var TPU = $('#hdnTPU_' + productType).val();
        var TSPU = $('#hdnTSPU_' + productType).val();
        var origin = $('#txtSearchOrigin_' + productType).val();
        var destination = $('#txtSearchDestination_' + productType).val();

        var _origin = $('#txtSearchOrigin_' + productType).val();
        var _destination = $('#txtSearchDestination_' + productType).val();

        if (FC == 0 || FP == 0 || $.trim(_origin) === '') {
            $('#txtSearchOrigin_' + productType).addClass('is-error');
            isValid = false;
        }

        if (TC == 0 || TP == 0 || $.trim(_destination) === '') {
            $('#txtSearchDestination_' + productType).addClass('is-error');
            isValid = false;
        }

        if (isValid) {
            var bs_FP = $('#txtSearchOrigin_' + productType).val();
            var bs_TP = $('#txtSearchDestination_' + productType).val();

            $('#txtSearchOrigin_' + productType).val(bs_TP);
            $('#txtSearchDestination_' + productType).val(bs_FP);

            $('#hdnOrigin_' + productType).val(destination);
            $('#hdnFC_' + productType).val(TC);
            $('#hdnFP_' + productType).val(TP);
            $('#hdnFSP_' + productType).val(TSP);
            $('#hdnFPU_' + productType).val(TPU);
            $('#hdnFSPU_' + productType).val(TSPU);
            $('#hdnDestination_' + productType).val(origin);
            $('#hdnTC_' + productType).val(FC);
            $('#hdnTP_' + productType).val(FP);
            $('#hdnTSP_' + productType).val(FSP);
            $('#hdnTPU_' + productType).val(FPU);
            $('#hdnTSPU_' + productType).val(FSPU);
        }
        else {
            TriggerShakeAnimation($(".sub-search-wrap"));
        }
    });

    //#region Form validation before submit for brief search panel
    $('form#briefSearchForm_' + productType).submit(function (e) {
        isValid = true;
        $('#locationError_' + productType).text('');
        //check for origin & destination search box
        var FC = $('#hdnFC_' + productType).val();
        var FP = $('#hdnFP_' + productType).val();
        var FSP = $('#hdnFSP_' + productType).val();
        var TC = $('#hdnTC_' + productType).val();
        var TP = $('#hdnTP_' + productType).val();
        var TSP = $('#hdnTSP_' + productType).val();
        var _origin = $('#txtSearchOrigin_' + productType).val();
        var _destination = $('#txtSearchDestination_' + productType).val();

        if (FC == 0 || FP == 0 || $.trim(_origin) === '') {
            $('#txtSearchOrigin_' + productType).addClass('is-error');
            isValid = false;
        }

        if (TC == 0 || TP == 0 || $.trim(_destination) === '') {
            $('#txtSearchDestination_' + productType).addClass('is-error');
            isValid = false;
        }

        //Get current on-screen roundtrip or one trip
        if ($('input:radio[data-product=' + productType + ']:checked').val() === "1") {
            _isRoundTrip = false;
        } else {
            _isRoundTrip = true;
        }

        //checking departure/return date field
        if (_isRoundTrip && ($('#dpReturnDate_' + productType).val() === ''
            || (new Date($('#dpReturnDate_' + productType).val()) < new Date($('#dpDepartureDate_' + productType).val())))) {
            $('#dpReturnDate_' + productType).addClass('is-error');
            isValid = false;
        }
        if ($('#dpDepartureDate_' + productType).val() === '') {
            $('#dpDepartureDate_' + productType).addClass('is-error');
            isValid = false;
        }

        //check either same place
        if (productType != 'Ferry' && FP === TP) {
            if (FC === TC) {
                if (FSP == 0 || TSP == 0) {
                    $('#txtSearchOrigin_' + productType).addClass('is-error');
                    $('#txtSearchDestination_' + productType).addClass('is-error');
                    $('#locationError_' + productType).text(JsErrorMsg.Msg1);
                    isValid = false;
                }
            }
        }

        if (!isValid && !isCwForm) {
            TriggerShakeAnimation($(".sub-search-wrap"));
            e.preventDefault();
        }
    });
    //#endregion

    if ($("#hdnSelectedCurrency_" + productType).val() === "") {
        //$("#selectedCurrencyspan").html("Currency");
        $('a.toggle-currency').html("Currency <span class='caret'></span>");
    }

    $("#currency-list").on("click", "a", function (e) {
        e.preventDefault();
        var selecting = $(this).parent().data("value");
        if ($(".k-top-bar").length > 0) {
            $(".k-top-bar div img").hide();
            $(`.k-top-bar div img.${selecting}`).show();
        }
        $(".SelectedCurrency" + productType).val(selecting).trigger("change");
        //$("#hdnSelectedCurrency2_" + productType).val($(this).parent().data("value")).trigger("change");
    });
    if (defaultLocation != null) {        
        searchPanelSetLocation(defaultLocation);
        $('#txtSearchOrigin_' + productType).val(defaultLocation.spid == 0 ? defaultLocation.pn : `${defaultLocation.spn}, ${defaultLocation.pn}`);
        $('#txtSearchDestination_' + productType).focus();
        if (defaultArrivalLocation != null) {
            searchPanelSetArrivalLocation(defaultArrivalLocation);
            $('#txtSearchDestination_' + productType).val(defaultArrivalLocation.spid == 0 ? defaultArrivalLocation.pn : `${defaultArrivalLocation.spn}, ${defaultArrivalLocation.pn}`);
        }
        InitSearchDestinationTypeahead();
        $('#txtSearchDestination_' + productType).focus();
    };
    //$('#btnBusTicket').click(function () {
    //    $('#bus-tickettype').text(JsCommonMsg.BusTickets);
    //    $('#hdnTicketType_Bus').val('1');
    //    $('#rbBusDayPass').parent().show();
    //});

    //$('#btnShuttleTicket').click(function () {
    //    $('#bus-tickettype').text(JsCommonMsg.ShuttleTickets);
    //    $('#hdnTicketType_Bus').val('2');
    //    $('#rbBusDayPass').parent().hide();
    //    if ($('#rbBusDayPass').prop('checked')) {
    //        $('input:radio[data-product="Bus"]:eq(1)').prop('checked', true);
    //        $('#busdaypass-search-form').hide();
    //        $('#Bus-search-panel-box-div').show();
    //        $('#Bus-location-error-div').show();
    //        $('#Bus-search-option-div').show();
    //    }
    //});
}

function InitDayPassSearchPanel(productId, productType) {
    InitSearchOriginDropDownList();

    function InitSearchOriginDropDownList() {

        $('#txtSearchOrigin_' + productType).change(function () {
            var fromCountryId = $(this).find(':selected').data('fromcountryid');
            var fromPlaceId = $(this).find(':selected').data('fromplaceid');
            var uniqueFromPlaceName = $(this).find(':selected').data('uniquefromplacename');
            var origin = $(this).find(':selected').text();
            $('#hdnOrigin_' + productType).val(origin);
            $('#hdnFC_' + productType).val(fromCountryId);
            $('#hdnFP_' + productType).val(fromPlaceId);
            $('#hdnFPU_' + productType).val(uniqueFromPlaceName);
        });
    }

    //#region Form validation before submit for brief search panel (common soon)

    //#region Form validation before submit for common search panel
    $('form#commonSearchForm_' + productType).submit(function (e) {
        isValid = true;
        $('#locationError_' + productType).text('');
        var fromCountryId = 0;
        var fromPlaceId = 0;
        var fromPlaceText = "";
        fromCountryId = $('#hdnFC_' + productType).val();
        fromPlaceId = $('#hdnFP_' + productType).val();

        if (fromCountryId == 0 || fromPlaceId == 0) {
            $('#txtSearchOrigin_' + productType).addClass('is-error');
            isValid = false;
            return isValid;
        }
    });

    //#region Form validation before submit for brief search panel
    $('form#briefSearchForm_' + productType).submit(function (e) {
        isValid = true;
        $('#locationError_' + productType).text('');
        //check for origin & destination search box
        var fromCountryId = 0;
        var fromPlaceId = 0;
        var fromPlaceText = "";
        fromCountryId = $('#hdnFC_' + productType).val();
        fromPlaceId = $('#hdnFP_' + productType).val();

        if (fromCountryId == 0 || fromPlaceId == 0) {
            $('#txtSearchOrigin_' + productType).addClass('is-error');
            isValid = false;
        }
        if (!isValid) {
            TriggerShakeAnimation($(".sub-search-wrap"));
            e.preventDefault();
        }
    });
    //#endregion


    if ($("#hdnSelectedCurrency_" + productType).val() === "") {
        $('a.toggle-currency').html("Currency <span class='caret'></span>");
    }

    $("#currency-list").on("click", "a", function (e) {
        e.preventDefault();
        $(".SelectedCurrency" + productType).val($(this).parent().data("value")).trigger("change");
    });
}

//function InitTrainLuxurySearchPanel(productId, productType) {
//    InitSearchOriginDropDownList();

//    function InitSearchOriginDropDownList() {

//        $('#txtSearchOrigin_' + productType).change(function () {
//            if ($('#txtSearchDestination_' + productType).val() != '')
//                $('#txtSearchDestination_' + productType).val($('#txtSearchDestination_' + productType + ' option:first').val());
//            $('#txtSearchDestination_' + productType).children('option[value != "" ]').show();
//            $('#txtSearchDestination_' + productType).children("option[value^=" + $(this).val() + "]").hide();
//            var fromCountryId = $(this).find(':selected').data('fromcountryid');
//            var fromPlaceId = $(this).find(':selected').data('fromplaceid');
//            var fromsubplaceid = $(this).find(':selected').data('fromsubplaceid');
//            var uniqueFromPlaceName = $(this).find(':selected').data('uniquefromplacename');
//            var uniqueFromSubPlaceName = $(this).find(':selected').data('uniquefromsubplacename');
//            var origin = $(this).find(':selected').text();        
//            $('#hdnOrigin_' + productType).val(origin);
//            $('#hdnFC_' + productType).val(fromCountryId);
//            $('#hdnFP_' + productType).val(fromPlaceId);
//            $('#hdnFSP_' + productType).val(fromsubplaceid);            
//            $('#hdnFPU_' + productType).val(uniqueFromPlaceName);
//            $('#hdnFSPU_' + productType).val(uniqueFromSubPlaceName);            
//        });

//        $('#txtSearchDestination_' + productType).mousedown(function (event) {
//            //event.preventDefault();
//            if($('#txtSearchOrigin_' + productType).val() == null)
//            {
//                alert('Please select departure first');
//                return false;
//            }
//        });

//        $('#txtSearchDestination_' + productType).change(function (event) {
//            //if ($('#txtSearchOrigin_' + productType).val() != '')
//            //    $('#txtSearchOrigin_' + productType).val($('#txtSearchDestination_' + productType + ' option:first').val());
//            //$('#txtSearchOrigin_' + productType).children('option[value != "" ]').show();
//            //$('#txtSearchOrigin_' + productType).children("option[value^=" + $(this).val() + "]").hide();
//            var toCountryId = $(this).find(':selected').data('tocountryid');
//            var toPlaceId = $(this).find(':selected').data('toplaceid');
//            var tosubplaceid = $(this).find(':selected').data('tosubplaceid');
//            var uniqueToPlaceName = $(this).find(':selected').data('uniquetoplacename');
//            var uniqueToSubPlaceName = $(this).find(':selected').data('uniquetosubplacename');
//            var destination = $(this).find(':selected').text();        
//            $('#hdnDestination_' + productType).val(destination);
//            $('#hdnTC_' + productType).val(toCountryId);
//            $('#hdnTP_' + productType).val(toPlaceId);
//            $('#hdnTSP_' + productType).val(tosubplaceid);
//            $('#hdnTPU_' + productType).val(uniqueToPlaceName);
//            $('#hdnTSPU_' + productType).val(uniqueToSubPlaceName);            
//        });
//    }

//    //#region Form validation before submit for brief search panel (common soon)

//    //#region Form validation before submit for common search panel
//    $('form#commonSearchForm_' + productType).submit(function (e) {
//        isValid = true;
//        $('#locationError_' + productType).text('');
//        var fromCountryId = 0;
//        var fromPlaceId = 0;
//        var fromPlaceText = "";
//        var fromCountryId = $('#hdnFC_' + productType).val();
//        var fromPlaceId = $('#hdnFP_' + productType).val();
//        var fromSubPlaceId = $('#hdnFSP_' + productType).val();
//        var toPlaceId = $('#hdnTP_' + productType).val();
//        var toSubPlaceId = $('#hdnTSP_' + productType).val();

//        if (fromCountryId == 0 || fromPlaceId == 0 || toPlaceId == 0 || (fromPlaceId == toPlaceId && fromSubPlaceId == toSubPlaceId)) {
//            $('#txtSearchOrigin_' + productType).addClass('is-error');
//            isValid = false;
//            return isValid;
//        }


//    });

//    //#region Form validation before submit for brief search panel
//    $('form#briefSearchForm_' + productType).submit(function (e) {
//        isValid = true;
//        $('#locationError_' + productType).text('');
//        //check for origin & destination search box
//        var fromCountryId = 0;
//        var fromPlaceId = 0;
//        var fromPlaceText = "";
//        fromCountryId = $('#hdnFC_' + productType).val();
//        fromPlaceId = $('#hdnFP_' + productType).val();

//        if (fromCountryId == 0 || fromPlaceId == 0) {
//            $('#txtSearchOrigin_' + productType).addClass('is-error');
//            isValid = false;
//        }
//        if (!isValid) {
//            TriggerShakeAnimation($(".sub-search-wrap"));
//            e.preventDefault();
//        }
//    });
//    //#endregion


//    if ($("#hdnSelectedCurrency_" + productType).val() === "") {
//        $('a.toggle-currency').html("Currency <span class='caret'></span>");
//    }

//    $("#currency-list").on("click", "a", function (e) {
//        e.preventDefault();
//        $(".SelectedCurrency" + productType).val($(this).parent().data("value")).trigger("change");
//    });
//}

function AdvancedSearchMode(productType) {
    $('#aBasic_' + productType).show();
    $('#originAdvancedMode_' + productType).show();
    $('#destinationAdvancedMode_' + productType).show();

    $('#aAdvanced_' + productType).hide();
    $('#originBasicMode_' + productType).hide();
    $('#destinationBasicMode_' + productType).hide();

    var fromCountryId = parseInt($('#originAdvancedMode_' + productType).attr('data-countryid'));
    var fromPlaceId = parseInt($('#originAdvancedMode_' + productType).attr('data-placeid'));
    var fromSubPlaceId = parseInt($('#originAdvancedMode_' + productType).attr('data-subplaceid'));
    var toCountryId = parseInt($('#destinationAdvancedMode_' + productType).attr('data-countryid'));
    var toPlaceId = parseInt($('#destinationAdvancedMode_' + productType).attr('data-placeid'));
    var toSubPlaceId = parseInt($('#destinationAdvancedMode_' + productType).attr('data-subplaceid'));

    //copying origin & destination info to hidden fields for submit
    var fromCountryNPlaceName = $('#selectedFromPlace_' + productType).html();
    var fromSubPlaceName = $('#selectedFromSubPlace_' + productType).html();
    var toCountryNPlaceName = $('#selectedToPlace_' + productType).html();
    var toSubPlaceName = $('#selectedToSubPlace_' + productType).html();
    if (fromCountryId != 0 && fromPlaceId != 0 && fromSubPlaceId != 0)
        $('#hdnOrigin_' + productType).val(fromSubPlaceName + ', ' + fromCountryNPlaceName);
    else if (fromSubPlaceId === 0)
        $('#hdnOrigin_' + productType).val(fromCountryNPlaceName);
    else
        $('#hdnOrigin_' + productType).val('');

    if (toCountryId != 0 && toPlaceId != 0 && toSubPlaceId != 0)
        $('#hdnDestination_' + productType).val(toSubPlaceName + ', ' + toCountryNPlaceName);
    else if (toSubPlaceId === 0)
        $('#hdnDestination_' + productType).val(toCountryNPlaceName);
    else
        $('#hdnDestination_' + productType).val('');

    $('#hdnFC_' + productType).val(fromCountryId);
    $('#hdnFP_' + productType).val(fromPlaceId);
    $('#hdnFSP_' + productType).val(fromSubPlaceId);
    $('#hdnTC_' + productType).val(toCountryId);
    $('#hdnTP_' + productType).val(toPlaceId);
    $('#hdnTSP_' + productType).val(toSubPlaceId);

    //$('.swap').addClass('advanced-mode');
    $('.' + productType + '.swap').addClass('advanced-mode');
    $('#locationError_' + productType).text('');
    _isAdvancedMode = true;
}

function PrepareToPlaceSelector(productId, productType) {
    $('#selectedToPlace_' + productType).html(JsCommonMsg.DestinationLocation);
    $('#hdnTC_' + productType).val('0');
    $('#hdnTP_' + productType).val('0');
    $('#hdnTSP_' + productType).val('0');
    $('#hdnTPU_' + productType).val('');
    $('#hdnTSPU_' + productType).val('');
    $('#selectedToPlace_' + productType).parent().addClass('disabled');

    $('#destinationAdvancedMode_' + productType).attr('data-countryid', 0);
    $('#destinationAdvancedMode_' + productType).attr('data-placeid', 0);
    $('#destinationAdvancedMode_' + productType).attr('data-subplaceid', 0);

    var params =
    {
        "productId": productId,
        "fromCountryId": parseInt($('#hdnFC_' + productType).val()),
        "fromPlaceId": parseInt($('#hdnFP_' + productType).val()),
        "fromSubPlaceId": parseInt($('#hdnFSP_' + productType).val())
    };

    $.ajax({
        dataType: "json",
        url: "/api/place/country_and_place",
        data: params,
        beforeSend: function () {
            $('#selectedToPlace_' + productType).parent().siblings('.loading-spinner').show();
        },
        complete: function () {
            $('#selectedToPlace_' + productType).parent().siblings('.loading-spinner').hide();
        },
        success: function (data) {
            $('#selectedToPlace_' + productType).parent().removeClass('disabled');
            $('#toPlaceDropdown_' + productType).empty();

            if (data.length == 0) {
                $('#toPlaceDropdown_' + productType).append('<div class="flyout-group clearfix">' + JsCommonMsg.Msg1 + '</div>');
                return false;
            }

            var countryList = [];
            $.each(data, function (i, place) {
                countryList.push(place.ctn);
            });
            // $.each($.unique(countryList), function (i, countryName) {
            $.each(unique(countryList), function (i, countryName) {
                $('#toPlaceDropdown_' + productType).append('<div class="flyout-header clearfix">' + countryName + '</div>');
                var placeItemWrapper = $('<ol class="flyout-group clearfix"/>');
                $.each(data, function (i, place) {
                    if (place.ctn === countryName) {
                        placeItemWrapper.attr('data-countryid', place.ctid);
                        placeItemWrapper.append('<li class="place flyout-item" data-countryid="' + place.ctid + '" data-countryname="' + place.ctn + '" default-countryname="' + place.dctn + '" data-placeid="' + place.pid + '" data-placename="' + place.pn + '" default-placename="' + place.pn + '" data-uniqueplacename="' + place.pusn + '" data-uniquesubplacename="' + place.spusn + '" title="' + place.pn + '">' + place.pn + '</li>');
                    }
                });
                $('#toPlaceDropdown_' + productType).append(placeItemWrapper);
                placeItemWrapper.children().sort(SortByContent) // sort elements
                                           .appendTo(placeItemWrapper);
            });
            $("div[id^='toPlaceDropdown'] .place[data-placeid='422'], div[id^='toPlaceDropdown'] .place[data-placeid='428']").addClass("bold");
        }
    });
}

function unique(array) {
    return $.grep(array, function (el, index) {
        return index === $.inArray(el, array);
    });
}

function PrepareFromSubPlaceSelector(productId, productType) {
    $('#selectedFromSubPlace_' + productType).html(JsCommonMsg.AnySubLocation);
    $('#hdnFSP_' + productType).val('0');
    $('#hdnFSPU_' + productType).val('');
    $('#selectedFromSubPlace_' + productType).parent().addClass('disabled');

    $('#originAdvancedMode_' + productType).attr('data-subplaceid', 0);

    var _fromCountryId = parseInt($('#hdnFC_' + productType).val());
    var _fromPlaceId = parseInt($('#hdnFP_' + productType).val());
    var _fromPlaceUniqueName = $('#hdnFPU_' + productType).val();

    var params =
    {
        "productId": productId,
        "fromCountryId": _fromCountryId,
        "fromPlaceId": _fromPlaceId,
        "toCountryId": 0,
        "toPlaceId": 0,
        "fromSubPlaceId": 0
    };

    $.ajax({
        dataType: "json",
        url: "/api/place/subplace_only",
        data: params,
        beforeSend: function () {
            $('#selectedFromSubPlace_' + productType).parent().siblings('.loading-spinner').show();
        },
        complete: function () {
            $('#selectedFromSubPlace_' + productType).parent().siblings('.loading-spinner').hide();
        },
        success: function (data) {
            var subplaceItemWrapper = $('<ol class="flyout-group clearfix"/>');
            if (data.length > 0) {
                $.each(data, function (i, subplace) {
                    subplaceItemWrapper.append('<li class="place flyout-item" data-countryid="' + subplace.ctid + '" data-countryname="' + subplace.ctn + '" default-countryname="' + data[0].dctn + '" data-placeid="' + subplace.pid + '" data-placename="' + subplace.pn + '" default-placename="' + subplace.pn + '" data-subplaceid="' + subplace.spid + '" data-subplacename="' + subplace.spn + '" default-subplacename="' + subplace.spn + '" data-uniqueplacename="' + subplace.pusn + '" data-uniquesubplacename="' + subplace.spusn + '" title="' + subplace.spn + '">' + subplace.spn + '</li>');
                });
                $('#selectedFromSubPlace_' + productType).parent().removeClass('disabled');
                $('#fromSubPlaceDropdown_' + productType).empty();
                $('#fromSubPlaceDropdown_' + productType).append(subplaceItemWrapper);
                subplaceItemWrapper.children().sort(SortByContent) // sort elements
                                               .appendTo(subplaceItemWrapper);
                subplaceItemWrapper.prepend('<li class="place flyout-item" data-countryid="' + data[0].ctid + '" data-countryname="' + data[0].ctn + '" default-countryname="' + data[0].dctn + '" data-placeid="' + data[0].pid + '" data-placename="' + data[0].pn + '" default-placename="' + data[0].pn + '" data-subplaceid="0" data-subplacename="" default-subplacename="" data-uniqueplacename="' + data[0].pusn + '" data-uniquesubplacename="">' + JsCommonMsg.AnySubLocation + '</li>');
            }
            else {
                subplaceItemWrapper.append('<li class="place flyout-item" data-countryid="' + _fromCountryId + '" data-countryname="" default-countryname="" data-placeid="' + _fromPlaceId + '" data-placename="" default-placename="" data-subplaceid="0" data-subplacename="" default-subplacename="" data-uniqueplacename="' + _fromPlaceUniqueName + '" data-uniquesubplacename="">' + JsCommonMsg.AnySubLocation + '</li>');
            }
        }
    });
}

function PrepareToSubPlaceSelector(productId, productType) {
    $('#selectedToSubPlace_' + productType).html(JsCommonMsg.AnySubLocation);
    $('#hdnTSP_' + productType).val('0');
    $('#hdnTSPU_' + productType).val('');
    $('#selectedToSubPlace_' + productType).parent().addClass('disabled');

    $('#destinationAdvancedMode_' + productType).attr('data-subplaceid', 0);

    var _toCountryId = parseInt($('#hdnTC_' + productType).val());
    var _toPlaceId = parseInt($('#hdnTP_' + productType).val());
    var _toPlaceUniqueName = $('#hdnTPU_' + productType).val();

    if (parseInt($('#hdnTC_' + productType).val()) != 0) {
        var params =
        {
            "productId": productId,
            "fromCountryId": parseInt($('#hdnFC_' + productType).val()),
            "fromPlaceId": parseInt($('#hdnFP_' + productType).val()),
            "toCountryId": parseInt($('#hdnTC_' + productType).val()),
            "toPlaceId": parseInt($('#hdnTP_' + productType).val()),
            "fromSubPlaceId": parseInt($('#hdnFSP_' + productType).val())
        };

        $.ajax({
            dataType: "json",
            url: "/api/place/subplace_only",
            data: params,
            beforeSend: function () {
                $('#selectedToSubPlace_' + productType).parent().siblings('.loading-spinner').show();
            },
            complete: function () {
                $('#selectedToSubPlace_' + productType).parent().siblings('.loading-spinner').hide();
            },
            success: function (data) {
                var subplaceItemWrapper = $('<ol class="flyout-group clearfix"/>');
                if (data.length > 0) {
                    $.each(data, function (i, subplace) {
                        subplaceItemWrapper.append('<li class="place flyout-item" data-countryid="' + subplace.ctid + '" data-countryname="' + subplace.ctn + '" default-countryname="' + subplace.dctn + '" data-placeid="' + subplace.pid + '" data-placename="' + subplace.pn + '" default-placename="' + subplace.pn + '" data-subplaceid="' + subplace.spid + '" data-subplacename="' + subplace.spn + '" default-subplacename="' + subplace.spn + '" data-uniqueplacename="' + subplace.pusn + '" data-uniquesubplacename="' + subplace.spusn + '" title="' + subplace.spn + '">' + subplace.spn + '</li>');
                    });
                    $('#selectedToSubPlace_' + productType).parent().removeClass('disabled');
                    $('#toSubPlaceDropdown_' + productType).empty();
                    $('#toSubPlaceDropdown_' + productType).append(subplaceItemWrapper);
                    subplaceItemWrapper.children().sort(SortByContent) // sort elements
                                              .appendTo(subplaceItemWrapper);

                    subplaceItemWrapper.prepend('<li class="place flyout-item" data-countryid="' + data[0].ctid + '" data-countryname="' + data[0].ctn + '" default-countryname="' + data[0].dctn + '" data-placeid="' + data[0].pid + '" data-placename="' + data[0].pn + '" default-placename="' + data[0].pn + '" data-subplaceid="0" data-subplacename="" default-subplacename="" data-uniqueplacename="' + data[0].pusn + '" data-uniquesubplacename="">' + JsCommonMsg.AnySubLocation + '</li>');
                }
                else {
                    subplaceItemWrapper.append('<li class="place flyout-item" data-countryid="' + _toCountryId + '" data-countryname="" default-countryname="" data-placeid="' + _toPlaceId + '" data-placename="" default-placename="" data-subplaceid="0" data-subplacename="" default-subplacename="" data-uniqueplacename="' + _toPlaceUniqueName + '" data-uniquesubplacename="">' + JsCommonMsg.AnySubLocation + '</li>');
                }
            }
        });
    }

}

function TriggerShakeAnimation(target) {
    target.addClass("error-shake");
    setTimeout(function () { target.removeClass("error-shake") }, 300);
}

function SortByContent(a, b) {
    return ($(b).html()) < ($(a).html()) ? 1 : -1;
}

function SortByCountryIdAttr(a, b) {
    return ($(b).data('countryid')) < ($(a).data('countryid')) ? 1 : -1;
}

function ResetLocationError(bus, ferry, train) {

    $('a[href="#bus-search-box"]').unbind().click(function () {
        $('#locationError_' + bus).text('');
        $('#locationError_' + ferry).text('');
        $('#locationError_' + train).text('');
    });

    $('a[href="#ferry-search-box"]').unbind().click(function () {
        $('#locationError_' + bus).text('');
        $('#locationError_' + ferry).text('');
        $('#locationError_' + train).text('');
    });

    $('a[href="#train-search-box"]').unbind().click(function () {
        $('#locationError_' + bus).text('');
        $('#locationError_' + ferry).text('');
        $('#locationError_' + train).text('');
    });


}







;
