﻿function InitializeHomePage() {

    $(document).ready(function () {
        $(".hoverpanel a").click(function () {
            HandleTab($(this).parent());
        });

    });
}

function JCarousel(id) { 
    $(id).jcarousel();
}

function AgentDetailCarousel() {
    $('#homepage_featuredImpressions').jcarousel({
     itemLoadCallback:updateVisibleRange,
     scroll: 4,
     animation: "slow"
     }); 
}

function updateVisibleRange(carousel, state){
    $("#listings_visible_range span").html(carousel.first + " - " + carousel.last);
 }

 function SwapImage(id) {
    var largeimageid = $('#LargeImage' + id);
    $('.detailproper-hdr a').hide();
    largeimageid.show();
}

function renderButton(buttonLabel, pagenumber, pagecount, buttonClickCallback) {

    var $Button = $('<li class="pgNext">' + buttonLabel + '</li>');

    var destPage = 1;

    // work out destination page for required button type
    if (buttonLabel.toLowerCase().indexOf("prev") != -1) {
        destPage = pagenumber - 1;
    }
    if (buttonLabel.toLowerCase().indexOf("next") != -1) {
        destPage = pagenumber + 1;
    }

    // disable and 'grey' out buttons if not needed.
    if (buttonLabel.toLowerCase().indexOf("prev") != -1) {
        pagenumber <= 1 ? $Button.addClass('pgEmpty') : $Button.click(function () { buttonClickCallback(destPage); });
    }
    else {
        pagenumber >= pagecount ? $Button.addClass('pgEmpty') : $Button.click(function () { buttonClickCallback(destPage); });
    }
    $Button.mouseover(function () { document.body.style.cursor = "pointer"; }).mouseout(function () { document.body.style.cursor = "auto"; });
    return $Button;
}



function SetupColorbox(popupname, linkname) {
    $(function () {
        //default options for colorbox call
        var colorboxOps = {
            overlayClose: false,
            close: "close",
            onOpen: function () {
                $("#cboxContent").css("background-color", "#fff");
            }
        }

        //recursive function for handling rendered SignIn partial
        var handleCalcPartial = function () {
            var popup = $(popupname);
            popup.find("form").submit(function (e) {
                e.preventDefault(); //no postback
                //alert($(this).attr("action"));

                $.post(
                        $(this).attr("action"),
                        $(this).serialize(),
                        function (json) {
                            if (json.Reload) {
                                if (json.IsConfirmed) {
                                    $(this).colorbox({ html: json.Html, open: true });
                                }
                                else {
                                    popup.replaceWith(json.Html);
                                    $.fn.colorbox.resize();
                                    handleCalcPartial();
                                }

                                if (json.Omniture != null) {
                                    AddOmniture(json.Omniture);
                                } //if json.omniture

                            } //if json.Reload
                            else {
                                $(linkname).colorbox.close();
                            } //else
                        }, //function(json)
                        "json"
                    ); //post
            }); //form.submit

        } //handleCalcPartial func()

        var CalcOps = $.extend(colorboxOps, {
            onComplete: handleCalcPartial,
            scrolling: false
        });

        //making anchor link to a colorbox
        $(linkname).colorbox(CalcOps);
    });
}

function Close() {
    $(this).colorbox.close();
}

function HandleTab(tab) {
    $(tab).addClass("selected");
    $("#footerplace").empty();
    $(".hoverpanel a").removeClass("selected");
    if ($(tab).hasClass("pan01")) {
        $(".pan01 a").addClass("selected");
        $("#advancedsearchForm .agent").hide();
        $("#advancedsearchForm .homes").show();
        $("#advancedsearchForm .foreclosure").show();
        $('#SearchType').val(0);
        $("#search_country_lnk").attr("href", "javascript:CountryDrop();");
        $("#ASHomeMarkets").tmpl("").appendTo("#footerplace");
        omAdvSearch('home');
    }
    else if ($(tab).hasClass("pan02")) {
        $(".pan02 a").addClass("selected");
        $("#advancedsearchForm .agent").show();
        $("#advancedsearchForm .homes").hide();
        $("#advancedsearchForm .foreclosure").hide();
        $('#SearchType').val(2);
        $("#search_country_lnk").attr("href", "javascript:CountryDrop();");
        $("#ASAgentMarkets").tmpl("").appendTo("#footerplace");
        omAdvSearch('agent');
    }
    else if ($(tab).hasClass("pan03")) {
        $(".pan03 a").addClass("selected");
        $("#advancedsearchForm .agent").hide();
        $("#advancedsearchForm .foreclosure").show();
        $("#advancedsearchForm .homes").hide();
        if ($("#SearchText").val().indexOf('Cities In') != -1 || $("#SearchText").val().indexOf('Cities-In') != -1) {
            $("#SearchText").val('');
        }
        $('#SearchType').val(1);
        $("#Country").val("USA");
        $("#search_country_lnk").attr("href", "javascript:void();");
        $("#search_country_lnk").text("United States");
        $("#ASforeclosureMarkets").tmpl("").appendTo("#footerplace");
        omAdvSearch('foreclosure');
    }
}
function setAdvSearcOmniture(type) { 
    
}

//*******************
//***Async Calls*****
//*******************

//HTTP Get to display Sign In Modal
function LoadMortgageRates() {
$.ajax({
		url: "/Homes/MortgageRate",
		type: "POST",
		cache: false,
		success: function(result) {
			if (result != null) {
				$("#MortgageRatesModal").empty();
				$("#MortgageRatesModal").html(result.htmldt);
				$("#MortgageRatesModal").jqmShow();
			}
		}
	});
}

function LoadMoneyButtonPage(x, pag, url) {
	RealEstateResource(x, pag, url);
	window.open(url);
}

function LoadMortgageRatesAction() {
	RealEstateResource(this, 'Get Mortgage Rates');
	$.ajax({
		url: "/Homes/MortgageRates",
		type: "POST",
		cache: false,
		success: function (result) {
			if (result != null) {
				$("#MortgageRatesModal").empty();
				$("#MortgageRatesModal").html(result);
				$("#MortgageRatesModal").jqmShow();
			}
		}
	});
}


//HTTP Get to display Sign In Modal
function LoadSignIn() {
	$.ajax({
		url: "/Account/LogOn",
		type: "GET",
		cache: false,
		success: function (data) {
			if (data != null && data.length > 0) {
				$("#AuthenticationModal").empty();
				$("#AuthenticationModal").html(data);
				$("#AuthenticationModal").jqmShow();
			}
		}
	});
}


function AuthoriseUser(propertyId) {
    var popupname = '#contact-login-pop';
    var linkname = '#SaveProperty' + propertyId;
    $(function () {
        //default options for colorbox call
        var colorboxOps = {
            overlayClose: false,
            close: "close",
            onOpen: function () {
                $("#cboxContent").css("background-color", "#fff");
            }
        }

        //recursive function for handling rendered SignIn partial
        var handleCalcPartial = function () {
            var popup = $(popupname);
            popup.find("form").submit(function (e) {
                e.preventDefault(); //no postback
                //alert($(this).attr("action"));

                $.post(
                        $(this).attr("action"),
                        $(this).serialize(),
                        function (json) {
                            //alert(json);
                            if (json.Reload) {
                                if (json.Username != null) {
                                    $(".welcome").text("Welcome " + json.Username);
                                    $("#displaycount a").html("Saved Listings (" + json.Count + ")");
                                    $(".sign_reg").html("<a class=\"accountanchor\" href=\"/Account/SavedListings\">Account</a> | <a href=\"/Account/LogOff\">Sign Out</a>");
                                }
                                popup.replaceWith(json.Html);
                                $.fn.colorbox.resize();
                                handleCalcPartial();
                                var pagetype = $("#PageType").val();
                                if (pagetype == "HomeListings") {
                                    ApplyFacets();
                                }
                                if (pagetype == "HomeDetail") {
                                    var id = "#UserActionSave_" + propertyId + " a";
                                    $(id).html("Saved");
                                }
                                OmPropertyActivity(this, "save this home");
                            } //if
                            else {
                                $(linkname).colorbox.close();
                            } //else
                        }, //function(json)
                        "json"
                    ); //post
            }); //form.submit

        } //handleCalcPartial func()

        var CalcOps = $.extend(colorboxOps, {
            onComplete: handleCalcPartial,
            scrolling: false
        });

        //making anchor link to a colorbox
        $(linkname).colorbox(CalcOps);
    });

}

function SaveListing(propertyId, addressLine1, city, state, country) {
    var propertyinfo = addressLine1 + " " + city + " " + state + " " + country;
    var data = { propertyId: propertyId, propertyinfo: propertyinfo }
    AjaxPosttoColorBoxPopUp(this, "/Account/SaveProperty", data);
    var id = "#UserActionSave_" + propertyId + " a";
    $(id).html("Saved");
    OmPropertyActivity(this, "save this home");
}

function RemoveProperty(propertyId, addressLine1, city, state, country) {
    var confirmationText = "<div id=\"remove_listing\"><div id=\"personalization_tb_hd\"><h2>Remove Listing</h2>";
    confirmationText += "<div class=\"close\"></div></div><div class=\"personalization_tb_body clearfix\">";
    confirmationText += "<p>Are you sure you want to <em>permanently</em> remove <br/><strong>";
    confirmationText += addressLine1 + " " + city + " " + state + " " + country;
    confirmationText += "</strong> from your saved listings?</p></div>";
    confirmationText += "<div id=\"personalization_tb_footer\"><a class=\"btn\" href=\"/Account/RemoveProperty/"+propertyId+"\">Remove</a>";
    confirmationText += "<span>or</span><a onclick=\"close();\" href=\"#\">Do Not Remove</a></div></div>";
    $(this).colorbox({ html: confirmationText, open: true });
    return false;
}

//Helper for Ajax POST and ColoBox Pop Up
function AjaxPosttoColorBoxPopUp(id, url, data) {
    $.ajax({
        url: url,
        type: "POST",
        cache: false,
        data: data,
        success: function (result) {
            if (result != null) {
                $(id).colorbox({ html: result.Html, open: true });
            }
        }
    });
}

function SubmitByEnterkey(e, formID) {
    if (window.event) {
        KeyCode = e.keyCode;
    } else if (e.which) {
        KeyCode = e.which;
    }
    if (KeyCode == 13) {
        if (formID != undefined) {
            if (formID == "userlogin") {
                Login();
            } else if (formID == "forgot_pw_form") {
                GetPassword();
            }
        }
    } else {
        return false;
    }
}

 
//HTTP Post to Login the User from Sign In Modal
function Login() {
    $.ajax({
        url: "/Account/Logon",
        type: "POST",
        cache: false,
        data: { EmailAddress: $("#EmailAddress").val(), Password: $("#Password").val(), RememberMe: $("RememberMe").val() },
        success: function (result) {
            if (result != null && result.name != null) {
                $("#AuthenticationModal").empty();
                $("#AuthenticationModal").jqmHide();
                $(".welcome").text("Welcome " + result.name);
                $("#displaycount a").html("Saved Listings (" + result.listingscount + ")");
                $(".sign_reg").html("<a class=\"accountanchor\" href=\"/Account/SavedListings\">Account</a> | <a href=\"/Account/LogOff\">Sign Out</a>");
                AccountAnchorHover();
                var canfacet = $("#CanFacet").val();
                if (canfacet == "True") {
                    ApplyFacets();
                }
                AddOmniture(result.omniture);
            }
            else {
                $("#AuthenticationModal").empty();
                $("#AuthenticationModal").html(result);
                $("#AuthenticationModal").jqmShow();
            }
        }
    });
    return false;                                                                                                     
}

function AddOmniture(items) {
    if (items != null) {
        $("#OmnitureLiteral").html("<script language='javascript' type='text/javascript'>" + eval(items) + "</script>");
    }
}

function AccountAnchorHover() {
    $(".accountanchor, #displaycount").hover(function () {
        $("#displaycount").toggle();
    });
}

//Method to Close jqModal
function CloseAuthModal() {
	$("#AuthenticationModal").jqmHide();
	$("#MortgageRatesModal").jqmHide();
}

//Method to Open Forgot Password Modal
function LoadForgotPassword() {
    $.ajax({
        url: "/Account/ForgotPassword",
        type: "GET",
        cache: false,
        success: function (data) {
            if (data != null && data.length > 0) {
                $("#AuthenticationModal").empty();
                $("#AuthenticationModal").html(data);
                $("#AuthenticationModal").jqm();
            }
        }
    });
}

//Method to Post data to ForgotPassword Action result
function RequestPassword() {
    $.ajax({
        url: "/Account/ForgotPassword",
        type: "POST",
        cache: false,
        data: { EmailAddress: $("#EmailAddress").val() },
        success: function (result) {
            $("#AuthenticationModal").empty();
            $("#AuthenticationModal").html(result);
        }
    });
}

//var IsSelectedValue = false;
//Search AutoComplete
function InitializeSearchBox() {
    var searchBox = $("#SearchText");

    SetDefaultSeachBoxText(searchBox);

    searchBox.blur(function () {
        SetDefaultSeachBoxText(searchBox);
    });

    searchBox.focus(function () {
        if (searchBox.val() == "City and State, or Zip Code") {
            searchBox.val("");
        } 
    });

    $("#SearchText").autocomplete('/Search/Find/', {
        minChars: 2,
        extraParams: {
            SearchText: function () { return searchBox.val(); },
            Country: function () { return $("#Country").val(); }
        }
    }).result(function (event, data, formatted) {
        if (data != null && data[1] != null) {
            $("#Keyword").attr("value", data[0]);
            $("#KeywordType").attr("value", data[1]);
        }
    });
}

function SetDefaultSeachBoxText(elem) {
    if ($.trim(elem.val()) == "" || $.trim(elem.val()) == ",") { elem.val("City and State, or Zip Code"); }
}

function isZip(s) {
    // Check for correct zip code
    reZip = new RegExp(/(^\d{5}$)|(^\d{5}-\d{4}$)/);

    if (!reZip.test(s)) {
        return false;
    }
    return true;
}

function ShowHideFooterUrls() {
    $(".showHideHomesAnchor a").click(function () {
        $(".moreNearestCities").toggle();
        $(".showHideHomesAnchor").toggle();
        return false;
    });

    $(".showHidePropAnchor a").click(function () {
        $(".moreNearestProperties").toggle();
        $(".showHidePropAnchor").toggle();
        return false;
    });

    $(".showHideZipCodeAnchor a").click(function () {
        $(".moreNearestZipCodes").toggle();
        $(".showHideZipCodeAnchor").toggle();
        return false;
    });
}

function ValidateKeyword() {
    $('.basicsearch #SearchText').keypress(function (event) {
        if (event.keyCode == '13') {
            AutoPopulateSearchText();
            return false;
        }
    });

    $("#ASearchTextSubmit").click(function () {
        $("#search_interior").addClass("waitforaction");
        ValidateASForm();
    });

    $('#advancedsearchForm #SearchText').keypress(function (event) {
        if (event.keyCode == '13') {
            ValidateASForm();
            return false;
        }
    });

    $("#SearchTextSubmit").click(function () {
        AutoPopulateSearchText();
    });

    $("#search_alert").focusout(function () {
        search_alert_close();
    });

    $("#search_alert_close a").click(function() {
        $("#search_alert").hide();
    });

} //ValidateKeyword

function AutoPopulateSearchText() {
    var currentkeywordvalue = $("#SearchText").attr("value");
    var result = $(".ac_results ul").find("li"); //Get any result from autocomplete
    if (result != null && result.length == 1) {
        var text = removeHTMLTags(result.html());
        if (text != null) {
            var parsedtext = text.replace(/,/g, '');
        }

        if (currentkeywordvalue.toLowerCase() != parsedtext.toLowerCase())
            return ValidateKeywordTyped();
        else {
        	var keywords = text.split(",");
        	if (keywords.length == 1) { //Province: Newfoundland (without comma)
        		$("#Keyword").attr("value", text);
        		$("#SearchText").val(text);
        		$("#KeywordType").attr("value", 9);
        		document.forms[0].submit(); return false;
			}
            else if (keywords.length == 2) { //City, State: Austin, TX
                $("#Keyword").attr("value", text);
                $("#SearchText").val(text);
                if ($.trim(keywords[1]).length == 2) {
                    $("#KeywordType").attr("value", 0);
                    document.forms[0].submit(); return false;
                }
                else if ($.trim(keywords[1]).length == 3) {  //State, Country: Texas, USA
                    $("#KeywordType").attr("value", 1);
                    document.forms[0].submit(); return false;
                }
            }
            else if (keywords.length == 3) { //Neighborhood, City, St: West Lake Hills, Austin, TX
                $("#Keyword").attr("value", text);
                $("#SearchText").val(text);
                $("#KeywordType").attr("value", 2);
                document.forms[0].submit(); return false;
            }
        }
    }
    else
        return ValidateKeywordTyped();
}

function removeHTMLTags(htmlstring) {
    if (htmlstring) {
        var stringdiv = document.createElement("div");
        stringdiv.innerHTML = htmlstring;
        if (document.all) { return stringdiv.innerText; }
        else { return stringdiv.textContent; }
    }
}

function ValidateASForm() {
    if (parseInt($("#SearchType").val()) == 2) {
        ValidateKeywordTyped();
    }
    else {
        var isvalid = false;
        
        var vmin = $("#PriceMin").val().replace(",", "").replace(" ", "").replace("Million", "000000");
        var vmax = $("#PriceMax").val().replace(",", "").replace(" ", "").replace("Million", "000000");
        if (vmin == '' && vmax == '') {
            if ($('#MlswebId').val() == '') {
                ValidateKeywordTyped();
                $("#search_interior").removeClass("waitforaction");
                return;
            }
            else {
                ValidateMlsWebId();
                return false;
            } 
        }
        if (vmin.indexOf("NoLimit") != -1 && parseInt(vmax)) { isvalid = false; }
        else if (vmax.indexOf("NoLimit") != -1) { isvalid = true; }
        else {
            var min = parseInt(vmin);
            var max = parseInt(vmax);
            if (min < max) { isvalid = true; }
        }
        if (!isvalid) {
            var helperhtml = "<div class=\"clearfix\" id=\"search_alert_message\">";
            helperhtml += "<p>The minimum price must be less than the maximum price</p></div>";
            helperhtml += "<div id=\"search_alert_close\"><a href=\"javascript:search_alert_close();\">close</a></div>";
            $("#search_alert").html(helperhtml).show();
            return false;
        }
        else {
            if ($('#MlswebId').val() == '' || $('#MlswebId').val().lenght == 0) {
                ValidateKeywordTyped();
            }
        }
    }
}
function ValidateMlsWebId() {
    $.ajax({
        url: "/Search/MlsValidate",
        type: "POST",
        cache: false,
        data: { mlsWebId: $("#MlswebId").val(), SearchText: $("#SearchText").val() },
        success: function (result) {
            if (result.MlsWebIdExist) {
                $("#search_interior").removeClass("waitforaction");
                if (result.count > 1) {
                    if (result.count < 21) {
                        $.fn.colorbox({ html: result.Html, width: "650px", height: "500px" });
                    }
                    else {
                        MSG.confirm("More than 20 properties match your search criteria.<br/> Please further refine your search by entering city, state or zip code."
                      , { buttons: [
                        { type: "image", css: "ok", onReturn: false, src: "../Content/images/buttonOK.png" },
                        { type: "image", css: "close", onReturn: true, src: "../Content/images/buttonclose.png" }
                      ], onComplete:
                              function (returnvalue) {
                                  //                                  if (returnvalue) {
                                  //                                      $.fn.colorbox({ html: result.Html, width: "650px", height: "500px" });
                                  //                                  }
                              }

                      }
                      );

                    }
                } else if (result.count > 0) {
                    window.location = result.detailUrl;
                }
                else MSG.error("<br/>There are no properties which match this criteria.<br/>"
                      , { buttons: [
                        { type: "image", css: "ok", onReturn: false, src: "../Content/images/buttonOK.png" },
                        { type: "image", css: "close", onReturn: true, src: "../Content/images/buttonclose.png" }
                      ]}
                      );
            }
            else {
                var helperhtml = "<div id=\"search_webid_message\"><p>WebID or MLS# '" + $("#MlswebId").val() + "' was not found in our database.</p></div>";
                helperhtml += "<div id=\"search_webid_alert_close\"><a href=\"javascript:search_webid_alert_close();\">close</a></div>";
                $("#search_webid_alert").html(helperhtml).show();
                return false;
            }
        }
    });

}
function search_webid_alert_close() {
    $("#search_webid_alert").hide();
}
function isEmpty(keyword){
    if (keyword == "" | keyword == "City, State or ZipCode")
        return true;
    else
        return false;
}

function ValidateKeywordTyped() {
    var keywordvalue = $("#Keyword").attr("value");
    var keywordTypevalue = $("#KeywordType").attr("value");
    var currentkeywordvalue = $("#SearchText").attr("value");

    if (isEmpty(currentkeywordvalue)) {
        var helperhtml = "<div class=\"clearfix\" id=\"search_alert_message\">";
        helperhtml += "<p>The minimum price must be less than the maximum price</p>";
        helperhtml += "<div id=\"search_alert_close\"><a href=\"javascript:search_alert_close();\">close</a></div>";
        $("#search_alert").html(helperhtml).show();
        return false;
    }
    else if (keywordvalue.toLowerCase() == currentkeywordvalue.toLowerCase() ) {
        //Check if Current Value is the selected value from AutoComplete
        document.forms[0].submit();
        return false;
    } //if
    else {
        //Split the text
        $(".ac_results").hide();
        var searchtextvalue = $("#SearchText").val();
        var keywords = searchtextvalue.split(",");

        if (keywords.length == 1) {


            $.ajax({
                url: "/Search/ValidateFind/",
                type: "POST",
                cache: false,
                data: { SearchText: $("#SearchText").val(), Country: $("#Country").val() },
                success: function (json) {
                    if (json != null) {
                        if (!json.isValid) {//throw error
                            $("#search_alert").html(json.Error).show();
                            return false;
                        }
                        else { //isValid
                            if (json.keywordType != null && json.keywordType != -1) {
                                $("#KeywordType").attr("value", json.keywordType);
                                if (json.SearchText != null && json.SearchText != '') {
                                    $("#Keyword").attr("value", json.SearchText);
                                    $("#SearchText").val(json.SearchText);
                                }
                                else {
                                    $("#Keyword").attr("value", searchtextvalue);
                                    $("#SearchText").val(searchtextvalue);
                                }
                                document.forms[0].submit();
                            } //if json keywordtype == some value other than -1
                            else { //Multiple results
                                $("#search_alert").html(json.Error).show();
                                return false;
                            } //else
                        } //else isValid
                    } //if json not null
                } //success func()
            });     //ajax func()


        }
        else if (keywords.length > 1 && keywords.length < 4) {
            if (ValidateSplittedKeywords(keywords)) {
                if(isNonUSACAN(keywords)) {
                    document.forms[0].submit();
                    $("#KeywordType").attr("value", 7);
                    $("#Keyword").attr("value", searchtextvalue);
                    return false;
                }
                $.ajax({
                    url: "/Search/ValidateKeyword/",
                    type: "POST",
                    cache: false,
                    data: { SearchText: $("#SearchText").val(), Country: $("#Country").val() },
                    success: function (json) {
                        if (json != null) {
                            if (!json.isValid) {//throw error
                                $("#search_alert").html(json.Error).show();
                                return false;
                            } //if- IsValid
                            else {
                                $("#KeywordType").attr("value", json.keywordType);
                                $("#Keyword").attr("value", searchtextvalue);
                                document.forms[0].submit();
                                return false;
                            } //else - IsValid
                        } //json != null
                    } //success
                });   //ajax func()
            } //If - Validate Splitted Keywords
            else {
                helperhtml = "<div class='clearfix' id='search_alert_message'><p>";
                helperhtml += "Your search for <strong>";
                helperhtml += $("#SearchText").val();
                helperhtml += "</strong> could not be found.</p>";
                helperhtml += "<p><strong>Suggestions:<br />You can search by US Zip Code or Canadian Postal Code or Search by Country, City, State or Province</strong></p>";
                helperhtml += "<a style=\"float:right\" href=\"javascript:search_alert_close();\">close</a>";
                helperhtml += "</div>";
                $("#search_alert").html(helperhtml).show();
            }
        } //If keywords.length > 1 & < 3
        else if (keywords.length > 3) {
            helperhtml = "<div class='clearfix' id='search_alert_message'><p>";
            helperhtml += "Your search for <strong>";
            helperhtml += $("#SearchText").val();
            helperhtml += "</strong> could not be found.</p>";
            helperhtml += "<p><strong>Suggestions:<br />You can search by US Zip Code or Canadian Postal Code or Search by Country, City, State or Province</strong></p>";
            helperhtml += "<a style=\"float:right\" href=\"javascript:search_alert_close();\">close</a>";
            helperhtml += "</div>";
            $("#search_alert").html(helperhtml).show();
            return false;
        } //If keywords.length > 3
    }// ELSE
} //ValidateKeywordTyped

function isNonUSACAN(keywords) {
    var Country = $("#Country").val();
    if (keywords.length == 2 & ($.trim(keywords[1]).length == 3)) {
        if (($.trim(keywords[1]) == 'USA' || $.trim(keywords[1]) == 'CAN') || (Country == 'USA' || Country == 'CAN'))
            return false;
        else
            return true;
    }
    else
        return false;
}

function ValidateSplittedKeywords(keywords) {
    for(i = 0; i < keywords.length; i++) {
        if(isNaN(keywords[i]) == false)
            return false;
    }
    return true;
}

function search_alert_close() {
    $("#search_alert").hide();
}


//To Add additional details when optional checkbox is selected in lead Form, contactagent.ascx
function LeadFormMoreInfo() {
    //live is used to add handler for all anchors with this class now and in future
    $('.leadformmoreinfo').live('click', function () { 
        $("#more_info").toggle();
        $("#contact-agent-pop").colorbox.resize();
    });
}



function GotoHome(search, country, sort, page) {
    parent.location.href = '/Search/PerformSearch?SearchText=' + search + '&Type=' + $("#SearchType").val() + '&Country=' + country + '&Sort=' + sort + '&Page=' + page;
}

function GotoCity(search, country) {
    parent.location.href = '/Search/PerformSearch?SearchText=' + search + '&Type=' + $("#SearchType").val() + '&Country=' + country ;
}

function GetNeighborhood(search, country, neighborhoodid) {
    parent.location.href = '/Search/PerformSearch?SearchText=' + search + '&Type=' + $("#SearchType").val() + '&Country=' + country + '&NeighborhoodId=' + neighborhoodid;
}

function SavedListingsDropDownOnChange() {
     $("#listings_sortoptions ul li").click(function () {
    parent.location.href = '/Account/SavedListings?sortBy=' + $(this).attr("id");
    });
} //savedlistings func()

function AgentSearchDropDownOnChange() {
	$("#listings_sortoptions ul li").click(function () {
		var country = $("#Country").val();
		var state = $("#State").val();
		var location = $("#Location").val();

		if (country == "CAN") {
			parent.location.href = "/Agents/" + country + "/" + state + "/" + state + "?Sort=" + $(this).attr("id");
		}
		else if (state != "" & location != "") {
			parent.location.href = "/Agents/" + country + "/" + state + "/" + location + "?Sort=" + $(this).attr("id");
		}
		else {
			parent.location.href = "/Agents/" + country + "?Sort=" + $(this).attr("id");
		}
	}); 
} //savedlistings func()

function SavedListingsDivOnHover() {
    $(".rolloffmode").hover(function () {
        $(this).toggleClass("rollonmode")
        $(this).find(".saved_tools").toggle();
    });
} //savedlistings func()

function RegisterUser() {
    $("#userRegisterForm").live('click', function () {
        $.ajax({
            url: "/Account/Register/",
            type: "POST",
            cache: false,
            data: {
                Email: $("#Email").val(),
                Password: $("#Password").val(),
                ConfirmPassword: $("#ConfirmPassword").val(),
                ZipCode: $("#ZipCode").val(),
                RememberMe: $("#RememberMe").is(':checked'),
                PreferredFormat: $('input[name="PreferredFormat"]').val(),
                FirstName: $("#FirstName").val(),
                LastName: $("#LastName").val(),
                BuyingAHome: $("#BuyingAHome").is(':checked'),
                SellingAHome: $("#SellingAHome").is(':checked'),
                ResearchHouseMarket: $("#ResearchHouseMarket").is(':checked')
            },
            success: function (json) {
                if (json != null) {
                    if (!json.IsValid) {//throw error
                        //$("#registeraccountcontainer").empty();
                        $("#registeraccountcontainer").html(json.Html);
                        return false;
                    } //if- IsValid
                    else {
                        if (s.pageName && !s.eVar19) s.eVar19 = s.pageName;
                        s.eVar42 = readCookie('OmnitureEvar42');
                        AddOmniture(json.omniture);
                        $(this).colorbox({
                            html: json.Html,
                            open: true,
                            onClosed: function () {
                                parent.location.href = "/Account/SavedListings";
                            }
                        });
                    } //else - IsValid
                } //json != null
            } //success
        });   //ajax func()
    });
}

function showVideo() {
     if($('.detailphoto')) $('.detailphoto').hide();
     if($('.property_contact')) $('.property_contact').hide();
     if($('.photocarousel')) $('.photocarousel').hide();

    $("#video_section").show();
 }

 function closevideo() {
     if($('.detailphoto')) $('.detailphoto').show();
     if($('.property_contact')) $('.property_contact').show();
     if($('.photocarousel')) $('.photocarousel').show();

     $("#video_section").hide();
 }

 function showPhotoTour() {
     if ($('.detailphoto')) $('.detailphoto').hide();
     if ($('.property_contact')) $('.property_contact').hide();
     if ($('.photocarousel')) $('.photocarousel').hide();

     $("#phototour_section").show();
     clearPhotoTour();
     var htmlStr = $("div.photoTourMainContent").html();
     $("div.s3").html(htmlStr);
     $(".s3").CarouSlide({

         animInfinity: true,
         showSlideNav: false,
         autoAnim: true,
         showPauseButton: true,
         showBackNext: true,
         animTime: 1200,
         slideTime: 5000
     });
 }
 function closePhotoTour() {
     if ($('.detailphoto')) $('.detailphoto').show();
     if ($('.property_contact')) $('.property_contact').show();
     if ($('.photocarousel')) $('.photocarousel').show();

     $("#phototour_section").hide();
     $(".slider-wrapper").remove();
     clearPhotoTour();
 }


 function clearPhotoTour() {
   $(".pause-button").remove();
   $(".slideshow-back-next").remove();}

function PostCaptcha(privatekey, display) {
    if (display == 'True') {
        var challenge = $("#recaptcha_challenge_field").val();
        var response = $("#recaptcha_response_field").val();
        if (response.length == 0) {
            $('#cmsg').text("Please enter the characters from the box");
            $('#cmsg').show();
        }
        else {
            $.ajax({
                type: "POST",
                cache: false,
                data:
                {
                    privatekey: privatekey,
                    challenge: $("#recaptcha_challenge_field").val(),
                    response: $("#recaptcha_response_field").val()
                },
                url: "/Agents/VerifyCaptcha",
                success: function (result) {
                    var s = result.toString();
                    if (s != 'true') {
                        $('#cmsg').text("Please retype the characters from the box");
                        $('#cmsg').show();
                        Recaptcha.reload();
                    }
                    else {
                        $('#cmsg').hide();
                        $('#emailagent').submit();
                    }
                }
            });
        } 
    }
    else {
        $('#emailagent').submit();
    }
}

function SubmitMoreInfo(privatekey, display) {
    $("#moreInfo").click(function () {
        var error = "";
        var formValue = true;
        if ($("#MIEmailAddress").val() == "") {
            $("#MIEmailAddress").addClass("input-validation-error");
            error += "Email is required."
            formValue = false;
        }
        else {
            reEmail = new RegExp(/(^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$)/);

            if (!reEmail.test($("#MIEmailAddress").val())) {
                $("#MIEmailAddress").addClass("input-validation-error");
                error += "Email is not in the correct format."
                formValue = false;
            }
            else
                $("#MIEmailAddress").removeClass("input-validation-error");
        }

        if ($("#MIFirstName").val() == "") {
            $("#MIFirstName").addClass("input-validation-error");
            error += "\nFirst name is required."
            formValue = false;
        }
        else
            $("#MIFirstName").removeClass("input-validation-error");

        if ($("#MILastName").val() == "") {
            $("#MILastName").addClass("input-validation-error");
            error += "\nLast name is required."
            formValue = false;
        }
        else
            $("#MILastName").removeClass("input-validation-error");

        MIPhoneVal = $("#MIPhone").val();
        if (MIPhoneVal != "" && MIPhoneVal != null) {
            rePhone = new RegExp(/([^a-zA-Z]$)/);
            if (!rePhone.test(MIPhoneVal)) {
                $("#MIPhone").addClass("input-validation-error");
                error += "\nPhone is not in the correct format."
                formValue = false;
            }
            else
                $("#MIPhone").removeClass("input-validation-error");
        }

        if (formValue) {

            if (display == 'True') {
                var challenge = $("#recaptcha_challenge_field").val();
                var response = $("#recaptcha_response_field").val();
                if (response.length == 0) {
                    $('#cmsg').text("Please enter the characters from the box");
                    $('#cmsg').show();
                }
                else {
                    $.ajax({
                        type: "POST",
                        cache: false,
                        data:
                            {
                                privatekey: privatekey,
                                challenge: $("#recaptcha_challenge_field").val(),
                                response: $("#recaptcha_response_field").val()
                            },
                        url: "/Agents/VerifyCaptcha/",
                        success: function (result) {
                            var s = result.toString();
                            if (s != 'true') {
                                $('#cmsg').text("Please retype the characters from the box");
                                $('#cmsg').show();
                                Recaptcha.reload();
                            }
                            else {
                                $('#cmsg').hide();
                                MoreInfoSubmit();
                            }
                        }
                    });
                }
            }
            else {
                MoreInfoSubmit();
            }         
        }
        else {
            alert(error);
        }
    });
}
function MoreInfoSubmit() {
    $.ajax({
        url: "/Agents/MoreInfo",
        type: "POST",
        cache: false,
        data:
                {
                    MIEmailAddress: $("#MIEmailAddress").val(),
                    MILastName: $("#MILastName").val(),
                    MIFirstName: $("#MIFirstName").val(),
                    MIagentID: $("#agentID").val(),
                    MIPropertyID: $("#propertyID").val(),
                    MIFeedID: $("#feedId").val(),
                    MIBookID: $("#bookID").val(),
                    MIPhone: $("#MIPhone").val()
                },
        success: function (result) {
            if (result != null) {
                $(this).colorbox({ html: result.Html, open: true });
                if (result.omniture != null) {
                    AddOmniture(result.omniture);
                }
            }
        }
    });
}
