﻿// Define o web site como Home Page
function SetHomePage() {
    if (document.all) {
        document.body.style.behavior = 'url(#default#homepage)';
        document.body.setHomePage('http://www.vilamais.pt');

    }
    else if (window.sidebar) {
    alert('As definições de segurança do seu Browser não permitem efectuar o processo pretendido.\nPor favor efectue o processo manualmente.');
    }
    else {
        alert('As definições de segurança do seu Browser não permitem efectuar o processo pretendido.\nPor favor efectue o processo manualmente.');
    }

    return false
}

// Adicionar o site aos Favoritos
function bookmark() {
    bookmarkurl = "http://www.vilamais.pt"
    bookmarktitle = "Vila Mais"
    if (document.all)
        window.external.AddFavorite(bookmarkurl, bookmarktitle)
    else if (window.sidebar) // firefox
        window.sidebar.addPanel(bookmarktitle, bookmarkurl, "");
        else {
            alert('O Browser em utilização não permite efectuar o processo pretendido.\nPor favor efectue o processo manualmente.');
    }
}

/* Método que valida a introdução de valores numéricos */
function numeric_Validate(e, obj) {
    var evt = e ? e : window.event;
    var keycode;
    if (document.all)
        keycode = evt.keyCode;
    else
        keycode = evt.which;
    if (keycode >= 48 && keycode <= 57 || (keycode == 0 || keycode == 8))
        return true;
    else
        return false;
}

/* Método que valida se o endereço de e-mail está correcto */
function validateEmail(e) {
    if (e != "") {
        var objRegExp = /^.+@.+\..{2,3}$/;
        return objRegExp.test(e);
    } else {
        return true;
    }
}

// Validação do Formulário de Subscrição da Newsletter
function frmNewsletter_Validate(clientID) {
    var msg = '';
    if (document.getElementById(clientID + "_tbName").value == "") msg += '» Nome\n';
    if (document.getElementById(clientID + "_tbMail").value == "") msg += '» E-mail\n';
    if (msg.length > 0) {
        alert("Os seguintes campos são de preenchimento obrigatório:\n" + msg);
        return false;
    }
    if (!validateEmail(document.getElementById(clientID + "_tbMail").value)) {
        alert("Introduza um endereço de e-mail válido.");
        return false;
    }
    return true;
}

// Validação do Formulário de Subscrição da Newsletter
function frmRecommend_Validate(clientID) {
    var msg = '';
    if (document.getElementById(clientID + "_tbName").value == "") msg += '» Nome\n';
    if (document.getElementById(clientID + "_tbMail").value == "") msg += '» E-mail\n';
    if (msg.length > 0) {
        alert("Os seguintes campos são de preenchimento obrigatório:\n" + msg);
        return false;
    }
    if (!validateEmail(document.getElementById(clientID + "_tbMail").value)) {
        alert("Introduza um endereço de e-mail válido.");
        return false;
    }
    return true;
}

// Validação do Formulário de Subscrição da Newsletter
function frmMarket_Validate(clientID) {
    var msg = '';
    if (document.getElementById(clientID + "_tbName").value == "") msg += '» Nome\n';
    if (document.getElementById(clientID + "_tbPhone").value == "") msg += '» Telefone\n';
    if (document.getElementById(clientID + "_tbEmail").value == "") msg += '» E-mail\n';
    if (msg.length > 0) {
        alert("Os seguintes campos são de preenchimento obrigatório:\n" + msg);
        return false;
    }
    if (!validateEmail(document.getElementById(clientID + "_tbEmail").value)) {
        alert("Introduza um endereço de e-mail válido.");
        return false;
    }
    return true;
}

// Validação do Formulário de Subscrição da Newsletter
function frmContactRequest_Validate(clientID) {
    var msg = '';
    if (document.getElementById(clientID + "_tbName").value == "") msg += '» Nome\n';
    if (document.getElementById(clientID + "_tbPhone").value == "") msg += '» Telefone\n';
    if (document.getElementById(clientID + "_tbEmail").value == "") msg += '» E-mail\n';
    if (msg.length > 0) {
        alert("Os seguintes campos são de preenchimento obrigatório:\n" + msg);
        return false;
    }
    if (!validateEmail(document.getElementById(clientID + "_tbEmail").value)) {
        alert("Introduza um endereço de e-mail válido.");
        return false;
    }
    return true;
}

// Função que determina quando é que a cookie expira
function cookies_ExpiresAt() {
    var e = new Date();
    e.setFullYear(e.getFullYear() + 1);

    return { expiresAt: e };
}

function AddFavorite(propertyID, cookieName, handlerPath) {
//$(".propertyAddFavorite").click(function () {
    if (propertyID > 0) {
        if ($.cookies.test()) {
            var v = ($.cookies.get(cookieName) != null) ? $.cookies.get(cookieName).toString().split(',') : new Array();

            var p = -1;
            for (var i = 0; i < v.length; i++) {
                if (v[i] == propertyID) {
                    p = i
                    break;
                }
            }

            if (p == -1) {
                v.push(propertyID);
                $.cookies.set(cookieName, v.join(','), cookies_ExpiresAt());
                alert('O imóvel foi adicionado à lista de favoritos com sucesso.');
                $('body').trigger('AddFavorites');
                $('body').trigger('UpdateFav');
                $('body').trigger('UpdateStar', [propertyID]);
    
                $.ajax({
                    type: "POST",
                    url: handlerPath + "/UpdateFavoritesStats.ashx",
                    data: { PropertyID: propertyID }
                });
            } else {
                alert('O imóvel já se encontra na lista de favoritos.');
            }
        } else {
            $(this).attr('checked', false);
            alert('Não é possível adicionar o imóvel à lista de favoritos.\nPara utilizar esta funcionalidade é necessário que o Browser que utiliza permita a utilização de cookies.');
        }
    }
//});
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

function AddSearchProperty(propertyID, cookieName, handlerPath) {
    if (propertyID > 0) {
        if ($.cookies.test()) {
            var v = ($.cookies.get(cookieName) != null) ? $.cookies.get(cookieName).toString().split(',') : new Array();

            var p = -1;
            for (var i = 0; i < v.length; i++) {
                if (v[i] == propertyID) {
                    p = i
                    break;
                }
            }
            
            if (p == -1) {
                if (v.length == 10) {
                    v.remove(0);
                    $(document).ready(function() {
                        $('.LastProperties').children('span').text((parseInt($('.LastProperties').children('span').text()) - 1).toString())
                    });
                }
                v.push(propertyID);
                $.cookies.set(cookieName, v.join(','), cookies_ExpiresAt());
                //alert('O imóvel foi adicionado à lista de últimos Imóveis com sucesso.');
                $(document).ready(function() {
                    $('.LastProperties').children('span').text((parseInt($('.LastProperties').children('span').text()) + 1).toString())
                });
            } else {
                //alert('O imóvel já se encontra na lista de favoritos.');
            }
            
        } else {
            $(this).attr('checked', false);
            //alert('Não é possível adicionar o imóvel à lista de favoritos.\nPara utilizar esta funcionalidade é necessário que o Browser que utiliza permita a utilização de cookies.');
        }
    }
}

function doc_GetHeight() {
    var h = 0;

    if (typeof (window.innerWidth) == 'number') {
        h = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        h = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        h = document.body.clientHeight;
    }

    return h;
}

function dialog_OnInit(w, h, src) {
    var lb = document.createElement('div');
    var sw = doc_GetHeight();

    if (document.body.scrollHeight > sw) sw = document.body.scrollHeight;

    with (lb) {
        id = 'lightbox';
        style.height = sw + 'px';

        setAttribute("onclick", "dialog_OnUnload();");
    }

    document.body.appendChild(lb);

    dialog_OnLoad(w, h, src);
}

function dialog_OnLoad(w, h, s) {
    var d = document.createElement('div');

    with (d) {
        id = 'dialog';

        style.width = w + 'px';
        style.height = h + 'px';

        style.top = ($(window).height() - h) / 2 + $(window).scrollTop() + 'px';
    }

    var cd = document.createElement('div');

    with (cd) {
        className = 'close';
        innerHTML = 'Fechar';

        setAttribute("onclick", "dialog_OnUnload();");
    }

    d.appendChild(cd)

    var i = document.createElement('iframe');

    var mw = 4;
    var mh = 18;

    with (i) {
        width = (w - mw) + 'px';
        height = (h - mh) + 'px';

        setAttribute('frameborder', 0);
        setAttribute('scrolling', 'no');
        setAttribute('src', s);
        setAttribute('allowtransparency', 'true');
    }

    d.appendChild(i);
    document.body.appendChild(d);
}

function dialog_OnUnload() {
    document.body.removeChild(document.getElementById('lightbox'));
    document.body.removeChild(document.getElementById('dialog'));
}

//Function to change de Location combos
function SetupMarket(qsDistrict, qsCounty, handlersPath, clientID, loadingFeedback, showOnlyWithProperties, emptyCounty) {
    $(document).ready(function() {

        //Fields declaration
        var ddlDistrict = "#" + clientID + "_ddlDistrict";
        var ddlCounty = "#" + clientID + "_ddlCounty";
        var tbHiddenBox = "#" + clientID + "_tbHidden";

        if (($(ddlDistrict).val() != undefined) && ($(ddlDistrict).val() > 0)) {
            BindCounties();
        }

        //SelectIndexChange - ddlDistrict
        $(ddlDistrict).change(function() {
            BindCounties();
        });

        $(ddlCounty).change(function() {
            $(tbHiddenBox).val($(ddlCounty + ' option:selected').text());
        });

        //GetCounties
        function BindCounties() {

            //RESET ddlCounty
            $(ddlCounty).html("");
            $(ddlCounty).attr("disabled", "disabled");

            //GET IDs of District
            var idDistrict = $(ddlDistrict).val();

            //IF SELECTED District
            if (idDistrict != 0 || idDistrict == undefined) {

                //GET Counties via JSON
                $(ddlCounty).append($("<option></option>").val(0).html(loadingFeedback));

                $.getJSON(handlersPath + "/GetCounties.ashx?cid=" + idDistrict + "&withprop=" + showOnlyWithProperties.toString, function(Counties) {

                    if (Counties != null && Counties != "-1") {
                        $(ddlCounty).html("");
                        //APPEND Counties ddlCounty
                        var hasRecords = false;

                        if (emptyCounty != "") $(ddlCounty).append($("<option></option>").val(0).html(emptyCounty))
                        else $(ddlCounty).append($("<option></option>").val(0).html(""))

                        $.each(Counties, function() {
                            $(ddlCounty).append($("<option></option>").val(this['VALUE']).html(this['TEXT']));
                            hasRecords = true;
                        });

                        //ENABLE ddlCounty
                        if (hasRecords) {
                            $(ddlCounty).removeAttr("disabled");
                        }

                        ParseQueryString(qsCounty, ddlCounty);

                    }
                    else {
                        $(ddlCounty).html("");
                    }
                });
            }
        }

        //get a specified key of query string
        function ParseQueryString(key, control) {

            var id = $.jqURL.get(key);

            if (id != "undefined" && id != null) {


                if (key == qsDistrict || key == qsGroup) {
                    $(control).val(id.toString())
                }
                else {
                    if ($(control).css("display") != "none") { selectItem(id, control); }
                }

                switch (key) {
                    case qsDistrict: BindCounties(); break;
                    case qsCounty: BindParishes(id); break;
                    case qsParish: BindZones(); break;
                }
            }
        }
    });
}

function AutoScroller() {
    $(window).load(function() {
        $('html, body').animate({ scrollTop: $('#PropertyList').offset().top }, 1500);
    });
}
