﻿var _baseUrl = "Service/TSIService.svc/";
var timer1;

function loadjscssfile(filename, filetype) {
    if (filetype == "js") { //if filename is a external JavaScript file
        var fileref = document.createElement('script')
        fileref.setAttribute("type", "text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype == "css") { //if filename is an external CSS file
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

function Search(_page) {

    BeforeSearch();

    //Declare Values
    var _keywords = "";
    var _phone = "";
    var _vat = "";
    var _country = "";
    var _province = "";
    var _town = 0;
    var Noresultstxt = $("#Noresultstxt").val();

    //Assign values to Members
    _keywords = $("#WhatWhoCtl").val();
    _phone = $("#TelNoCtl").val();
    _vat = $("#VatNoCtl").val();
    _country = $("#CountryRadioBtn").val();
    _province = $("#provincectl").val();
    _town = $("#townctl").val();
    _languagecode = $("#LanguageCtl").val();
    // This part gets the IP
    var _ip = $("#IPAddCtl").val();

    var _domain = fnGetDomain(document.URL);

   

    if ($("input[@name=whereOptns]:checked").attr('id') == "ProvinceRadioBtn") {
        _town = 0;
    }

    // Load JSON for <IE8.
    if (!this.JSON) {
        LoadJsonIE7();
    }

    //Call Json Ajax
    $.ajax({
        url: _baseUrl + "Search",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ Keywords: _keywords, Phone: _phone, Vat: _vat, Country: _country, Province: _province, Town: _town, Page: _page }),
        processdata: true,
        dataType: "json",
        async: true,
        success: function (msg) { AfterSearch(msg, _page); },
        error: function (xhr, ajaxOptions, thrownError) { //$("#results").html(xhr.responseText);             
            $("#results").html(Noresultstxt + "<b> '" + GetQuery() + '</b>" ');
        }
    });

    //Call Json Ajax
    $.ajax({
        url: _baseUrl + "SearchTracker_C",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ IPAddress: _ip, DomainUrl: _domain, Keyword: _keywords, Phone: _phone, VatNumber: _vat, CountryCode: _country, Province_Id: _province, Town_Id: _town, City: '', Page: _page, LanguageCode: _languagecode, Header: '', InsertBy: 0 }),
        processdata: true,
        dataType: "json",
        async: true
    });

    GetLeftBanners();
}

 function fnGetDomain(url) {
return (url);
}
function BeforeSearch() {
    $("#results").css("background-color", "");
    $("#results").css("border", "");
    document.getElementById("resultsContainer").style.visibility = "visible";
    document.getElementById("resultsContainer").style.display = "block";

    $("#results").html('<div style="padding-left:35%;padding-top:5%;"><img alt="loading..." src="Images/loadingAnimation.gif" /></div>');

}

String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
    var temp = this;
    var index = temp.indexOf(stringToFind);
    while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
    }
    return temp;
}

function GetQuery() {
    var searchQuery = "";

    if ($("#WhatWhoCtl").val() != "") {
        searchQuery = $("#WhatWhoCtl").val();
    }
    else if ($("#TelNoCtl").val() != "") {
        searchQuery = $("#TelNoCtl").val();
    }
    else if ($("#VatNoCtl").val() != "") {
        searchQuery = $("#VatNoCtl").val();
    }

    return searchQuery;

}

function PagingModule(searchType, searchresults, currentPage) {



    //Display Total No of Records
    if (searchresults['d']['totalResultsAvailable'] != undefined) {
        var resultCount = searchresults['d']['totalResultsAvailable'];
        var recordsPerPage = searchresults['d']['recordsPerPage'];
        var AboutTxt = $("#AboutTxt").val();
        var resultsfortxt = $("#resultsfor").val();


        $("#NoOfWordsCtl").html(AboutTxt + " <b>'" + resultCount + "'</b> " +resultsfortxt+" <b>' " + GetQuery() + "'</b>");

        if (parseInt(resultCount) > parseInt(recordsPerPage)) {

            var pages = Math.ceil(resultCount / recordsPerPage);
            var NavigationLinks = "";
            var startPage = 1;
            var endPage = 10;
            var Backtxt = $("#BackTxt").val();
            var Nexttxt = $("#NextTxt").val();

            //Back Link
            if (currentPage > 1 ) {
                if (searchType == "site") {
                    NavigationLinks = "<a href='javascript:Search(" + parseInt(currentPage - 1) + ")'><b>" + Backtxt + "</b></a>&nbsp;&nbsp;" + NavigationLinks;
                }
                else if (searchType == "web") {
                    NavigationLinks = "<a href='javascript:GetWebSearch(" + parseInt(currentPage - 1) + ")'><b>" + Backtxt + "</b></a>&nbsp;&nbsp;" + NavigationLinks;
                }
            }

            if (pages > 10) {
                if (currentPage > 1) {
                    startPage = currentPage;
                    endPage = endPage + currentPage - 1;
                }
            }
            else {
                endPage = pages;
            }

            //Middle Links
            for (startPage; startPage <= endPage; startPage++) {
                if (currentPage != startPage) {
                    if (searchType == "site") {
                        NavigationLinks = NavigationLinks + "<a href='javascript:Search(" + startPage + ")'>" + startPage + "</a>&nbsp;&nbsp;";
                    }
                    else if (searchType == "web") {
                        NavigationLinks = NavigationLinks + "<a href='javascript:GetWebSearch(" + startPage + ")'>" + startPage + "</a>&nbsp;&nbsp;";
                    }
                }
                else {
                    NavigationLinks = NavigationLinks + startPage + "&nbsp;&nbsp;";
                }

            }

            //next Link 
            if (!searchresults['d']['isLastPage']) {
                
                if (searchType == "site") {
                    NavigationLinks = NavigationLinks + "&nbsp; <a href='javascript:Search(" + parseInt(currentPage + 1) + ")'><b>" + Nexttxt + "</b></a>&nbsp;" 
                }
                else if (searchType == "web") {
                    NavigationLinks = NavigationLinks + "&nbsp; <a href='javascript:GetWebSearch(" + parseInt(currentPage + 1) + ")'><b>" + Nexttxt + "</b></a>&nbsp;";
                }
            }

            $('#TopLinks').html('<b> ' + NavigationLinks + '</b>');
            $('#BottomLinks').html('<b> ' + NavigationLinks + '</b>');

        }
        else {
            $('#TopLinks').html('<b>Page: 1 </b>');
            $('#BottomLinks').html('<b>Page: 1 </b>');
        }
    }

}

function AfterSearch(searchresults, currentPage) {

    var companyIds = "";

    $('#TopLinks').html('');
    $('#BottomLinks').html('');
    $("#centerDiv").css("margin-left", "0px");
    $("#centerDiv").css("width", "69%");
    var clckhertxt = $("#Clickheretxt").val();
    var Websearchtxt = $("#Websearchtxt").val();
    var Noresultstxt = $("#Noresultstxt").val();
    var enIntlSearch = $("#enableIntlSearch").val();

    if (searchresults["d"]["SearchResult"] != null && searchresults['d']["SearchResult"][0] != undefined) {

        PagingModule("site", searchresults, currentPage);
        $("#findinfodiv").css("display", "block");
        $("#findinfodiv").css("visibility", "visible");
        //Format the Collection
        $.each(searchresults["d"]["SearchResult"], function (index, value) {

            companyIds = companyIds + searchresults["d"]["SearchResult"][index]["Company_Id"] + "- " + searchresults["d"]["SearchResult"][index]["IsStatisticsValid"] + ",";
            if (searchresults["d"]["SearchResult"][index]["IsLogoValid"] == false || searchresults["d"]["SearchResult"][index]["LogoPath"] == "" || searchresults["d"]["SearchResult"][index]["LogoPath"] == null) {
                searchresults["d"]["SearchResult"][index]["IsLogoValid"] = "display:none;visibility:hidden";
            }
            else if (searchresults["d"]["SearchResult"][index]["IsLogoValid"] == true && searchresults["d"]["SearchResult"][index]["LogoPath"] != "" || searchresults["d"]["SearchResult"][index]["LogoPath"] != null) {
                searchresults["d"]["SearchResult"][index]["LogoPath"] = searchresults["d"]["SearchResult"][index]["LogoPath"].replace('~/', '');
            }

            if (searchresults["d"]["SearchResult"][index]["IsPhoneValid"] == false || searchresults["d"]["SearchResult"][index]["Phone"] == "" || searchresults["d"]["SearchResult"][index]["Phone"] == null) {
                searchresults["d"]["SearchResult"][index]["IsPhoneValid"] = "display:none;visibility:hidden";
            }

            if (searchresults["d"]["SearchResult"][index]["IsEmailValid"] == false || searchresults["d"]["SearchResult"][index]["Email"] == "" || searchresults["d"]["SearchResult"][index]["Email"] == null) {
                searchresults["d"]["SearchResult"][index]["IsEmailValid"] = "display:none;visibility:hidden";
            }

            if (searchresults["d"]["SearchResult"][index]["IsMobileValid"] == false || searchresults["d"]["SearchResult"][index]["Mobile"] == "" || searchresults["d"]["SearchResult"][index]["Mobile"] == null) {
                searchresults["d"]["SearchResult"][index]["IsMobileValid"] = "display:none;visibility:hidden";
            }

            if (searchresults["d"]["SearchResult"][index]["IsFaxValid"] == false || searchresults["d"]["SearchResult"][index]["Fax"] == "" || searchresults["d"]["SearchResult"][index]["Fax"] == null) {
                searchresults["d"]["SearchResult"][index]["IsFaxValid"] = "display:none;visibility:hidden";
            }

            if (searchresults["d"]["SearchResult"][index]["IsWebsiteValid"] == false || searchresults["d"]["SearchResult"][index]["Website"] == "" || searchresults["d"]["SearchResult"][index]["Website"] == null) {
                searchresults["d"]["SearchResult"][index]["IsWebsiteValid"] = "display:none;visibility:hidden";
            }

            if (searchresults["d"]["SearchResult"][index]["IsMinisiteValid"] == false || searchresults["d"]["SearchResult"][index]["Minisite"] == "" || searchresults["d"]["SearchResult"][index]["Minisite"] == null) {
                searchresults["d"]["SearchResult"][index]["IsMinisiteValid"] = "display:none;visibility:hidden";
            }

            if (searchresults["d"]["SearchResult"][index]["IsSuperBonusValid"] == false || searchresults["d"]["SearchResult"][index]["CompanyType"] == "B2B" || searchresults["d"]["SearchResult"][index]["CompanyType"] == "NHL" || searchresults["d"]["SearchResult"][index]["CompanyType"] == "HLP") {
                searchresults["d"]["SearchResult"][index]["IsSuperBonusValid"] = "display:none;visibility:hidden";
            }

            //            if (searchresults["d"]["SearchResult"][index]["IsBonusValid"] == false || searchresults["d"]["SearchResult"][index]["CompanyType"] == "B2B") {
            //                searchresults["d"]["SearchResult"][index]["IsBonusValid"] = "display:none;visibility:hidden";
            //            }

            //B2C
            if (searchresults["d"]["SearchResult"][index]["CompanyType"] == "B2C") {
                searchresults["d"]["SearchResult"][index]["IsNoPublic"] = 'Images/CompanyTypeImages/B2C.png';     
              searchresults["d"]["SearchResult"][index]["CompanyType"] = $("#B2CNopublictext").val();
              

            }
            // BCC
            else if (searchresults["d"]["SearchResult"][index]["CompanyType"] == "BCC") {
                searchresults["d"]["SearchResult"][index]["IsNoPublic"] = 'Images/CompanyTypeImages/BCC.png';
                searchresults["d"]["SearchResult"][index]["CompanyType"] = $("#BCCNopublictext").val();
            }
            //B2B
            else if (searchresults["d"]["SearchResult"][index]["CompanyType"] == "B2B") {
                searchresults["d"]["SearchResult"][index]["IsNoPublic"] = 'Images/CompanyTypeImages/B2B.png';
                searchresults["d"]["SearchResult"][index]["CompanyType"] = $("#B2BNopublictext").val();
            }
            //NHL
            else if (searchresults["d"]["SearchResult"][index]["CompanyType"] == "NHL") {
                searchresults["d"]["SearchResult"][index]["IsNoPublic"] = 'Images/CompanyTypeImages/square.png';
                searchresults["d"]["SearchResult"][index]["CompanyType"] = $("#NHLText").val();
            }
            //HLP
            else if (searchresults["d"]["SearchResult"][index]["CompanyType"] == "HLP"){
                searchresults["d"]["SearchResult"][index]["IsNoPublic"] = 'Images/CompanyTypeImages/heart.png';
                searchresults["d"]["SearchResult"][index]["CompanyType"] = $("#HLPText").val();
            }

            if (searchresults["d"]["SearchResult"][index]["IsFree"] == true) {
                searchresults["d"]["SearchResult"][index]["IsOrg"] = "display:none;visibility:hidden";
            }

            if (searchresults["d"]["SearchResult"][index]["StaffCount"] == 0) {
                searchresults["d"]["SearchResult"][index]["IsOrg"] = "display:none;visibility:hidden";
            }

            if (searchresults["d"]["SearchResult"][index]["PublicityText"] != "" || searchresults["d"]["SearchResult"][index]["PublicityText"] != null) {
                searchresults["d"]["SearchResult"][index]["PublicityText"] = searchresults["d"]["SearchResult"][index]["PublicityText"].ReplaceAll("_", "<br />");
            }

        });


        $("#results").html('');
        $('#searchTemplate').tmpl(searchresults["d"]["SearchResult"]).appendTo("#results");

        if (searchresults['d']['isLastPage']) {

            if (enIntlSearch == "y") {
                $("#results").append("<div style='text-align:center;'><a href='javascript:GetWebSearch(1);'>" + clckhertxt + "</a> " + Websearchtxt + "</div>");
            }

        }
       
        

        $("#contents img[title]").tooltip();
            $("#noPublicDiv img[title]").Nopublictooltip();
        $("#cid").val(companyIds);
        UpdateStatistics();

    }
    else {
        $("#NoOfWordsCtl").html('');
        $('#Links').html('');
        $("#results").html('');

        if (enIntlSearch == "y") {
            $("#results").html("<div style='text-align:center;'> <h2>" + Noresultstxt + " '<b>" + GetQuery() + "</b>'.</h2><a href='javascript:GetWebSearch(1);'>" + clckhertxt + "</a> " + Websearchtxt + "</div>");
        }
        else {
            $("#results").html("<div style='text-align:center;'> <h2>" + Noresultstxt + " '<b>" + GetQuery() + "</b>'.</h2></div>");
        }

        $("#websearchdiv").css("display", "none");
        $("#websearchdiv").css("visibility", "hidden");
        
        $("#findinfodiv").css("display", "none");
        $("#findinfodiv").css("visibility", "hidden");
    }
}

function UpdateStatistics() {
    var cids = $("#cid").val();

    $.ajax({
        url: _baseUrl + "StatisticsSearchResult",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ companyIds: cids }),
        processdata: true,
        dataType: "json",
        async: true
    });
}

function GetLocationInfo() {

    var _keywords = "";

    var _country = $("#CountryNameCtl").val();
    var _province = $("#provincectl option:selected").text();
    var _town = $("#townctl option:selected").text();

    if ($("#townctl").val() > 0) {
        _keywords = _town;
    }
    else if ($("#provincectl").val() > "0") {
        _keywords = _province;
    }
    else {
        // _keywords = _country;
    }
    return _keywords;
}

function GetWebSearch(_page) {

    var _keywords = GetQuery();
    GetLeftBanners();
    GetRightBanners();
    $("#ssRightContainer").css("display", "block");
    $("#ssRightContainer").css("visibility", "visible");
    $("#results").css("background-color", "");
    $("#results").css("border", "");

    $("#results").html('<div style="padding-left:35%;padding-top:5%;"><img alt="loading..." src="Images/loadingAnimation.gif" /></div>');

    $.ajax({
        url: _baseUrl + "GetYahooResult",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ query: _keywords, page: _page }),
        processdata: true,
        dataType: "json",
        async: true,
        success: function (msg) { ServiceSucceeded(msg, _page); },
        error: function (errMsg) { errorSever(errMsg) }
    });
}

function ServiceSucceeded(searchresults, _page) {
    $("#results").html('');
    $('#TopLinks').html('');
    $('#BottomLinks').html('');
    var Noresultstxt = $("#Noresultstxt").val();
    if (searchresults["d"] != null) {
        if (searchresults["d"]["WebResult"] != null) {
            document.getElementById("resultsContainer").style.visibility = "visible";
            document.getElementById("resultsContainer").style.display = "block";
            PagingModule("web", searchresults, _page);
            $("#results").css("background-color", "#FEFEF2");
            $("#results").css("border", "1px solid gray");
            $("#centerDiv").css("margin-left", "1%");
            $("#centerDiv").css("width", "73%");
            $("#ssLeftContainer").css("margin-left", "1%");

            $('#yahootemplate').tmpl(searchresults["d"]["WebResult"]).appendTo("#results");
        } else {
            $("#results").html("<div style='text-align:center;'> <h2>"+ Noresultstxt +"'<b>" + GetQuery() + "</b>'.</h2> Try searching for different Query.</div>");
        }
    }
    else {
        $("#results").html("<div style='text-align:center;'> <h2>"+ Noresultstxt +"'<b>" + GetQuery() + "</b>'.</h2> Try searching for different Query.</div>");
    }
}

function errorSever(error) {
    alert(error["Message"]);
}


function LoadJsonIE7() {
    this.JSON = {};
    (function () {

        function f(n) {
            // Format integers to have at least two digits.
            return n < 10 ? '0' + n : n;
        }

        if (typeof Date.prototype.toJSON !== 'function') {

            Date.prototype.toJSON = function (key) {

                return isFinite(this.valueOf()) ?
                   this.getUTCFullYear() + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate()) + 'T' +
                 f(this.getUTCHours()) + ':' +
                 f(this.getUTCMinutes()) + ':' +
                 f(this.getUTCSeconds()) + 'Z' : null;
            };

            String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
        }

        var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;


        function quote(string) {

            // If the string contains no control characters, no quote characters, and no
            // backslash characters, then we can safely slap some quotes around it.
            // Otherwise we must also replace the offending characters with safe escape
            // sequences.

            escapable.lastIndex = 0;
            return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
        }


        function str(key, holder) {

            // Produce a string from holder[key].

            var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

            // If the value has a toJSON method, call it to obtain a replacement value.

            if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
                value = value.toJSON(key);
            }

            // If we were called with a replacer function, then call the replacer to
            // obtain a replacement value.

            if (typeof rep === 'function') {
                value = rep.call(holder, key, value);
            }

            // What happens next depends on the value's type.

            switch (typeof value) {
                case 'string':
                    return quote(value);

                case 'number':

                    // JSON numbers must be finite. Encode non-finite numbers as null.

                    return isFinite(value) ? String(value) : 'null';

                case 'boolean':
                case 'null':

                    // If the value is a boolean or null, convert it to a string. Note:
                    // typeof null does not produce 'null'. The case is included here in
                    // the remote chance that this gets fixed someday.

                    return String(value);

                    // If the type is 'object', we might be dealing with an object or an array or
                    // null.

                case 'object':

                    // Due to a specification blunder in ECMAScript, typeof null is 'object',
                    // so watch out for that case.

                    if (!value) {
                        return 'null';
                    }

                    // Make an array to hold the partial results of stringifying this object value.

                    gap += indent;
                    partial = [];

                    // Is the value an array?

                    if (Object.prototype.toString.apply(value) === '[object Array]') {

                        // The value is an array. Stringify every element. Use null as a placeholder
                        // for non-JSON values.

                        length = value.length;
                        for (i = 0; i < length; i += 1) {
                            partial[i] = str(i, value) || 'null';
                        }

                        // Join all of the elements together, separated with commas, and wrap them in
                        // brackets.

                        v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                        gap = mind;
                        return v;
                    }

                    // If the replacer is an array, use it to select the members to be stringified.

                    if (rep && typeof rep === 'object') {
                        length = rep.length;
                        for (i = 0; i < length; i += 1) {
                            k = rep[i];
                            if (typeof k === 'string') {
                                v = str(k, value);
                                if (v) {
                                    partial.push(quote(k) + (gap ? ': ' : ':') + v);
                                }
                            }
                        }
                    } else {

                        // Otherwise, iterate through all of the keys in the object.

                        for (k in value) {
                            if (Object.hasOwnProperty.call(value, k)) {
                                v = str(k, value);
                                if (v) {
                                    partial.push(quote(k) + (gap ? ': ' : ':') + v);
                                }
                            }
                        }
                    }

                    // Join all of the member texts together, separated with commas,
                    // and wrap them in braces.

                    v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
                    gap = mind;
                    return v;
            }
        }

        // If the JSON object does not yet have a stringify method, give it one.

        if (typeof JSON.stringify !== 'function') {
            JSON.stringify = function (value, replacer, space) {

                // The stringify method takes a value and an optional replacer, and an optional
                // space parameter, and returns a JSON text. The replacer can be a function
                // that can replace values, or an array of strings that will select the keys.
                // A default replacer method can be provided. Use of the space parameter can
                // produce text that is more easily readable.

                var i;
                gap = '';
                indent = '';

                // If the space parameter is a number, make an indent string containing that
                // many spaces.

                if (typeof space === 'number') {
                    for (i = 0; i < space; i += 1) {
                        indent += ' ';
                    }

                    // If the space parameter is a string, it will be used as the indent string.

                } else if (typeof space === 'string') {
                    indent = space;
                }

                // If there is a replacer, it must be a function or an array.
                // Otherwise, throw an error.

                rep = replacer;
                if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                    throw new Error('JSON.stringify');
                }

                // Make a fake root object containing our value under the key of ''.
                // Return the result of stringifying the value.

                return str('', { '': value });
            };
        }


        // If the JSON object does not yet have a parse method, give it one.

        if (typeof JSON.parse !== 'function') {
            JSON.parse = function (text, reviver) {

                // The parse method takes a text and an optional reviver function, and returns
                // a JavaScript value if the text is a valid JSON text.

                var j;

                function walk(holder, key) {

                    // The walk method is used to recursively walk the resulting structure so
                    // that modifications can be made.

                    var k, v, value = holder[key];
                    if (value && typeof value === 'object') {
                        for (k in value) {
                            if (Object.hasOwnProperty.call(value, k)) {
                                v = walk(value, k);
                                if (v !== undefined) {
                                    value[k] = v;
                                } else {
                                    delete value[k];
                                }
                            }
                        }
                    }
                    return reviver.call(holder, key, value);
                }


                // Parsing happens in four stages. In the first stage, we replace certain
                // Unicode characters with escape sequences. JavaScript handles many characters
                // incorrectly, either silently deleting them, or treating them as line endings.

                text = String(text);
                cx.lastIndex = 0;
                if (cx.test(text)) {
                    text = text.replace(cx, function (a) {
                        return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                    });
                }

                // In the second stage, we run the text against regular expressions that look
                // for non-JSON patterns. We are especially concerned with '()' and 'new'
                // because they can cause invocation, and '=' because it can cause mutation.
                // But just to be safe, we want to reject all unexpected forms.

                // We split the second stage into 4 regexp operations in order to work around
                // crippling inefficiencies in IE's and Safari's regexp engines. First we
                // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
                // replace all simple value tokens with ']' characters. Third, we delete all
                // open brackets that follow a colon or comma or that begin the text. Finally,
                // we look to see that the remaining characters are only whitespace or ']' or
                // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

                if (/^[\],:{}\s]*$/
                    .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                    .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                    .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                    // In the third stage we use the eval function to compile the text into a
                    // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
                    // in JavaScript: it can begin a block or an object literal. We wrap the text
                    // in parens to eliminate the ambiguity.

                    j = eval('(' + text + ')');

                    // In the optional fourth stage, we recursively walk the new structure, passing
                    // each name/value pair to a reviver function for possible transformation.

                    return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
                }

                // If the text is not JSON parseable, then a SyntaxError is thrown.

                throw new SyntaxError('JSON.parse');
            };
        }
    } ());
}

function ShowList(company_id, _imgTag) {

    //var company_id = Company_Id;
    //Call Json Ajax
    $.ajax({
        url: _baseUrl + "GetStaffMembersByCompany",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ Company_Id: company_id }),
        processdata: true,
        dataType: "json",
        async: true,
        success: function (msg) { FormatStaffMembers(msg, company_id, _imgTag); }
        //        error: function (xhr, ajaxOptions, thrownError) { //$("#results").html(xhr.responseText); 
        //            $("#results").html('No Results for "<b>' + GetQuery() + '</b>" ');

        //        }
    });

}

function FormatStaffMembers(staffmemberslist, cmpId, _imgTag) {
    $("#Org").html('');
    if (staffmemberslist["d"] != null && staffmemberslist['d'] != undefined) {


        $('#StafflistTemplate').tmpl(staffmemberslist["d"]).appendTo("#Org");

    }

    $("#Org").css("left", zxcPos(_imgTag)[0] - 7 + 'px');
    $("#Org").css("top", zxcPos(_imgTag)[1] - 160 + 'px');
    $('#Org').show();
    $("#Org").css("display", "block");
    $("#Org").css("visibility", "visible");
    // timer1 = window.setTimeout(function () { $('#Org').fadeOut('slow'); }, 2000);
    cancelHide();
}

function cancelHide() {

    clearTimeout(timer1);
}

function hidePopup() {
    timer1 = window.setTimeout(function () { $('#Org').fadeOut('slow'); }, 500);
}

function zxcPos(obj) {
    var rtn = [obj.offsetLeft, obj.offsetTop];
    while (obj.offsetParent != null) {
        var objp = obj.offsetParent;
        rtn[0] += objp.offsetLeft - objp.scrollLeft;
        rtn[1] += objp.offsetTop - objp.scrollTop;
        obj = objp;
    }
    return rtn;
}

function GetLeftBanners() {


    var countrycode = document.getElementById("CountryDropDown").value;
    var provinceid = document.getElementById("provincectl").value;
    $("#ssRightContainer").css("display", "none");
    $("#ssRightContainer").css("visibility", "hidden");
    $.ajax({
        url: _baseUrl + "GetBanners",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ CountryCode: countrycode, Province_Id: provinceid }),
        processdata: true,
        dataType: "json",
        async: true,
        success: function (msg) { BindLeftImageUrl(msg); }
    });


}

function BindLeftImageUrl(ActiveBanneritem) {
    var imageurl = "";
    var bannerurl = "";
    var bannerid = "";
    var companyid = "";
    var bannerurllink = "";
    if (ActiveBanneritem["d"] != null && ActiveBanneritem['d'] != undefined) {
        bannerid = ActiveBanneritem["d"]["Banner_Id"].toString();
        companyid = ActiveBanneritem["d"]["Company_Id"].toString();
        imageurl = ActiveBanneritem["d"]["URL"].toString().replace('../', '');
        bannerurl = ActiveBanneritem["d"]["BannerURL"];
        urlredirector = "Redirector/URLRedirector.aspx";
        bannerurllink = urlredirector + "?li=" + bannerurl + "&b=" + bannerid + "&c=" + companyid;
        $("#BannerLeftImage").attr("src", imageurl);
        $("#LeftBannerURLLink").attr("href", bannerurllink);


    }
    else {
        $("#ssLeftContainer").css("display", "none");
        $("#ssLeftContainer").css("visible", "hidden");

    }

}

function GetRightBanners() {

    var countrycode = document.getElementById("CountryDropDown").value;
    var provinceid = document.getElementById("provincectl").value;
    $.ajax({
        url: _baseUrl + "GetBanners",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ CountryCode: countrycode, Province_Id: provinceid }),
        processdata: true,
        dataType: "json",
        async: true,
        success: function (msg) { BindRightImageUrl(msg); }
    });


}

function BindRightImageUrl(ActiveBanneritem) {
    var imageurl = "";
    var bannerurl = "";
    var bannerid = "";
    var companyid = "";
    var bannerurllink = "";
    if (ActiveBanneritem["d"] != null && ActiveBanneritem['d'] != undefined) {
        bannerid = ActiveBanneritem["d"]["Banner_Id"].toString();
        companyid = ActiveBanneritem["d"]["Company_Id"].toString();
        imageurl = ActiveBanneritem["d"]["URL"].toString().replace('../', '');
        bannerurl = ActiveBanneritem["d"]["BannerURL"];
        urlredirector = "Redirector/URLRedirector.aspx";
        bannerurllink = urlredirector + "?li=" + bannerurl + "&b=" + bannerid + "&c=" + companyid;
        $("#BannerRightImage").attr("src", imageurl);
        $("#RightBannerURLLink").attr("href", bannerurllink);

    }
    else {
        $("#ssRightContainer").css("display", "none");
        $("#ssRightContainer").css("visibility", "hidden");
    }

}


function UpdateClickCount(companyid,bannerid, type) {

    $.ajax({
        url: _baseUrl + "UpdateCompanyStatistics",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ Company_Id: companyid,Banner_Id:bannerid,Type:type }),
        processdata: true,
        dataType: "json",
        async: true,
        success: function (msg) { }
      
    });


}

