﻿
var seachTextBox = $("#FarmSearchPhrase");
var seachButton = $("#FarmSearchExecute");

$(document).ready(function() {

    Searcher.initialize();

    seachTextBox.keydown(function(event) {

        if (event.keyCode == 13) {
            seachButton.trigger("click");
            return false;
        }
    });

    seachButton.click(function() {

        Form.clearCheckboxes();

        if (seachTextBox.val() == "")
            Searcher.showAll();
        else Searcher.phraseSearch(seachTextBox.val());

    });

    $("#searchFamsByAttribute input").click(function(e) {

        Form.clearSearchInput();
        var params = Form.getSelectedAttributes()

        if (params)
            Searcher.attributeSearch(params);
        else
            Searcher.showAll();
    });

    // perform search on History Back button
    if (seachTextBox.val() != "")
        Searcher.phraseSearch(seachTextBox.val());
    else
        if (Form.isSomethingChecked())
            Searcher.attributeSearch(Form.getSelectedAttributes());
});

var Form = {

    clearSearchInput: function() {
        seachTextBox.val("");
    },

    clearCheckboxes: function() {
        $("#searchFamsByAttribute input:checked").each(function() { $(this).attr("checked", ""); });
    },

    getSelectedAttributes: function() {
        var params = { phrase: "", use_of_buildings: "", location: "" };
        var valid = false;
        $("#searchFamsByAttribute .use_of_buildings:checked").each(function () { valid = true; params.use_of_buildings += $(this).attr("name") + " "; });
        $("#searchFamsByAttribute .location:checked").each(function () { valid = true; params.location += $(this).attr("name") + " "; });
        if (valid)
            return params;
        else
            return false;
    },

    isSomethingChecked: function() {
        return $("#searchFamsByAttribute input:checked").size() > 0;
    }
}


var Searcher = {
    Proxy: new serviceProxy("/webservices/FarmsRepository.svc/"),
    map: null,
    markers: [],
    geocoder: null,
    baseIcon: new GIcon(G_DEFAULT_ICON),

    initialize: function () {
        if (GBrowserIsCompatible()) {
            this.map = new GMap2(document.getElementById("gmap"));
            if ($(".rightmap").length != 1) {
                this.map.setCenter(new GLatLng(56.108810038002154, 10.92041015625), 6);
            } else {
                this.map.setCenter(new GLatLng(56.108810038002154, 10.92041015625), 5);
            }
            this.baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
            this.baseIcon.iconSize = new GSize(20, 34);
            this.baseIcon.shadowSize = new GSize(37, 34);
            this.baseIcon.iconAnchor = new GPoint(9, 34);
            this.baseIcon.infoWindowAnchor = new GPoint(9, 2);
            var mapControl = new GMapTypeControl();
            if ($(".rightmap").length != 1) {
                this.map.addControl(mapControl);
                this.map.addControl(new GLargeMapControl());
            }
            if (activeFarmPage == false) {
                this.createMarkers(true)
            }
            else {
                this.createMarker(this.findFarm(activeFarmPage), true);
            }
        }
    },

    createMarkers: function (visible) {

        for (var i = 0; i < farms.length; i++)
            this.createMarker(i, visible);
    },

    findFarm: function (id) {
        for (var i = 0; i < farms.length; i++)
            if (farms[i].id == id)
                return i;
        return -1;
    },

    createMarker: function (i, visible) {
        if (farms[i]) {
            var letteredIcon = new GIcon(this.baseIcon);
            var gc = farms[i].geocode.split(",");
            var geocode = new GLatLng(gc[0], gc[1]);

            this.markers[i] = new GMarker(geocode, { icon: letteredIcon });

            GEvent.addListener(this.markers[i], "mouseover", function () {
                var html = "<div class='info_title'>" + farms[i].name + "</div>" + "<div class='info_desc'>" + farms[i].teaser + '</div>';
                if ($(".rightmap").length != 1) {
                    this.openInfoWindowHtml(html);
                }
            });

            GEvent.addListener(this.markers[i], "click", function () {

                activeFarmPage = farms[i].id;
                window.location.href = '/' + farms[i].id + '.aspx';
            });

            if (!visible) this.markers[i].hide();

            this.map.addOverlay(this.markers[i]);
        }
    },

    showInfo: function (index) {
        markers[index].openInfoWindowHtml("info");
    },

    showAll: function () {
        for (i = 0; i < farms.length; i++)
            if (Searcher.markers[i])
                Searcher.markers[i].show();
            else
                Searcher.createMarker(i, true);
    },

    phraseSearch: function (text) {

        var searchparams = {
            phrase: text,
            size: "",
            use_of_buildings: "",
            region: ""
        };

        this.Proxy.invoke("SearchFarms", searchparams, this.processResults);
    },

    attributeSearch: function (searchparams) {
        this.Proxy.invoke("SearchFarms", searchparams, this.processResults);
    },

    processResults: function (result) {

        if (activeFarmPage != false) {
            Searcher.markers[Searcher.findFarm(activeFarmPage)].hide();
            Searcher.createMarkers(false); activeFarmPage = false;
        }

        var foo = new Array();

        for (var q = 0; q < result.length; q++) {
            foo[result[q].Id] = true;
        }

        for (var i = 0; i < farms.length; i++) {

            if (foo[farms[i].id] == true) {
                Searcher.markers[i].show();
            }
            else {
                Searcher.markers[i].hide();
            }
            Searcher.markers[i].closeInfoWindow()
        }
    }
}

var ContentService = {

    loadFarmContent: function(id) {
        $.get("/" + id + ".aspx", function(content) {
            $("#farm_list").css("display", "none");
            $("#farm_content").html(content).css("display", "");
        });
    },

    loadListContent: function() {
        $("#farm_list").css("display", "");
        $("#farm_content").html("").css("display", "none");
    }

}

function serviceProxy(serviceUrl) {
    var _I = this;
    this.serviceUrl = serviceUrl;

    this.invoke = function(method, data, callback, error, bare) {

        var json = JSON2.stringify(data);

        var url = _I.serviceUrl + method;

        $.ajax({
            url: url,
            data: json,
            type: "POST",
            processData: false,
            contentType: "application/json",
            timeout: 10000,
            dataType: "text",  // not "json" we'll parse
            success:
                    function(res) {
                        if (!callback) return;

                        // *** Use json library so we can fix up MS AJAX dates
                        var result = JSON2.parse(res);

                        // *** Bare message IS result
                        if (bare)
                        { callback(result); return; }

                        // *** Wrapped message contains top level object node
                        // *** strip it off
                        for (var property in result) {
                            callback(result[property]);
                            break;
                        }
                    },
            error: function(xhr) {
                if (!error) return;
                if (xhr.responseText) {
                    var err = JSON2.parse(xhr.responseText);
                    if (err)
                        error(err);
                    else
                        error({ Message: "Unknown server error." })
                }
                return;
            }
        });
    }
}


