﻿$(document).ready(function() {
    $('.resetSearch').bind("focus", function() {
        $('#Status').html("");
        $('#ContactAgents').hide();
        $('#btnContactAgents').show();
        $('.modalCancels').show();
       //$.fn.modalform.centre('#Modal')

    });
    $('#RequestValuationForm').bind("keypress", function(e) {


        if (!e) var e = window.event;
        if (e.keyCode == 13) {
            e.cancelBubble = true;
            if (e.stopPropagation) e.stopPropagation();
            $("input[type=image]", "#btnContactAgents").click();
            return false;
        }


    })
 
})

function SelectAll(selector) {
    $(selector + ' input[type = "checkbox"]').attr("checked", "checked").parent().attr("class", "checked clearfix")

}
function SelectNone(selector) {
    $(selector + ' input[type = "checkbox"]').attr("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) {

    if (obj == null) {
        obj = new Object();
        $(obj).modalform({ allow_page_scroll: true, onEsc: CleanUpDialog, modal_id: '#Modal', pos_middle: true })
     $(obj).trigger("show");
    }
    else {
        $(obj).trigger("show");
    }
}

        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();
        }

function AutoShowDialog(objId, showValidationError) {
    if ($.cookie("npts") == null && $.cookie("notnow") == null) {
        if ($.cookie("pvc") == null || Number($.cookie("pvc").split(",")[0]) < 1 || showValidationError) {
            // The server controls whether the html for the modal is output to the source (after the 6 property view)
            // only show if the cookie is 0, i.e if a user views a property and uses the back button the cookie value would have increased to 1
            // cookie is only 0 when the dialog was loaded for the first time.
            var date = new Date();
            date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
            $.cookie("pvc", "1", { expires: date });
            ShowDialog();
        }
    }
}

function CloseDialog() {
    $(document).trigger('close.modalform', '#Modal');
    CleanUpDialog();
     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();
}

function CleanUpValue(obj) {
    obj.value = obj.value.replace(/<[^>*]/g, "");
}

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-Z]{1,2}[0-9R][0-9A-Z]? ?[0-9][ABD-HJLNP-UW-Z]{2}$");
   
     return reg.test(str.toUpperCase());
}

function GetAgents() {

    var postcode = $('.txtPostcode', '#RequestValuationForm').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("");
    if (propertyType == "" || bedrooms == "" || postcode == "") {
        statusMsg.html('<p class="bold">You must specify your postcode, type of property and number of bedrooms first</p>');
    }
    else {
        if (!IsValidPostCode(postcode.trim())) {
            statusMsg.html('<p class="bold">You\'re postcode appears to be invalid</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>');
                        alert(textStatus);
                    }
                    hourGlass.hide(); $('#btnContactAgents').show();
                },
                success: function(data) {
                    if (data.length > 0) {

                        var o = eval("(" + 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>');

                        }
                        else if (Agents != null) {
                            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>"
                            }

                            AgentList.html(listItems);
                            $('input', AgentList).bind('click', function() { this.parentNode.className = (this.checked) ? 'checked clearfix' : 'clearfix' });

                            if (Message != null) statusMsg.html(Message)
                            hourGlass.hide();
                            
                            ContactAgents.show();$.fn.modalform.centre('#Modal');
                            $('#btnContactAgents').hide();

                        }
                        else {
                            hourGlass.hide();
                            if (Message != null) {
                                statusMsg.append(Message);
                            }
                            else {
                                statusMsg.append(noresultsMessage);
                            }
                            $('.modalCancels').show();

                        }


                    }
                    else {
                        hourGlass.hide();
                        statusMsg.append(noresultsMessage);
                        $('.modalCancels').show();

                    }
                }
            });
        }
    }
}