function getnamevalue(param) {

    var ar = new Array();
    var t = param.split("&");
    for (jj = 0; jj < t.length; jj++) {
        var namevalue = t[jj].split("=");
        ar[namevalue[0]] = namevalue[1];
    }
    return ar;
}

function propercase(str) {
    str = str.replace('-', ' ');
    str = str.split(' ');
    var outstr = "";
    for (i = 0; i < str.length; i++) {
        outstr += str[i].charAt(0).toUpperCase() + str[i].substring(1) + " ";
    }
    return outstr;
}


function readrecentsearches(box) {
    var value = readCookie("sc");

    if (value && value.length > 0) {
        var tokens = value.split(",");
        var out = "";
        for (ii = 0; ii < tokens.length; ii++) {
            if (!tokens[ii]) {
                continue;
            }
            var param = tokens[ii].split(":");
            if (!param || param.length != 2) {
                continue;
            }
            param[1] = param[1].replace("/property/foreclosed-homes/", "");

            var location = param[1].split(/\/|\.html|\?/);
            
            var namevalue = getnamevalue(location[location.length - 1]);

            out += "<div>";
            if (param[0] == "ci") {
                out += "<a href='/property/foreclosed-homes/" + param[1] + "'>" + propercase(location[2]) + " Foreclosures</a>";
            }
            else if (param[0] == "co") {
                out += "<a href='/property/foreclosed-homes/" + param[1] + "'>" + propercase(location[1]) + " County " + " Foreclosures</a>";
            }
            else if (param[0] == "st") {
                out += "<a href='/property/foreclosed-homes/" + param[1] + "'>" + propercase(location[0]) + " Foreclosures</a>";
            }

            var display = "";
            if (namevalue["beds"]) {
                display += namevalue["beds"] + " Beds";
            }
            if (namevalue["beds"] && namevalue["baths"]) {
                display += " / ";
            }
            if (namevalue["baths"]) {
                display += namevalue["baths"] + " Baths";
            }
            if ((namevalue["beds"] || namevalue["baths"]) && namevalue["sqfeet"]) {
                display += ", ";
            }
            if (namevalue["sqfeet"]) {
                display += namevalue["sqfeet"] + " Sq.Ft";
            }
            if ((namevalue["beds"] || namevalue["baths"] || namevalue["sqfeet"]) && ((namevalue["pricestart"] && namevalue["pricestart"] != "1") || namevalue["priceend"])) {
                display += ", ";
            }
            if ((namevalue["pricestart"] && namevalue["pricestart"] != "1") || namevalue["priceend"]) {
                display += "Price: ";
            }
            if (namevalue["pricestart"] && namevalue["pricestart"] != "1") {
                display += formatCurrency(namevalue["pricestart"]);
            }
            if (namevalue["pricestart"] && namevalue["pricestart"] != "1" && namevalue["priceend"]) {
                display += " - ";
            }
            if (namevalue["pricestart"] && namevalue["priceend"]) {
                display += formatCurrency(namevalue["priceend"]);
            }
            if (display) {
                out += " <span style='font-size:100%'> with " + display + "</span>";
            }


            out += "</div>";
        }
        if (out.length > 15) {
            var googlead = "<iframe src='/property/googleadsense.html?page=detail&location=zillow-link&width=200' frameborder='0' scrolling='no' width='200' height='90' style='margin-top:10px'></iframe>";
            var finalout = '';
            if (box != "nobox") {
                finalout += '<div class="box">' +
                            '<div class="boxtop"></div>' +
                            '<div class="boxcenter">' +
                            '<div class="boxcontent"><div class="boxheader"><h2>Recent Searches</h2></div>';
            }
            else {
                finalout += '<div class="boxheader"><h2>Recent Searches</h2></div>';
            }

            finalout += '<div class="rightboxbody" style="padding-left:10px">'
                    + '<div style="padding-right:30px;text-align:right;font-weight:bold">'
                    + '<span style="padding-left:10px"><a href="" onclick="return clearrecentsearch()">Clear</a></span></div>'
                    + '<div style="padding-left:6px">' + out + '</div>';

            if (box != "nobox") {
                    finalout += googlead;
            }
            finalout += "</div>";
            if (box != "nobox") {
                finalout += '</div></div><div class="boxbottom"></div></div>';
            }

            $("#recentsearches").html(finalout);
            document.getElementById("recentsearches").style.display = 'block';
        }
    }
}
function clearrecentsearch() {
    document.cookie = "sc=;path=/";
    $("#recentsearches").html("");
    document.getElementById("recentsearches").style.display = 'block';
    return false;
}

function savestatecriteria(state, url) {
    url = url.substring(0, url.indexOf(".html"));
    var tokens = url.split("/");
    state = tokens[3];
    var county = tokens[4];
    var city = tokens[5];

    url = "/property/foreclosed-homes";
    if (state) {
        url += "/" + state;
    }
    if (county) {
        url += "/" + county;
    }
    if (city) {
        url += "/" + city;
    }
    url += ".html";

    var params = "";
    if (state && city && state.length > 2 && city.length > 0) {
        params += "ci:" + url;
    }
    else if (state && county && state.length > 2 && county.length > 0) {
        params += "co:" + url;
    }
    else if (state && state.length > 2) {
        params += "st:" + url;
    }
    if (params.length > 0) {
        saveCookie("sc", params, 5);
    }
    return true;
}

function savecriteria(form) {
    var state = form.state[form.state.selectedIndex].innerHTML;
    state = state.substring(state.indexOf(" - ") + 3).toLowerCase();
    state = state.replace(" ", "-");

    var county = form.county[form.county.selectedIndex].value;
    county = county.toLowerCase().replace(" ", "-");

    var city = form.city[form.city.selectedIndex].value;
    city = city.toLowerCase().replace(" ", "-");

    var url = "/property/foreclosed-homes";
    if (state) {
        url += "/" + state;
    }
    if (county) {
        url += "/" + county;
    }
    if (city) {
        url += "/" + city;
    }
    url += ".html";

    if (form.state.value.length == 2 && form.pricestart.value > 1 || form.priceend.value || form.sqfeet.value || form.beds.value || form.baths.value) {
        url += "?pricestart=" + form.pricestart.value;
        url += "&priceend=" + form.priceend.value;
        url += "&sqfeet=" + form.sqfeet.value;
        url += "&beds=" + form.beds.value;
        url += "&baths=" + form.baths.value;
    }

    var params = "";
    if (form.state.value.length == 2 && form.city.value.length > 0) {
        params += "ci:" + url;
    }
    else if (form.state.value.length == 2 && form.county.value.length > 0) {
        params += "co:" + url;
    }
    else if (form.state.value.length == 2) {
        params += "st:" + url;
    }
    if (params.length > 0) {
        saveCookie("sc", params, 5);
    }
    document.location.href = url;
    return false;
}

function loadforelosurelaw() {
    document.write("<a href='http://www.ForeclosureLaw.org' target=_new>ForeclosureLaw.org</a>");
}

function loadpage(url) {
    window.open(url, '_new');
    return false;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}


function saveRecent(id) {
    saveCookie("rec", id, 3);
}

function saveCookie(name, id, max) {
    var recent = readCookie(name);
    var cookies = "";
    if (recent && recent.length > 0) {
        cookies = id;
        var arr = recent.split(",");
        var count = 0;
        for (ii = 0; ii < arr.length; ii++) {
            if (arr[ii] != id) {
                cookies += "," + arr[ii];
                count++;
                if(count == max-1){
                    break;
                }
            }
        }
    }
    else {
        cookies = id;
    }
    document.cookie = name + "=" + cookies + ";path=/";
}


function tab(area, total, current) {
    if (!current) {
        current = readCookie(area);
    }

    if (!current) {
        current = 1;
    }
    for (ii = 1; ii <= total; ii++) {
        document.getElementById(area + "toc" + ii).className = "";
        document.getElementById(area + ii).style.display = "none";
    }
    document.getElementById(area + "toc" + current).className = "current";
    document.getElementById(area + current).style.display = "block";
    document.cookie = area + "=" + current;
    return false;
}


function loadrecentlyviewed(state, location) {
    $.ajax({
        url: "/property/recentlyviewed.html?ids=" + readCookie("rec") + "&state=" + state + "&loc=" + location,
        cache: false,
        success: function(html) {
            $("#recentlyviewed").html(html);
            document.getElementById("recentlyviewed").style.display = 'block';
        }
    });
    return false;
}

function saveproperty(id) {
    $.ajax({
        url: "/property/saveproperty.html?id=" + id,
        cache: false,
        success: function(html) {
            $("#savearea").html(html);
        }
    });
    return false;
}
function loadcomment(id) {
    $.ajax({
        url: "/property/listcomments.html?id=" + id,
        cache: false,
        success: function(html) {
            $("#commentarea").append(html);
        }
    });
}
function loadalsoviewed(id) {
    $.ajax({
        url: "/property/getalsonviewed.html?propertyid=" + id,
        cache: false,
        success: function(html) {
            $("#alsovistedarea").append(html);
        }
    });
}

function loadneighbourhood(zip, city, state, displayarea, display) {
    $.ajax({
        url: "/property/neighborhood.html?zipcode=" + zip + "&city=" + city + "&state=" + state + "&display=" + display,
        cache: true,
        success: function(html) {
            $("#" + displayarea).append(html);
        }
    });
}

function loadcounty(state, formname) {
    form = document.forms[formname];
    form.searchbtn.disabled = false;
    form.searchbtn2.disabled = false;
    form.county.disabled = true;
    form.city.disabled = true;

    $.ajax({
        url: "/property/citycountylist.html?type=county&state=" + state,
        cache: true,
        success: function(html) {
            citycountydisplay(html, form.county, "County");
        }
    });
}

function loadcity(state, county, formname) {
    form = document.forms[formname];
    form.city.disabled = true;

    $.ajax({
        url: "/property/citycountylist.html?type=city&state=" + state + "&county=" + escape(county),
        cache: true,
        success: function(html) {
            citycountydisplay(html, form.city, "City");
        }
    });
}
function citycountydisplay(html, field, label) {
    var trimmed = html.replace(/^\s+|\,\s+$/g, '');
    var tokens = trimmed.split(",");
    if (field) {
        field.options[0] = new Option("Select " + label);
        field.options[0].value = "";

        for (ii = 0; ii < tokens.length; ii++) {
            field.options[ii + 1] = new Option(tokens[ii]);
            field.options[ii + 1].value = tokens[ii];
        }
        field.disabled = false;
    }
}


function hide(id) {
    document.getElementById(id).style.display = 'none';
}
function show(id) {
    document.getElementById(id).style.display = 'block';
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
              num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num);
}

function claculateloan() {
    var amount = document.loancalculation.amount.value;
    amount = amount.replace(/\$|\,/g, '');

    var rate = document.loancalculation.interest.value;
    var downpayment = document.loancalculation.downpayment.value;

    var years = "30";
    if (amount == "" || rate == "" || years == "") {
        document.getElementById("loancalcresult1").innerHTML = "All the fields are required";
    }
    else if (!isNaN(amount) && !isNaN(rate) && !isNaN(years)) {
        amount = amount - (amount * (downpayment / 100) );
        var pmt = amount / ((1 - (1 / Math.pow((1 + (rate / 1200)), (years * 12)))) / (rate / 1200));
        document.getElementById("loancalcresult1").innerHTML = "Your monthly payment is " + formatCurrency(pmt);
    }
    else {
        document.getElementById("loancalcresult1").innerHTML = "Your input is invalid";
    }
    return false;
}
function logout() {
    document.redirectform.action = '/community/member/logout.html';
    var url = location.href;
    url = url.replace('addcomment.html', 'propertydetail.html')
    document.redirectform.url.value = url;
    document.redirectform.submit();
    return false;
}
function login() {
    var url = location.href;
    url = url.replace('addcomment.html', 'propertydetail.html')
    url = url.replace('s=f&', '');
    document.loginform.url.value = url;

    var email = document.loginform.MemberName.value;
    var error = 0;
    document.getElementById("loginerror").innerHTML = "";
    document.getElementById("emailerror").innerHTML = "";
    document.getElementById("passworderror").innerHTML = "";
    if (email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1) {
        document.getElementById("emailerror").innerHTML = "Invalid Email Address";
        error = 1;
    }
    if (document.loginform.MemberMatkhau.value.length < 4) {
        document.getElementById("passworderror").innerHTML = "Invalid Password";
        error = 1;
    }
    if (error == 0) {
        document.loginform.submit();
        return true;
    }
    return false;
}


function validatecompare() {
    form = document.compareform;

    var count = 0;
    for (ii = 0; ii < form.pid.length; ii++) {
        if (form.pid[ii].checked) {
            count++;
        }
    }

    if (count == 2) {
        for (ii = 0; ii < form.pid.length; ii++) {
            if (!form.pid[ii].checked) {
                form.pid[ii].disabled = true;
            }
        }
    }
    else {
        for (ii = 0; ii < form.pid.length; ii++) {
            form.pid[ii].disabled = false;

        }
    }
}

function comparehomes() {
    form = document.compareform;
    var id1 = "";
    var id2 = "";
    for (ii = 0; ii < form.pid.length; ii++) {
        if (form.pid[ii].checked) {
            if (id1 == "") {
                id1 = form.pid[ii].value;
            }
            else {
                id2 = form.pid[ii].value;
            }
        }
    }

    var qs = document.location.search.substring(1);
    var namevalue = qs.split("&");
    var newqs = "";
    for (i = 0; i < namevalue.length; i++) {
        if (!namevalue[i].match(/^id\d+/)) {
            newqs += "&" + namevalue[i]
        }
    }

    if (id1 && id2) {
        document.getElementById("compare-message").innerHTML = '';
        document.location.href = form.action + "?id1=" + id1 + "&id2=" + id2 + newqs;
    }
    else {
        document.getElementById("compare-message").innerHTML = 'To compare please select check boxes next to the property';
    }
    return false;
}
