var eyekiller_property_actions = {"receive_property":"37","retrieve_property":"38","cron_job":"39","track_search":"40","querybuilder":"41","output_js_action":"42","async_search":"43","join_mailing_list":"44","export_mailing_list":"45","epc_image_output":"48"};
var eyekiller_properties_fields = ["from_address","min_price","max_price","from_coords","keywords","sort","orderby","querybuilder","killer_property_status","id","url_title","agent_id","import_source","import_id","import_profile_id","sector","house_no","house_name","address_1","address_2","address_3","address_4","post_code","area","area_id","location","viewing","age","description","available_from","available_from_text","asking_price","asking_price_cur","price_description","is_price_on_application","tenure","ground_rent","current_offer","current_offer_cur","status","nav","bedrooms","receptions","bathrooms","heating_type","is_garage","house_type","is_auction","current_energy_rating","potential_energy_rating","epc_reference","epc_landmark_code","virtual_tour","longitude","latitude","secret","date_created","date_modified","sort_order","is_processing","is_active"];
var eyekiller_developments_fields = ["from_address","min_price","max_price","from_coords","keywords","sort","orderby","querybuilder","killer_property_status","id","url_title","agent_id","import_source","import_id","import_profile_id","sector","headline","house_no","house_name","address_1","address_2","address_3","address_4","post_code","area","area_id","location","viewing","deposit","joint_agent","joint_agent_id","developer","developer_id","age","description","release_date","release_date_text","price_range","min_price","min_price_cur","max_price","max_price_cur","status","ground_rent","nav","min_bedrooms","max_bedrooms","receptions","heating_type","is_garage","house_type","virtual_tour","is_auction","is_new_development","current_energy_rating","potential_energy_rating","epc_reference","epc_landmark_code","longitude","latitude","secret","date_created","date_modified","sort_order","is_processing","is_active"];

var async_search_submit_form_timeout;
var ek_hashbangs = parseHashBangArgs();

$(document).ready(function (evt) {
    $("input[name='killer_property_javascript_enabled']").attr("value", 1);
    if (window["async_wrapper_id"] != undefined && window["async_wrapper_id"] != null && window["async_wrapper_id"] != "") {
        var qs = parseHashBangArgs();
        var path = "/index.php/search/async/";

        $.get(path, qs, function (text) {
            $("#" + window["async_wrapper_id"]).html(text);
        });
    }
});

function update_hashbangs_from_form(search_params){

    var form_search_params = $.extend(true, {}, search_params);
    var query_search_params = parseHashBangArgs();
    var new_search_params = ""
    var hash_glue = "";

    if("range-min-price" in form_search_params){
        form_search_params["min_price"] = form_search_params["range-min-price"];
    }

    if("range-max-price" in form_search_params){
        form_search_params["max_price"] = form_search_params["range-max-price"];
    }

    $.each(form_search_params, function(name, value){
        if(window["eyekiller_properties_fields"].indexOf(name) >= 0){
            new_search_params += hash_glue + name + "=" + value;
            delete query_search_params[name];
            hash_glue = "&";
        }
    });

    $.each(query_search_params, function(name, value){

        if (typeof value === 'object'){

            var object_value = "";
            for(i = 0; i < Object.keys(value).length; i++){
                new_search_params += hash_glue + name + "[]=" + value[i];
            }

        } else {
            new_search_params += hash_glue + name + "=" + value;
        }
    });

    location.hash = "!/" + new_search_params;
    $(".update_async_querystring").each(function(index, item){
        var src = $(item).attr("href");
        var query_marker_index = src.indexOf("?");
        if(query_marker_index > 0){
            src = src.subString(0, query_marker_index);
        }
        src = src.trimRight("/") + "/";
        src += "?" + new_search_params;
        $(item).attr("href", src);
    });
}

function get_async_map_results(page, method, template, search_query){
    var search_params = convert_query_to_object(search_query || location.search.substring(1));
    var ACT = window["eyekiller_property_actions"]["async_search"];

    if(page != null && page > 0){
        search_params["page"] = page;
    }
    search_params["include_result_data"] = true;

    search_params.kpt = "properties";
    search_params.limit = "20";
    search_params.template = template;
    search_params.tag_params = {
        "paginate" : "bottom"
    }

    var return_data = null;

    $.get(
        "/?ACT=" + ACT,
        search_params,
        function (data) {
            //alert("ok so far");
            var fn = window[method];
            if(typeof fn === 'function') {
                fn(data);
            }

        },
        "json"

    );

    return return_data;
}

function async_search_submit_query(search_params, update_container_id) {

    var ACT = window["eyekiller_property_actions"]["async_search"];

    search_params.kpt = "properties";
    search_params.KILLERPROPERTYVIEWSTATE = $("#KILLERPROPERTYVIEWSTATE").val();

    if ($(".eyekiller_property_async_container").length > 0) {
        var async_div = $(".eyekiller_property_async_container").first();
        search_params.template_id = $(async_div).data("template_id");
        search_params.container_id = update_container_id = $(async_div).attr("id");
    }

    $.get(
        "/?ACT=" + ACT,
        search_params,
        function (data) {
            if (data.template != undefined && update_container_id != false) {
                $("#" + update_container_id).html(data.template)
            }
            if (typeof killer_property_async_return == 'function') {
                killer_property_async_return(data);
            }
            if ($("#" + update_container_id + "_progress").length > 0) {
                $("#" + update_container_id + "_progress").hide();
            }
        },
        "json"
    );
}

function async_search_submit_form(event, this_control) {

    // we want to stop the currently-delayed action, to avoid a duplication of effort
    clearTimeout(window["async_search_submit_form_timeout"]);

    var form = $(this).parentsUntil("form").parent();
    if (form == null || form == undefined) {
        return;
    }

    // now we delay the action by two seconds to allow further changes to be made in the interim
    // TODO: in the meantime, start a ticker to show progress
    window["async_search_submit_form_timeout"] = setTimeout(function () {
        do_async_search(form);
    }, 2000);
}



// This function is called in an onload event at the end of the search HTML
function do_async_init(update_container_id) {

    // parse the contents of the hashbangs
    var search_params = parseHashBangArgs();

    // this will populate the search form with the hashbang data
    do_populate_search_form(search_params);

    // this will submit the search form through ajax using the hashbang data
    async_search_submit_query(search_params, update_container_id);


    // when we're populating the search form, it is triggering these (causing a duplication),
    // so we should wire them up AFTER the search form has been populated
    $(document).on("slidechange", "#slider-range", async_search_submit_form);

    $(document).on("change", ".async-property-search", async_search_submit_form);

    $(document).on("click", ".async-property-search-button", async_search_submit_form);

    if(window["async_form_events"] != undefined && window["async_form_events"] != null){
        $.each(window["async_form_events"], function (index, item){
            $(document).on(item["event"], item["selector"], async_search_submit_form);
        });
    }

    $(document).on("click", ".killer_property_async_paging a", function (evt) {
        var search_params = parseHashBangArgs(decodeURIComponent($(this).attr("href")));
        var update_container_id = $(this).parentsUntil(".eyekiller_property_async_container").parent().attr("id");
        async_search_submit_query(search_params, update_container_id)
    });

    $(".update_async_querystring").each(function(index, item){
        var src = $(item).attr("href");
        var query_marker_index = src.indexOf("?");
        if(query_marker_index > 0){
            src = src.subString(0, query_marker_index);
        }
        src = src.trimRight("/") + "/";
        src += "?" + window.location.href.slice(window.location.href.indexOf('#!') + 3);
        $(item).attr("href", src);
    });

}

function join_object_to_string(obj, glue) {
    var return_value = "";
    var this_glue = "";
    if(obj != null && obj != undefined){
        $.each(obj, function (itemkey, itemvalue) {
            return_value += this_glue + itemvalue;
            this_glue = glue;
        });
    }
    return return_value;
}

function set_control_value(controls, value) {

    var tagname = controls.prop("tagName");

    if (tagname == "input") {
        switch (controls.attr("type")) {
            case "radio":
                if (typeof value === 'object') {
                    $.each(value, function (index, value) {
                        $(form).find("[name='" + itemkey + "']").first()
                    });
                }
                break;
            case "checkbox":
                if (typeof value === 'object') {
                    $.each(value, function (index, value) {

                    });
                }
                break;
            default:
                controls.val(value);
                break;
        }
    } else {
        controls.val(value);
    }
}

function do_populate_search_form(search_params) {

    var this_params = $.extend(true, {}, search_params);
    var qb = this_params["querybuilder"];
    delete this_params["querybuilder"];

    $(".async_search_form").each(function (formindex, form) {

        if(qb != undefined && qb != null){
            $.each(qb, function (querybuilderindex, querybuilderitem) {
                addQueryBuilderValueToList(querybuilderindex, querybuilderitem, querybuilderitem);
            });
        }

        var prices = $("#slider-range").slider("values");
        var new_prices = {"min_price" : prices[0], "max_price": prices[1]};

        $.each(this_params, function (itemkey, itemvalue) {
            var i = itemvalue;
            var x = form;
            var y = formindex;

            if(itemkey != "" && itemkey != null && itemkey != undefined){
                if (itemkey == "min_price" || itemkey == "max_price") {
                    //searchWatermark
                    var mp = $(form).find("[name='" + itemkey + "']").first();
                    var control_name = (("min_price") ? "range-min-price" : "range-max-price");

                    new_prices[itemkey] = itemvalue;
                    $("#slider-range").slider({values: [new_prices["min_price"], new_prices["max_price"]]});
                    $(form).find("[name='amount']").val("£" + addCommas(new_prices["min_price"]) + " - £" + addCommas(new_prices["max_price"]));

                    if(mp.find("[value='" + itemvalue + "']").length > 0){
                        mp.val(itemvalue);
                        mp.find("[value='" + itemvalue + "']").prop('selected', true);
                    } else {
                        var insertBefore = null;
                        $.each(mp.find("option"), function(index, item){
                            if(index == 1 && (parseInt(item.value) > parseInt(itemvalue))){
                                insertBefore = item;
                                return false;
                            }
                            if(parseInt(item.value) < parseInt(itemvalue)){
                                insertBefore = item;
                                return false;
                            }
                        });
                        if(insertBefore != null){
                            $("<option value='"+ itemvalue + "'>£" + addCommas(itemvalue) + "</option>").insertBefore(insertBefore);
                        } else {
                            $(mp).append("<option value='"+ itemvalue + "'>£" + addCommas(itemvalue) + "</option>");
                        }
                    }
                } else if (itemkey == "keywords") {
                    //searchWatermark
                    $(form).find("[name='" + itemkey + "']").val(itemvalue);
                    $("#searchWatermark").hide();
                } else if (typeof itemvalue === 'object') {
                    var itemvalue = join_object_to_string(itemvalue);
                    $(form).find("[name=" + itemkey + "]").val(itemvalue);
                } else {
                    var control = $(form).find("[name=" + itemkey + "]").first();
                    if($(control).prop("tagName") == "INPUT"){
                        switch($(control).attr("type")){
                            case "radio":
                                if($(form).find("[name=" + itemkey + "][value='" + itemvalue + "']").length > 0){
                                    $(form).find("[name=" + itemkey + "][value='" + itemvalue + "']").first().prop("checked", true)
                                }
                                break;
                            default:
                                $(form).find("[name=" + itemkey + "]").val(itemvalue);
                                break;
                        }
                    } else {
                        $(form).find("[name=" + itemkey + "]").val(itemvalue);
                    }

                }
            }



        });

        $(form).find(".search_form_async_progress").hide();
    });

}

function do_async_search(form) {

    var search_params = $(form).serializeObject();
    update_hashbangs_from_form(search_params);

//    delete search_params.action;
//    delete search_params.csrf_token;
//    delete search_params.this_page;
    delete search_params.ACT;
    search_params.kpt = "properties";
    search_params.limit = 5;
    search_params.KILLERPROPERTYVIEWSTATE = $("#KILLERPROPERTYVIEWSTATE").val();

    var ACT = window["eyekiller_property_actions"]["async_search"];

    var update_container_id = false;

    if ($(".eyekiller_property_async_container").length > 0) {
        var async_div = $(".eyekiller_property_async_container").first();
        search_params.template_id = $(async_div).data("template_id");
        search_params.container_id = update_container_id = $(async_div).attr("id");
    }

    $.get(
            "/?ACT=" + ACT,
            search_params,
            function (data) {
                if (data.template != undefined && update_container_id != false) {
                    $("#" + update_container_id).html(data.template)
                }
                if (typeof killer_property_async_return == 'function') {
                    killer_property_async_return(data);
                }
            },
            "json"
    );
}

$.fn.serializeObject = function ()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function parseHashBangArgs(aURL) {

    aURL = aURL || window.location.href;

    var vars = {};
    var hashes = aURL.slice(aURL.indexOf('#!') + 3).split('&');

    for (var i = 0; i < hashes.length; i++) {
        var hash = hashes[i].split('=');

        if (hash.length > 1) {
            var name = hash[0];
            var SquareBracketIndex = name.indexOf("[")
            if (SquareBracketIndex >= 0) {
                var arrays = name.split("[");
                name = name.substring(0, SquareBracketIndex);
                if (vars[name] == undefined || vars[name] == null) {
                    vars[name] = {};
                }
                var currentObject = vars[name];
                for (var j = 1; j < arrays.length; j++) {
                    var arrayname = arrays[j].replace(/]/i, "");
                    if (arrayname == "") {
                        if (j == (arrays.length - 1)) {
                            var xx = Object.keys(currentObject).length;
                            currentObject[xx] = hash[1];
                        } else {
                            currentObject.push({});
                        }
                    } else {
                        if (currentObject[arrayname] == undefined || currentObject[arrayname] == null) {
                            currentObject[arrayname] = {};
                        }
                    }
                }
                vars[name] = currentObject;
            } else {
                vars[name] = hash[1];
            }

        } else {
            vars[hash[0]] = null;
        }
    }
    return vars;
}

function convert_query_to_object(query){

    var vars = {};
    var hashes = query.split('&');

    for (var i = 0; i < hashes.length; i++) {
        var hash = hashes[i].split('=');

        if (hash.length > 1) {
            var name = hash[0];
            var SquareBracketIndex = name.indexOf("[")
            if (SquareBracketIndex >= 0) {
                var arrays = name.split("[");
                name = name.substring(0, SquareBracketIndex);
                if (vars[name] == undefined || vars[name] == null) {
                    vars[name] = {};
                }
                var currentObject = vars[name];
                for (var j = 1; j < arrays.length; j++) {
                    var arrayname = arrays[j].replace(/]/i, "");
                    if (arrayname == "") {
                        if (j == (arrays.length - 1)) {
                            var xx = Object.keys(currentObject).length;
                            currentObject[xx] = hash[1];
                        } else {
                            currentObject.push({});
                        }
                    } else {
                        if (currentObject[arrayname] == undefined || currentObject[arrayname] == null) {
                            currentObject[arrayname] = {};
                        }
                    }
                }
                vars[name] = currentObject;
            } else {
                vars[name] = hash[1];
            }

        } else {
            vars[hash[0]] = null;
        }
    }
    return vars;
}

/*
 function parseHashBangArgs(aURL) {

 aURL = aURL || window.location.href;

 var vars = {};
 var hashes = aURL.slice(aURL.indexOf('#!') + 3).split('&');

 for (var i = 0; i < hashes.length; i++) {
 var hash = hashes[i].split('=');

 if (hash.length > 1) {
 vars[hash[0]] = hash[1];
 } else {
 vars[hash[0]] = null;
 }
 }
 return vars;
 }
 */

function getHashBangArg(key, value) {

}

function getQuerystring() {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
    return results;
}

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

$(document).ready(function () {

    $(".ekp-searchWatermark").click(function (e) {
        var ul = $(this).parentsUntil("ul.ekp-search_ul").parent();
        $(ul).find(".ekp-keywords").first().focus();
    });

    $(".ekp-keywords").focus(function (e) {
        var ul = $(this).parentsUntil("ul.ekp-search_ul").parent().parent();
        $(ul).find(".ekp-searchWatermark").first().hide();
    });

    $(".ekp-keywords").blur(function (e) {
        var ul = $(this).parentsUntil("ul.ekp-search_ul").parent().parent();
        if ($(this).val() == "" && ($(ul).find(".ekp-selected-item").length <= 0))
            $(ul).find(".ekp-searchWatermark").first().show();
    });

    $(".ekp-keywords").keyup(function (e) {
        
        var ul = $(this).parentsUntil("ul.ekp-search_ul").parent().parent();
        window["eyekiller_property_querybuilder"] = ul;

        //need to check for a down arrow
        if (e.keyCode == 40) {
            // do down action
        } else {
            // do search

            if ($(this).val().length >= 3) {

                var url = "/?ACT=" + window["eyekiller_property_actions"]["querybuilder"];

                $.get(url, {q: $(this).val()}, function (data) {

                    if (data != "<ul class='ekp-resultList'></ul>") {

                        $(window["eyekiller_property_querybuilder"]).find(".ekp-search_location_results").first().html(data);

                        if (!$(window["eyekiller_property_querybuilder"]).find(".ekp-search_location_results").first().is(":visible")){
                            $(window["eyekiller_property_querybuilder"]).find(".ekp-search_location_results").first().show();
                        }
                    } else {
                        $(window["eyekiller_property_querybuilder"]).find(".ekp-search_location_results").first().hide();
                    }

                });

            } else {
                $(window["eyekiller_property_querybuilder"]).find(".ekp-search_location_results").first().hide();
            }

        }

        //$("#searchLocationHint").text($(this).val());

    });

    $(".ekp-search_location_results").on("click", ".ekp-searchSuggestion", function (evt) {
        
        var ul = $(this).parentsUntil("ul.ekp-search_ul").parent().parent();

        addQueryBuilderValueToList($(this).data("locationid"), $(this).data("location"), $(this).data("area"), ul);

    });

});

$(".ekp-search_ul").on("click", ".ekp-remove-item", function (evt) {

    $("#" + $(this).data("id")).remove();

    evt.preventDefault();

});


function isValueAlreadyAdded(text, ul) {

    var isAlreadyAdded = false;

    $(ul).find(".ekp-search_ul .ekp-selected-item").each(function (i) {

        if ($(this).find("input").first().val() == text)
            isAlreadyAdded = true;

    });

    return isAlreadyAdded;
}

function addQueryBuilderValueToList(locationid, location, area, ul) {

    var isAlreadyAdded = isValueAlreadyAdded(location, ul);

    if (!isAlreadyAdded) {

        // add to ul

        var html = "";

        html += "<li id=\"" + locationid + "\" class=\"ekp-selected-item\">\n";
        html += "\t<span class=\"ekp-list-item-wrap\">\n";
        html += "\t\t<span title=\"" + location + ", " + area + "\">" + location + "</span>\n";
        html += "\t\t<a href=\"#\" class=\"ekp-remove-item\" data-id=\"" + locationid + "\">\n"
        html += "\t\t\t<img src=\"/images/search-delete.png\" width=\"19\" height=\"25\">\n";
        html += "\t\t</a>\n";
        html += "\t</span>\n";
        html += "\t<input type=\"hidden\" name=\"querybuilder[]\" value=\"" + location + "\">\n";
        html += "</li>\n";

        $(ul).find(".ekp-search_ul li:last").before(html);

        //css hack for search textbox
        $(ul).find('.ekp-keywords').css('margin-top', '-11px');
    }

    $(ul).find(".ekp-keywords").first().val("");
    $(ul).find(".ekp-keywords").first().focus();
    $(ul).find(".ekp-search_location_results").first().hide();

}

