﻿$(document).ready(function () {
    InitForm();
})

function InitForm() {

    $('.resetSearch').bind("focus", function () {
        
        var resize = false;
        if ($('#ContactAgents').css("display") != "none") { resize = true; };
        $('#ContactAgents').hide();
        $('#btnContactAgents').show();
        $('[id*=_mp]').show();
        $('.modalCancels').show();
        //$.fn.modalform.centre('#Modal')
        if (resize) {
            $('#Status').html("");
            resizeVerticalAnimation("FormHeight");
         };
    });
    $('#RequestValuationForm').bind("keydown", function (e) {

        if (!e) var e = window.event;
        if (e.keyCode == 13) {
            e.cancelBubble = true;
            if (e.stopPropagation) e.stopPropagation();
            $('[id$="AgentSearchButton"]').click();
            return false;
        }
    });

    if ($.browser.msie && $.browser.version.substr(0, 1) <= 7) {
        $("a.majorButtonCancel").removeAttr("href");
        $('[id$="txtPostcode"]').keydown(function (e) {
            if (e.keyCode == 13) {
                return false;
            }
        });
    }

    $("a[id$=NoPropLink]").click(function (e) {
        e.preventDefault();
        return NoPropertyToSell();
    });
}

function callback() { InitForm();}

function SelectAll(selector) {
    $(selector + ' input[type = "checkbox"]').prop("checked", "checked").parent().attr("class", "checked clearfix")

}
function SelectNone(selector) {
    $(selector + ' input[type = "checkbox"]').prop("checked", "").parent().attr("class", "clearfix")

}
var noresultsMessage = $('<p class="bold">No agents were found matching your criteria</p>');

function ValidateAgentSelections(obj, args) {
    args.IsValid = false;
    var AgentList = $('input', '#EmailAgentList'), i = 0;
    while (checkbox = AgentList[i++]) {
        if (checkbox.checked) {
            args.IsValid = true
            break;
        }
    }

}


var obj = null;
function ShowDialog(objId) {
    $('[id$="EmailToAllButton"]').bind('click', function () {
        if (Page_IsValid) { $('#ValuationHourGlass').show(); }
    });
    $(document).bind('keydown.modal', keyUp);
    $('#valuationRequest .sellingHomeBox').css('border', '1px solid #a21951');
    $('#valuationRequest .requestValuation').css('margin-left', '0');
     $('#ValuationHourGlass').hide();
    
}

function keyUp(e) {
    keycode = e.which || e.keyCode;
    if (keycode == 27) { CloseDialog(); $(document).unbind('keydown.modal'); }
}

function CleanUpDialog() {
    $('#Status').html("");
    $('#ContactAgents').hide()
    $('.requestValuation').find("select").each(function() { this.selectedIndex = 0 }).end().find("input[type='text']").val("").end().find("textarea").val("");
    $('#btnContactAgents').show();
    $('.modalCancels').show();
    $('[id*=_mp]').show();
    resizeVerticalAnimation("FormHeight");
}

function CloseDialog() { closeModalDialog(); return false;}

function NotNow() {
    var cookieName = "notnow";
    var date = new Date();
    var todayString = date.toDateString();
    date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
    
    if ($.cookie(cookieName) == null) {
        $.cookie(cookieName, "1," + todayString, { expires: date});
    } else {
        var newValue = Number($.cookie(cookieName).split(",")[0]) + 1;

        if (newValue == 3) {
            return NoPropertyToSell();
        } else {
            $.cookie(cookieName, newValue + "," + todayString, { expires: date });
        }
    }
    return CloseDialog();
}
var maxNoteLength = 500;
function CleanUpValue(obj) { obj.value = obj.value.replace(/<[^>*]/g, "");}

function UpdateCounter() {
    var notes = $('#ContactAgents .notes'), value = notes.val(), len = value.length, msgStr = $("#ContactAgents [id$='lblCharactersLeft']");
    if (value != null && value != "Write your message here...")
        msgStr.html(maxNoteLength - len);
    if (len > maxNoteLength) {
        notes.val(value.substr(0, maxNoteLength)); msgStr.html(0); notes.scrollTop(notes[0].scrollHeight + 100000);
    }
}

function NoPropertyToSell() {
    $.cookie("npts", "true", { expires: 365, path: '/' });
    return CloseDialog();
}

String.prototype.trim = function() {
    return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

function IsValidPostCode(str){
    var reg = new RegExp("^[A-Za-z]{1,2}[0-9R][0-9A-Za-z]? ?[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$");return reg.test(str.toUpperCase());
}

function GetAgents() {

    var postcode = $('#valuationRequest input[id$=txtPostcode]').val(),
        propertyType = $('.ddlPropertyType', '#RequestValuationForm').val(),
        bedrooms = $('.ddlBedrooms', '#RequestValuationForm').val(),
        worthFrom = $('.txtWorthFrom', '#RequestValuationForm').val(),
        worthTo = $('.txtWorthTo', '#RequestValuationForm').val(),
        AgentList = $('#EmailAgentList'),
        listItems = "",
        ContactAgents = $('#ContactAgents'),
        hourGlass = $('#ValuationHourGlass'), 
        statusMsg = $('#Status');

    statusMsg.html("");
    $('.v_status').html('');
    if (propertyType == "" || bedrooms == "" || postcode == "") {
        statusMsg.html('<p class="bold">You must specify your postcode, type of property and number of bedrooms first</p>');
    } else {

        var minPrice = $("input[id$=txtWorthFrom]")
        var minVal = minPrice.val().replace(",", "");
        var maxPrice = $("input[id$=txtWorthTo]");
        var maxVal = maxPrice.val().replace(",", "");

        if (!isNaN(minVal)) minVal=(minVal-0); // Force numeric
        if (!isNaN(maxVal)) maxVal=(maxVal-0); // Force numeric

        if (!IsValidPostCode(postcode.trim())) { statusMsg.html('<p class="bold">Your postcode appears to be invalid</p>'); }
        else if (isNaN(minVal) || isNaN(maxVal)) { statusMsg.html('<p class="bold">Please enter numbers only for how much your property is worth.</p>'); }
        else if ((minVal < 0) || (maxVal < 0)) { statusMsg.html('<p class="bold">Please enter positive numbers for how much your property is worth.</p>'); }
        else if ((minVal != "") && (maxVal != '') && (maxVal < minVal)) { statusMsg.html('<p class="bold">Your From price is greater than your To price.</p>'); }
        else {
            $(".modalCancels").hide();
            hourGlass.show();
            $.ajax({
                type: 'POST',
                url: '/svc/agentDirectoryService.asmx/GetAgentsForValuation',
                data: "{'postcode':" + "'" + postcode + "', 'propertyType' : '" + propertyType + "', 'bedrooms' : '" + bedrooms + "', 'minPrice' : '" + worthFrom + "', 'maxPrice' : '" + worthTo + "'}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                timeout: 10000,
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    if (textStatus != null && textStatus == "timeout") { statusMsg.html('<p class="bold">Search timeout - please try your search again.</p>'); }
                    else { statusMsg.html('<p class="bold">An error occured when searching for agents</p>'); }
                    hourGlass.hide(); $('#btnContactAgents').show(); $('[id*=_mp]').show();
                },
                success: function (data) {

                    if (data) {

                        var o = eval("(" + ((data.d) ? data.d : data) + ")");
                        var Agents = o["Agents"];
                        //var IsSecondSearch = o["IsSecondSearch"];
                        var Message = o["Message"];
                        var ValidationError = o["ValidationError"];
                        if (ValidationError == true) {
                            hourGlass.hide();
                            statusMsg.html('<p class="bold">You must specify your postcode, type of property and number of bedrooms first</p>');
                            resizeVerticalAnimation("FormHeight");
                        }
                        else if (Agents != null) {
                            var AgentsShown = "";
                            for (i = 0; i < Agents.length; i++) {
                                listItems += "<li class=\"clearfix\"><input type=\"checkbox\" name=\"EmailAgentCheckBox\" value=\"" + Agents[i]["id"] + "\" id=\"EmailAgentCheckBox" + i
                                    + "\" /><label for=\"EmailAgentCheckBox" + i + "\" >" + Agents[i]["name"] + "<br />" + Agents[i]["tel"] + "</label></li>";
                                AgentsShown += Agents[i]["id"] + ",";
                            }
                            $("[id$='_AgentsShownList']").val(AgentsShown);

                            AgentList.html(listItems);
                            $('input', AgentList).bind('click', function () { this.parentNode.className = (this.checked) ? 'checked clearfix' : 'clearfix' });

                            if (Message != null && Message != "" && Message.toLowerCase() != "none") statusMsg.html(Message)
                            hourGlass.hide();

                            ContactAgents.show();
                            //$.fn.modalform.centre('#modalDialog');

                            $('#btnContactAgents').hide();
                            $('[id*=_mp]').hide();
                            resizeVerticalAnimation("FormHeight");
                        }
                        else {
                            hourGlass.hide();
                            if (Message && Message != "" && Message.toLowerCase() != "none") {

                                statusMsg.append(Message);
                            }
                            else {
                                statusMsg.append(noresultsMessage);
                            }
                            $('.modalCancels').show();
                            resizeVerticalAnimation("FormHeight");
                        }
                    }
                    else {
                        hourGlass.hide();
                        statusMsg.append(noresultsMessage);
                        $('.modalCancels').show();
                    }
                }
            });
        }
    }
}

function resetValidation() {
    $("#valuationRequest [id*='Validator']").css('display', 'none');
    $('#valuationRequest input').removeClass('warning_field');
}

function validatePostcodeBox(sender, args) {
    $('.v_status').html('');
    if ((IsValidPostCode($(".avm_pstCode").val()) && ($(".avm_pstCode").val() != ""))) { $('#Status').html(''); args.IsValid = true; }
    else { $('#Status').html('<p class="bold">Your postcode appears to be invalid</p>'); args.IsValid = false; }
}

function disableEnterKey(e) {
    var key;
    if (window.event) {
        key = window.event.keyCode; //IE
    }
    else {
        key = e.which; //firefox     
    }

        return (key != 13);
}


(function ($) {

    $('.avm_pstCode').click(function () { $(this).addClass("focused"); });

    function validatePostcode(obj) {
        if (IsValidPostCode($(".avm_pstCode").val()) && ($(".avm_pstCode").val() != "")) {
            $('#PostcodeRow').removeClass("warning_field");
            return true;
        }
        else {
            obj.find('#PostcodeRow').addClass("warning_field");
            obj.find(".avm_pstCode").val("");
            obj.find(".avm_pstCode").focus();
            obj.find(".showToolTip").show();
            return false;
        };
    };

    $(".avm_pstCode").keydown(function () {
        if (IsValidPostCode($(".avm_pstCode").val()) || ($(".avm_pstCode").val() == "")) {
            $('#PostcodeRow').removeClass("warning_field");
        };
    });

    $('#EstateAgentValuation').click(function () {
        if (validatePostcode($(this).parent().parent())) {
            $(this).attr("href", "/?dnpu=true&show-mp=false&postcode=" + $(".avm_pstCode").val().toUpperCase());
            ShowValuationModal(this);
        };
        return false;
    });

    $('#MousePriceValuation').click(function () {
        $('.v_status').html('');
        if ($(this).parent().parent().attr("id") == "btnRow") {
            if (!(IsValidPostCode($("#valuationRequest .avm_pstCode").val()) && ($("#valuationRequest  .avm_pstCode").val() != ""))) {
                $('#Status').html('<p class="bold">Your postcode appears to be invalid</p>');

            }
            else {
                $(this).attr("href", "/?dnpu=true&postcode=" + $(".avm_pstCode").val().toUpperCase());
                ShowMousePriceModal(this);
            }
        } else {
            if (validatePostcode($(this).parent().parent())) {
                $(this).attr("href", "/?dnpu=true&postcode=" + $(".avm_pstCode").val().toUpperCase());
                ShowMousePriceModal(this);
            };
        };
        return false;
    });

    $(".closer").click(function () { $(this).parent().parent().hide();});

    $(".avm_pstCode").keypress(function (e) { if (e.which == '13') { e.preventDefault(); } });

    $('.fullItemContainer').click(function (e) {
    
        $target = $(e.target).closest("a");

        if($target.length > 0 && $target.hasClass("askAnExpert")){
            var holderDiv = $(this);
        
            $target.attr("href", "/?dnpu=true&hv-address=" + escape(holderDiv.find('.fullItemLeft .line1').text()) + "&show-mp=false&postcode=" + holderDiv.find('.fullItemLeft .line1 .avm_pc').text().toUpperCase());
            ShowValuationModal($target);
            return false;
        }
    });
})(jQuery);

