/// <reference name="MicrosoftAjax.js" />
/// <reference name="dnn.js" assembly="DotNetNuke.WebUtility" />
/// <reference name="dnn.xmlhttp.js" assembly="DotNetNuke.WebUtility" />

///Type.registerNamespace('Vios');
///Vios.ViewSearchModule.registerClass('Vios.ViewSearchModule', Sys.Component);


Type.registerNamespace('Vios');

Vios.ViewSearchModule = function () {
    //Call Base Method
    Vios.ViewSearchModule.initializeBase(this);

    //Member Variables
    this._msgs = {};
    this._settings = {};
    this._helloButton = null;

    //Associated delegates to single member variable dictionary to make it easy to dispose
    this._delegates = {
        _helloSuccessDelegate: Function.createDelegate(this, this._helloSuccess),
        _helloFailDelegate: Function.createDelegate(this, this._helloFail),
        _onLoadDelegate: Function.createDelegate(this, this._onLoad),
        _PropertySearchDelegate: Function.createDelegate(this, this._tbSearchProperty),
        componentPropChangedDelegate: Function.createDelegate(this, this._onPropChanged),
        _propertySearchResultDelegete: Function.createDelegate(this, this._searchResultsControl),
        _ajaxSuccess: Function.createDelegate(this, this._ajaxSuccess02)

    };

    //Event Hookup
    Sys.Application.add_load(this._delegates._onLoadDelegate);
}

Vios.ViewSearchModule.prototype =
{
    //Properties
    get_ns: function () { return this.get_id() + '_'; },
    get_msgs: function () { return this._msgs; },
    set_msgs: function (value) { this._msgs = value; },
    get_settings: function () { return this._settings; },
    set_settings: function (value) { this._settings = value; },
    get_name: function () {
        return $get(this.get_ns() + 'lblName').innerHTML;
    },
    get_description: function () {
        return $get(this.get_ns() + 'lblDesc').innerHTML;
    },

    //Events
    initialize: function () {
        //Call Base Method    
        Vios.ViewSearchModule.callBaseMethod(this, 'initialize');

        //hookup event handlers
        $addHandlers(document.getElementById(this.get_ns() + 'rbSale'), { "click": this._saletransaction }, this);
        $addHandlers(document.getElementById(this.get_ns() + 'rbRent'), { "click": this._renttransaction }, this);
        $addHandlers(document.getElementById(this.get_ns() + 'txTown'), { "focus": this._townfocus }, this);
        $addHandlers(document.getElementById(this.get_ns() + 'txTown'), { "keyup": this._townsuggestion }, this);
        $addHandlers(document.getElementById(this.get_ns() + 'dvDropDown'), { "change": this._fill02 }, this);

        $addHandlers(document.getElementById(this.get_ns() + 'ddlSearchCountry'), { "change": this._ddlSearchCountry }, this);

        //create UI
        var txTownHlp = this.getMessage('txTown')
        if (txTownHlp != null) {
            var txTown = document.getElementById(this.get_ns() + 'txTown');
            if (txTown != null) {
                txTown.value = txTownHlp;
                txTown.style.color = this.getSetting('TownColor', '#888888');
            }
        }


        //create UI
        this._helloButton = this._createChildControl('btnHello', 'input', 'button');
        this._helloButton.value = this.getMessage('btnHello'); //get localized value
        $get(this.get_ns() + 'lblName').parentNode.appendChild(this._helloButton);



        //hookup event handlers
        //        $addHandlers(document.getElementById(this.get_ns() + 'tbSearch'), { "mouseover": this._tbSearchmouseover }, this);
        //        $addHandlers(document.getElementById(this.get_ns() + 'tbSearch'), { "mouseout": this._tbSearchmouseout }, this);

        //        $addHandlers(document.getElementById('tbSearch'), { "mouseover": this._tbSearchmouseover }, this);
        //        $addHandlers(document.getElementById('tbSearch'), { "mouseout": this._tbSearchmouseout }, this);

        var objHlp = $('#tbSearch');
        if (objHlp != null) {
            $('#tbSearch').mouseover(this._tbSearchmouseover);
            $('#tbSearch').mouseout(this._tbSearchmouseout);
            $('#tbSearch').click(this._delegates._PropertySearchDelegate);
        }

        $addHandlers(document.getElementById(this.get_ns() + 'imgSearch'), { "mouseover": this._imgSearchmouseover }, this);
        $addHandlers(document.getElementById(this.get_ns() + 'imgSearch'), { "mouseout": this._imgSearchmouseout }, this);


        $addHandlers(this._helloButton, { "click": this._onHello }, this);

        $addHandlers(document.getElementById(this.get_ns() + 'ImageButton2'), { "click": this._clearform }, this);

        $addHandlers(document.getElementById(this.get_ns() + 'ImageButton1'), { "mouseover": this._ImageButton1mouseover }, this);
        $addHandlers(document.getElementById(this.get_ns() + 'ImageButton1'), { "mouseout": this._ImageButton1mouseout }, this);
        $addHandlers(document.getElementById(this.get_ns() + 'ImageButton2'), { "mouseover": this._ImageButton2mouseover }, this);
        $addHandlers(document.getElementById(this.get_ns() + 'ImageButton2'), { "mouseout": this._ImageButton2mouseout }, this);
    },

    _ddlSearchCountry: function (src, arg) {
        //alert('selector changed');
        var dropdownSelector = src.target;

        var szCountrySearch = dropdownSelector.options[dropdownSelector.selectedIndex].text;
        if (szCountrySearch != "Select Country") {
            var lbCountryid = '#' + document.getElementById(this.get_ns() + 'lbCountry').id;
            if (lbCountryid != null) {
                $(lbCountryid).html(szCountrySearch);
            }
        }
    },

    _fill03: function () {

        var szCountrySearch = this.getSetting('txInitialCountry', 'UK');
        var szTownSearch = "";

        //Get the id of the selector and the input fields
        var dropdownSeletorid = document.getElementById(this.get_ns() + 'dvDropDown').id
        var txTownid = '#' + document.getElementById(this.get_ns() + 'txTown').id;
        szTownSearch = $(txTownid)[0].value;

        //Get the id of the search fields
        lbcountrysearchid = '#' + document.getElementById(this.get_ns() + 'lbCountrySearch').id;
        txtownsearchid = '#' + document.getElementById(this.get_ns() + 'txTownSearch').id;

        //Set the selected value
        //$(txTownid).attr("value", szTownSearch);
        $(lbcountrysearchid).html(szCountrySearch);
        $(txtownsearchid).html(szTownSearch);

        //Hide the selector
        hlp02 = '#' + dropdownSeletorid;
        $(hlp02).hide();

        //Show the imagebutton ImageButton1
        imagebutton1id = '#' + document.getElementById(this.get_ns() + 'imgSearch').id;
        $(imagebutton1id).show();

        //Display the search results for this town
        $('#tbSearch').click();
    },

    _fill02: function (src, arg) {
        //alert('selector change');

        //debugger;

        var nPos = -1;
        var szTownSearch = "";
        var szCountrySearch = this.getSetting('txInitialCountry', 'UK'); ;

        //Get the selected option
        var dropdownSelector = src.target;
        if (dropdownSelector != null) {
            var szTown = dropdownSelector.options[dropdownSelector.selectedIndex].text;
            //nPos = szTown.indexOf(" (");
            nPos = szTown.indexOf(", ");
            if (nPos != -1) {
                szTownSearch = szTown.substring(0, nPos);
                szCountrySearch = szTown.substring(nPos);

                //                szCountrySearch = szCountrySearch.replace(" (", "");
                //                szCountrySearch = szCountrySearch.replace(")", "");

                szCountrySearch = szCountrySearch.replace(", ", "");

                //Get the city only
                nPos = -1;
                nPos = szCountrySearch.indexOf(",");
                if (nPos != -1) {
                    szTownSearch = szCountrySearch.substring(0, nPos);
                }
                else {
                    //szTownSearch = szCountrySearch;
                }
            }
            else {
                nPos = -1;
                nPos = szTown.indexOf(" (");
                if (nPos != -1) {
                    szTownSearch = szTown.substring(0, nPos);
                }
                else {
                    szTownSearch = szTown;
                }
            }
        }

        if (szTownSearch != "Select Town") {

            //Get the id of the selector and the input fields
            var dropdownSeletorid = dropdownSelector.id;
            var txTownid = '#' + document.getElementById(this.get_ns() + 'txTown').id;

            //Get the id of the search fields
            lbcountrysearchid = '#' + document.getElementById(this.get_ns() + 'lbCountrySearch').id;
            txtownsearchid = '#' + document.getElementById(this.get_ns() + 'txTownSearch').id;

            //Set the selected value
            $(txTownid).attr("value", szTownSearch);
            $(lbcountrysearchid).html(szCountrySearch);
            $(txtownsearchid).html(szTownSearch);

            //Hide the selector
            hlp02 = '#' + dropdownSeletorid;
            $(hlp02).hide();

            //Show the imagebutton ImageButton1
            imagebutton1id = '#' + document.getElementById(this.get_ns() + 'imgSearch').id;
            $(imagebutton1id).show();

            //Display the search results for this town
            $('#tbSearch').click();
        }
    },

    _townsuggestion: function (src, arg) {

        src.preventDefault();

        //alert('_townsuggestion');
        //debugger;

        //Get the ids for the required controls
        var szCountry = document.getElementById(this.get_ns() + 'lbCountry').innerHTML;
        var szServiceUrl = document.getElementById(this.get_ns() + 'lbClientUrl').innerHTML;
        var inputString = src.target.value;

        //Hide the imagebutton
        var imgSearchid = document.getElementById(this.get_ns() + 'imgSearch').id;
        $('#' + imgSearchid).hide();

        //Show the dropdown control
        var dvDropDownid = document.getElementById(this.get_ns() + "dvDropDown").id;
        $('#' + dvDropDownid).show();

        if (inputString.length == 0) {
            //Do nothing
            if (src.keyCode == '13') {
            }
        }
        else {
            //Get data from server
            if (src.keyCode == '13') {
                //debugger;
                //Display the search results
                this._fill03();
            }
            var nCount = 10;
            if (szServiceUrl != "") {
                this._callWebService02(szCountry, inputString, nCount, szServiceUrl);
            }
        }

    },

    _callWebService02: function (szCountry, szTown, nCount, szserviceUrl) {
        //alert('_callWebService02 with: ' + szserviceUrl + ' ' + szCountry + ' ' + szTown + ' ' + nCount);


        $.ajax({
            type: "POST",
            //url: "../Portals/_default/XModPro/PptControls/PropertiesbyCountry.asmx/GetCompletionList04",
            //url: "../../Portals/_default/XModPro/PptControls/PropertiesbyCountry.asmx/GetCompletionList04",
            url: szserviceUrl,
            data: "{'szCountry':'" + szCountry + "', 'szTownPrefix':'" + szTown + "', 'nCount':'" + nCount + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: this._ajaxError,
            //success: this._ajaxSuccess02
            success: this._delegates._ajaxSuccess
        });
    },

    _ajaxError: function (XMLHttpRequest, textStatus, errorThrown) {
        var szMsg = textStatus + ' ' + XMLHttpRequest.responseText;
        alert(szMsg);
    },


    _ajaxSuccess02: function (msg) {
        //Get the values for the select
        var szOptions = msg.d;

        //        alert(msg.d);
        //        this;

        //Delete old data
        var dropdownHlpid = '#' + document.getElementById(this.get_ns() + "dvDropDown").id;
        var dropdownHlp = $(dropdownHlpid);
        dropdownHlp[0].options.length = 0

        // Split at each ; character.
        var ss = szOptions.split(";");
        var nLen = ss.length;

        //Add new options
        this._insertOption(dropdownHlpid.substring(1), "Select Town", 1);
        for (var nPos in ss) {
            if (ss[nPos] != "") {
                this._insertOption(dropdownHlpid.substring(1), ss[nPos], 0);
            }
        }

    },

    _insertOption: function (ddlTownid, optionValue, selected) {
        //Create the option
        var y = document.createElement('option');
        y.text = optionValue;

        // Add it to the select tag
        var x = document.getElementById(ddlTownid);
        if (x != null) {

            //Add attributes 
            if (selected == 1) {
                y.setAttribute("selected", "selected");
            }

            try {
                x.add(y, null); // standards compliant
            }
            catch (ex) {
                x.add(y); // IE only
            }
        }
    },

    _townfocus: function (src, arg) {
        if (src != null) {
            var txTown = src.target;
            txTown.value = "";
            txTown.style.color = "";
        }
    },

    _saletransaction: function (src, arg) {

        //src.preventDefault();
        var rdButton = src.target;
        if (rdButton.checked) {
            var rdButtonRent = document.getElementById(this.get_ns() + 'rbRent');
            rdButtonRent.checked = false;
        }

        //Clear the controls
        //this.showMessage('Clear was clicked in the client side');
    },

    _renttransaction: function (src, arg) {

        //src.preventDefault();
        var rdButton = src.target;
        if (rdButton.checked) {
            var rdButtonSale = document.getElementById(this.get_ns() + 'rbSale');
            rdButtonSale.checked = false;
        }

        //Clear the controls 
        //this.showMessage('Clear was clicked in the client side');
    },

    _tbSearchProperty: function (src, arg) {
        var szUrl = "";
        var szSearchID = "";
        var szResultsID = "";
        var szPropertyType = "";
        var szTransaction = "";
        var szCountry = "";
        var szTown = "";
        var szMsg = "";
        var hlpID = "";

        //Get the serachid
        hlpID = '#' + document.getElementById(this.get_ns() + 'lbSearchId').id;
        if (hlpID != null) {
            szSearchID = $(hlpID).html();
        }

        //Get the url
        hlpID = '#' + document.getElementById(this.get_ns() + 'lbResultsTabid').id;
        if (hlpID != null) {
            szUrl = $(hlpID).html();
        }

        //Get the property type
        hlpID = '#' + document.getElementById(this.get_ns() + 'lbCategoryID').id;
        if (hlpID != null) {
            szPropertyType = $(hlpID).html();
        }

        //Get the transaction
        var rdButtonRent = document.getElementById(this.get_ns() + 'rbRent');
        if (rdButtonRent != null) {
            if (rdButtonRent.checked) {
                szTransaction = "Rent";
            }
            else {
                szTransaction = "Purchase";
            }
        }

        //Get the city
        hlpID = '#' + document.getElementById(this.get_ns() + 'lbCountry').id;
        if (hlpID != null) {
            szCountry = $(hlpID).html();
        }

        //Get the town
        var txTownHlp = this.getMessage('txTown');
        hlpID = '#' + document.getElementById(this.get_ns() + 'txTown').id;
        if (hlpID != null) {
            szTown = $(hlpID).attr("value");
            if (szTown == "" || szTown == txTownHlp) {
                hlpID = '#' + document.getElementById(this.get_ns() + 'lbMsg').id
                if (hlpID != null) {
                    $(hlpID).html("Please supply the town or postal code");
                }
                return;
            }
        }

        //Get the search results control using a web service
        var szserviceUrl = document.getElementById(this.get_ns() + 'lbClientUrl').innerHTML;
        szserviceUrl = szserviceUrl.replace("GetCompletionList04", "SearchPropertyResults");
        $.ajax({
            type: "POST",
            url: szserviceUrl,
            data: "{'szCategoryID':'" + szPropertyType + "', 'szTransactionType':'" + szTransaction + "', 'szSearchCountry':'" + szCountry + "', 'szTownZip':'" + szTown + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: this._ajaxError,
            success: this._delegates._propertySearchResultDelegete
        });

    },

    _searchResultsControl: function (msg) {
        //Display the error or call the web site for the search results
        var szOptions = msg.d;
        //        alert(msg.d);
        //        this;

        var szUrl = "";
        var szSearchID = "";
        var szResultsnID = "";
        var szResultsID = "";
        var szPropertyType = "";
        var szTransaction = "";
        var szCountry = "";
        var szTown = "";
        var szMsg = "";
        var hlpID = "";

        if (msg.d != "True") {
            hlpID = '#' + document.getElementById(this.get_ns() + 'lbMsg').id
            if (hlpID != null) {
                $(hlpID).html(msg.d);
            }
        }
        else {
            //Get the serachid
            hlpID = '#' + document.getElementById(this.get_ns() + 'lbResultsnTabid').id;
            if (hlpID != null) {
                szResultsnID = $(hlpID).html();
            }

            hlpID = '#' + document.getElementById(this.get_ns() + 'lbSearchId').id;
            if (hlpID != null) {
                szSearchID = $(hlpID).html();
            }

            //Get the url
            hlpID = '#' + document.getElementById(this.get_ns() + 'lbResultsTabid').id;
            if (hlpID != null) {
                szUrl = $(hlpID).html();
            }

            //Get the property type
            hlpID = '#' + document.getElementById(this.get_ns() + 'lbCategoryID').id;
            if (hlpID != null) {
                szPropertyType = $(hlpID).html();
                //                if (szPropertyType == "1") {
                //                    szPropertyType = "Residential";
                //                }

                switch (szPropertyType) {
                    case "1":
                        szPropertyType = "Residential";
                        break;
                    case "2":
                        szPropertyType = "Commercial";
                        break;
                    case "3":
                        szPropertyType = "Agriculture";
                        break;
                    default:
                        szPropertyType = "Residential";
                        break;
                }

            }

            //Get the transaction
            var rdButtonRent = document.getElementById(this.get_ns() + 'rbRent');
            if (rdButtonRent != null) {
                if (rdButtonRent.checked) {
                    szTransaction = "Rent";
                }
                else {
                    szTransaction = "Purchase";
                }
            }

            //Get the city
            hlpID = '#' + document.getElementById(this.get_ns() + 'lbCountry').id;
            if (hlpID != null) {
                szCountry = $(hlpID).html();
            }

            //Get the town
            var txTownHlp = this.getMessage('txTown');
            hlpID = '#' + document.getElementById(this.get_ns() + 'txTown').id;
            if (hlpID != null) {
                szTown = $(hlpID).attr("value");
                if (szTown == "" || szTown == txTownHlp) {
                    hlpID = '#' + document.getElementById(this.get_ns() + 'lbMsg').id
                    if (hlpID != null) {
                        $(hlpID).html("Please supply the town or postal code");
                    }
                    return;
                }
            }

            //Call the web site
            szMsg = "/tabid/" + szResultsnID + "/PropertyType/" + szPropertyType + "/Transaction/" + szTransaction + "/Country/" + szCountry + "/TownZip/" + szTown + "/SearchId/" + szSearchID + "/Default.aspx";
            szUrl = szUrl.replace(".aspx", szMsg);
            if (szUrl != null) {
                window.open(szUrl, "_self");
            }
        }
    },

    _tbSearchmouseover: function (src, arg) {
        var dropdownSelector = src.target;
        dropdownSelector.className = 'tbl_B';
    },

    _tbSearchmouseout: function (src, arg) {
        var dropdownSelector = src.target;
        dropdownSelector.className = 'tbl_A';
    },

    _imgSearchmouseover: function (src, arg) {
        var dropdownSelector = src.target;
        dropdownSelector.className = 'SearchResidentialButtonhover';
    },

    _imgSearchmouseout: function (src, arg) {
        var dropdownSelector = src.target;
        dropdownSelector.className = 'SearchResidentialButton';
    },


    _ImageButton1mouseover: function (src, arg) {
        var dropdownSelector = src.target;
        dropdownSelector.className = 'SearchResidentialPropertySendButtonhover';
    },

    _ImageButton1mouseout: function (src, arg) {
        var dropdownSelector = src.target;
        dropdownSelector.className = 'SearchResidentialPropertySendButton';
    },

    _ImageButton2mouseover: function (src, arg) {
        var dropdownSelector = src.target;
        dropdownSelector.className = 'SearchResidentialPropertyClearButtonhover';
    },

    _ImageButton2mouseout: function (src, arg) {
        var dropdownSelector = src.target;
        dropdownSelector.className = 'SearchResidentialPropertyClearButton';
    },

    _clearform: function (src, arg) {

        src.preventDefault();

        //Clear the controls
        this.showMessage('Clear was clicked in the client side');
    },

    _onLoad: function (src, arg) {
        //page is completely loaded, you can now access any element or component
        var components = arg.get_components();
        //sample of how to do client-side IMC - look for other components we are interested in
        //in this case, we will look for other instances of the same module that are not ourselves
        //but you can communicate with any components
        for (var i = 0; i < components.length; i++) {
            if (Object.getTypeName(components[i]) == Object.getTypeName(this) && components[i].get_id() != this.get_id())
                this.add_propertyChanged(components[i]._delegates.componentPropChangedDelegate);
        }
    },

    _onHello: function (src, arg) {
        this._displayWait(true);
        dnn.xmlhttp.callControlMethod('Vios.Modules.SearchResidentialProperty.ViewSearchModule.' + this.get_id(),
            'Hello', { Name: this.get_name(), Description: this.get_description() }, this._delegates._helloSuccessDelegate, this._delegates._helloFailDelegate);

        this.raisePropertyChanged('SayHello');
    },

    _onPropChanged: function (src, args) {
        this.showMessage(String.format('You {0} to {1} but not to me?', args.get_propertyName(), src.get_name()));
    },

    //Methods
    getMessage: function (key) {
        return this._msgs[key];
    },

    showMessage: function (msg) {
        $get(this.get_ns() + 'lblResponse').innerHTML = msg;
    },


    getSetting: function (key, def) {
        if (this._settings[key])
            return this._settings[key];
        return def;
    },


    //Private Methods
    _createChildControl: function (id, tag, type) {
        var ctl = document.createElement(tag);
        ctl.id = this.get_ns() + id;
        if (type)
            ctl.type = type;
        return ctl;
    },

    _displayWait: function (show) {
        $get(this.get_ns() + 'imgAjax').className = (show ? '' : 'ceHidden');
    },

    _helloSuccess: function (payload, ctx, req) {
        this._displayWait(false);
        this.showMessage(payload);
    },

    _helloFail: function (payload, ctx, req) {
        this._displayWait(false);
        alert('error: ' + payload);
    },

    dispose: function () {
        $clearHandlers(this._helloButton);
        this._helloButton = null;
        this._delegates = null;
        Vios.ViewSearchModule.callBaseMethod(this, 'dispose');
    }
}

//register class and inherit from Sys.Component
Vios.ViewSearchModule.registerClass('Vios.ViewSearchModule', Sys.Component);

