﻿/// <reference path="jquery-1.5.1.js" />
/// <reference path="jquery.tmpl.js" />
/// <reference path="jquery.deserialize.js" />

var handleGMap = function () { };
var handleSendEmail = function () { };
var site = { summary: [], gdata: [{ gps: { Zoom: 0, Latitude: 0, Longitude: 0 }, title: "", html: "", icon: ""}] };

Array.prototype.uniq = function () {
    var cnt = {};
    var res = [];
    for (var i = 0; i < this.length; i++) {
        var t = this[i];
        cnt[t] = (cnt[t] || res.push(t) * 0) + 1;
    }
    return res;
};

String.prototype.EmCo = function (compare, separator) {
    return this == "" || this == compare || $.inArray(compare, this.split(separator || ",")) > -1;
}

if (!Array.prototype.filter) {
    Array.prototype.filter = function (fun, thisp) {
        var len = this.length >>> 0;
        if (typeof fun != "function")
            throw new TypeError();

        var res = [];
        var thisp = arguments[1];
        for (var i = 0; i < len; i++) {
            if (i in this) {
                var val = this[i]; // in case fun mutates this  
                if (fun.call(thisp, val, i, this))
                    res.push(val);
            }
        }

        return res;
    };
}

$(document).ready(function () {
    var p = $("div.photoThumbs>ul");
    p.width(p.find("li").length * 125);

    $('aside select').customStyle();

    $('aside input[type="radio"]').ezMark({ radioCls: 'unselected', selectedCls: 'selected' });

    var filter = $("#filter");
    if (filter.is('form')) {
        //$.template("opt", '<option value="${Value}">${Name} (${Count})</option>');
        $.template("opt", '<option value="${Value}">${Name}</option>');
        site.any = { Value: "", Name: "any", Count: 0 };

        site.filter = filter;

        site.fields = {
            m: $("#m"), //Market
            t: $("#t"), //Property Type
            c: $("#c"), //County
            d: $("#d"), //Location
            b: $("#b"), //Bedrooms from
            bmax: $("#bmax"), //Bedrooms to
            s: $("#s"), //Sizes from
            smax: $("#smax"), //Sizes to
            p: $("#p"), //Price from
            pmax: $("#pmax") //Price to
        };

        var fill = function (field, data, empty, deserialize) {
            empty && field.empty();
            data = data || [];
            site.any.Count = data.length;
            var ddata = empty ? [site.any] : [];
            var f = field.attr("sname");
            var n = f == "Price" ? "&euro;" : "";
            ddata = ddata.concat($.map(
            $.map(data, function (a) { return a[f] }).uniq().sort(function (a, b) { return !isNaN(a) && !isNaN(b) ? a - b : a > b ? 1 : a < b ? -1 : 0 }),
            function (a) { return { Value: a, Name: n + a, Count: $.grep(data, function (e) { return e[f] == a }).length} })
            .filter(function (e) { return isNaN(e.Value) || e.Value > 0 })
            );
            $.tmpl("opt", ddata).appendTo(field);
            deserialize && site.filter.deserialize(site.filter.attr("def"), { only: [field.attr("name")] });
        };

        var onChange = function () {
            var order = { m: "t", t: "c", c: "d", d: "b", b: "bmax", bmax: "p", s: "smax", smax: "p", p: "pmax" };
            var name = $(this).attr("name");
            var isCom = "Commercial Sales,Industrial New Developments,Commercial Rental".EmCo(site.fields.m.val());
            if (isCom) {
                if (name == "m") {
                    site.fields.s.parent().show();
                    site.fields.b.parent().hide();
                }
                order.d = "s";
                order.b = undefined;
                order.bmax = undefined;
            }
            else {
                if (name == "m") {
                    site.fields.s.parent().hide();
                    site.fields.b.parent().show();
                }
                order.s = undefined;
                order.smax = undefined;
            }
            var fnext = site.fields[order[name]];
            var cur = site.summary;
            for (var i in order) {
                var f = site.fields[i];
                var n = f.attr("sname");
                var v = f.val();
                var vn = Number(v);
                cur = i != undefined && v != "" ? $.grep(cur, isNaN(v) ? function (e) { return v.EmCo(e[n]) } : function (e) { return vn <= e[n] })
                : cur;
                if (i == name) break;
            }
            fill(fnext, cur, true, site.init);
            site.init = site.init && name != "p";
            fnext.change();
        };

        $("select[name!=pmax]").change(onChange);

        $.ajax(
        {
            url: '/odata.svc/Summary',
            headers: { accept: 'application/json' },
            success: function (data) {
                site.init = true;
                site.summary = data.d;
                //fill(site.fields.m, site.summary, false, true);
                site.fields.m.change();
            }
        }
        );
    }

    var gmap = $("#gmap");
    if (gmap.is('div')) {
        handleGMap = function () {
            var gps = { Zoom: 20, Latitude: 0, Longitude: 0 };
            $.each(site.gdata, function (i, e) { gps.Latitude += e.gps.Latitude; gps.Longitude += e.gps.Longitude; gps.Zoom = gps.Zoom > e.gps.Zoom ? e.gps.Zoom : gps.Zoom; });
            gps.Latitude /= (site.gdata.length || 1);
            gps.Longitude /= (site.gdata.length || 1);

            var myLatlng = new google.maps.LatLng(gps.Latitude, gps.Longitude);

            var myOptions = {
                zoom: site.gdata.length > 1 ? 7 : gps.Zoom,
                center: myLatlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(gmap.get(0), myOptions);
            $.each(site.gdata, function (i, e) {
                var infowindow = new google.maps.InfoWindow({
                    content: e.html
                });

                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(e.gps.Latitude, e.gps.Longitude),
                    map: map,
                    //icon: e.icon,
                    title: e.title
                });

                google.maps.event.addListener(marker, 'click', function () { infowindow.open(map, marker); });
            });

        };
        $.getScript("http://maps.google.com/maps/api/js?sensor=false&callback=handleGMap&region=IE");
    }

    var zoom = $(".photoZoom").find('a');
    if (zoom.is('a')) {
        $(".photoThumbs").find('a').click(function () {
            zoom.find('img').attr("src", $(this).attr("href"));
            zoom.attr('href', $(this).attr("full"));
            return false;
        });
    }

    var answer = $("#answer");
    if (answer.is("span")) {
        handleSendEmail = function (data) {
            answer.text(data.result ? "Message sent. Thanks for contacting us!" : "Incorrect email.");
        }
    }
});
