﻿var COOKIE_ADCODE = "adcodes";
var COOKIE_SUBKEY_ADCODE1 = "ac1";
var COOKIE_SUBKEY_ADCODE2 = "ac2";
var COOKIE_SUBKEY_ADCODE3 = "ac3";

function onDropdownChange(elem) {
    var selval = $(elem).val();
    window.location = selval;
}

function InsertExtraVisistat(extradid, extrapagename) {
    if (extradid != '') {
        var script = document.createElement('script');
        script.text = 'var DID=' + extradid + ';var MyPageName=\'' + extrapagename + '\';';
        script.type = 'text/javascript';
        document.getElementsByTagName('head')[0].appendChild(script);

        var script2 = document.createElement('script');
        script2.type = 'text/javascript';
        script2.src = 'http://sniff.visistat.com/sniff.js';
        document.getElementsByTagName('head')[0].appendChild(script2);
    }
}

function validate(showalert, vFields, pName) {
    var boolReturn = true;
    var strErrMessage = "";
    var boolRButtons = "false";


    // Test for invalid fields
    for (i = 0; i < vFields.length; i++) {
        objVal = document.getElementById(vFields[i]);

        if ((vFields[i]).match("email") != null) {
            if (!(/^\w+([\.\-]\w+)*@\w+([\.\-]\w+)*\.\w{2,4}$/.test(objVal.value))) {
                boolReturn = false;
                strErrMessage += pName[i] + ' ' + R.Common.IsInvalid + '\n';
            }
        }
        else if (objVal.type == "text" || objVal.type == "select-one" || objVal.type == "textarea") {
            if (objVal.value.length == 0) {
                boolReturn = false;
                strErrMessage += pName[i] + ' ' + R.Common.IsRequiredField + '\n';
            }
        }
        else if (objVal.type == "select-multiple") {
            if (objVal.selectedIndex <= 0) {
                boolReturn = false;
                strErrMessage += pName[i] + ' ' + R.Common.IsRequiredField + '\n';
            }
        }
        else if (objVal.type == "radio" || objVal.type == "checkbox") {

            rbuttons = document.getElementsByName(vFields[i]);
            for (ia = 0; ia < rbuttons.length; ia++) {
                if (rbuttons[ia].checked) {
                    ia = rbuttons.length;
                    boolRbuttons = true;
                }
                else
                { boolRbuttons = false; }
            }
            if (!boolRbuttons) {
                boolReturn = false;
                strErrMessage += pName[i] + ' ' + R.Common.IsRequiredField + '\n';
            }

        }


    }
    if (!boolReturn) {
        if (showalert) {
            alert(strErrMessage);
        }
        else {
            strErrMessage = strErrMessage.replace(/\n/g, ',');
            if (strErrMessage.charCodeAt(strErrMessage.length) == ',') {
                strErrMessage = strErrMessage.substring(0, strErrMessage.length - 1);
            }
            return strErrMessage;
        }
    }
    else {
        return ('success');
    }
}

function focusTextbox(id, value) {
    var textbox = document.getElementById(id);
    if (textbox.value == value) {
        textbox.value = "";
    }
    textbox.className = "textbox_selected";
}

function blurTextbox(id, value) {
    var textbox = document.getElementById(id);
    if (textbox.value == "" || textbox.value == value) {
        textbox.value = value;
        textbox.className = "textbox_unselected";
    }
    else {
        textbox.className = "textbox_unselected_value";
    }
}

function appendErrorMsgComma(curmsg, appendmsg) {
    if (curmsg != '') {
        curmsg = curmsg + ', ';
    }
    curmsg = curmsg + appendmsg;

    return curmsg;
}

function isNumeric(val) {
    var validChars = '0123456789.';

    for (var i = 0; i < val.length; i++) {
        if (validChars.indexOf(val.charAt(i)) == -1)
            return false;
    }

    return true;
}

function formatCurrency(strValue) {
    strValue = strValue.toString().replace(/\$|\,/g, '');
    dblValue = parseFloat(strValue);

    blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
    dblValue = Math.floor(dblValue * 100 + 0.50000000001);
    intCents = dblValue % 100;
    strCents = intCents.toString();
    dblValue = Math.floor(dblValue / 100).toString();
    if (intCents < 10)
        strCents = "0" + strCents;
    for (var i = 0; i < Math.floor((dblValue.length - (1 + i)) / 3); i++)
        dblValue = dblValue.substring(0, dblValue.length - (4 * i + 3)) + ',' +
		dblValue.substring(dblValue.length - (4 * i + 3));
    return (((blnSign) ? '' : '-') + '$' + dblValue + '.' + strCents);
}

function formatCurrencyDropCents(strValue) {
    strValue = strValue.toString().replace(/\$|\,/g, '');
    dblValue = parseFloat(strValue);

    blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
    dblValue = Math.floor(dblValue * 100 + 0.50000000001);
    dblValue = Math.floor(dblValue / 100).toString();

    for (var i = 0; i < Math.floor((dblValue.length - (1 + i)) / 3); i++)
        dblValue = dblValue.substring(0, dblValue.length - (4 * i + 3)) + ',' +
		dblValue.substring(dblValue.length - (4 * i + 3));
    return (((blnSign) ? '' : '-') + '$' + dblValue);
}

function searchProperties() {
    var query = "/Properties?";
    var params = [];

    formFieldToQueryParameter(params, '#txtSearchCity', 'city');
    formFieldToQueryParameter(params, '#ddlMinPrice', 'minp');
    formFieldToQueryParameter(params, '#ddlMaxPrice', 'maxp');
    formFieldToQueryParameter(params, '#ddlBeds', 'beds');
    formFieldToQueryParameter(params, '#ddlBaths', 'baths');
    formFieldToQueryParameter(params, '#hidSort', 'sort');
    formFieldToQueryParameter(params, '#hidDir', 'dir');

    window.location = "/Properties?" + params.join("&") + '#displaytypes';
}

function formFieldToQueryParameter(parameters, field, key) {

    var value = $(field).val();
    var s;

    if (value) {
        s = [key, '=', value].join("");
        parameters.push(s);
    }
}

function searchKeyPress(e) {
    if (e.which == 13) {
        searchProperties();
    }
}

function disableEnter(e) {
    if (e.which == 13) {
        e.preventDefault();
    }
}

function setupSearchForm() {
    $('#txtSearchCity').val($.query.get('city'));
    $('#ddlMinPrice').val($.query.get('minp'));
    $('#ddlMaxPrice').val($.query.get('maxp'));
    $('#ddlBeds').val($.query.get('beds'));
    $('#ddlBaths').val($.query.get('baths'));

    $('body').keydown(disableEnter);
    $('#txtSearchCity').keydown(searchKeyPress);
    $('#ddlMinPrice').keydown(searchKeyPress);
    $('#ddlMaxPrice').keydown(searchKeyPress);
    $('#ddlBeds').keydown(searchKeyPress);
    $('#ddlBaths').keydown(searchKeyPress);
}

String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
};

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + value +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function setCookieCollection(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

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 readCookieSubkey(name, subkey) {
    var val = unescape(readCookie(name));

    if (val) {
        var parts = val.split('&');
        for (i = 0; i < parts.length; i++) {
            var pair = parts[i].split('=');
            if (pair.length > 0) {
                if (pair[0] == subkey) {
                    return (pair.length > 1) ? pair[1] : '';
                }
            }
        }
    }

    return '';
}

function showErrorMessage(errormsg) {
    var msgHtml = '<div id="lightbox-messaging"><a href="javascript:;" onclick="closeMessage();" title="' + R.Common.Close + '" class="closeerror">' + R.Common.Close + '</a><p class="formerror"></p></div>';
    $('body').append(msgHtml);
    $('.formerror').html(errormsg);
    $('#lightbox-messaging').show().animate({ top: "0" }, { duration: 800, easing: 'easeOutExpo' }).animate({ top: "-50px" }, { duration: 300, easing: 'easeInExpo' });
    setTimeout('$("#lightbox-messaging a.closeerror").fadeTo(800, 1.0);', 1200);
}

function closeMessage() {
    try {
        $("#lightbox-messaging a.closeerror").fadeTo(800, 0.0);
        $('#lightbox-messaging').animate({ top: "-300px" }, { duration: 800, easing: 'easeInExpo', complete: hideErrorMessaging_TeamMember });
    }
    catch (e) { }
    finally {
        $('#lightbox-messaging').remove();
    }
}

function submitTotalAccessGlobal(name, email, phone, comments, buyersellerchoice, extracontent, callback, errorCallback) {
    submitTotalAccessGlobal(name, email, phone, comments, buyersellerchoice, extracontent, 0, false, callback, errorCallback)
}
function submitTotalAccessGlobal(name, email, phone, comments, buyersellerchoice, extracontent, ticks, useTicks, callback, errorCallback) {
    submitTotalAccessGlobalFinal(name, email, phone, comments, buyersellerchoice, extracontent, ticks, useTicks, -1, callback, errorCallback);
}

function submitTotalAccessGlobalFinal(name, email, phone, comments, buyersellerchoice, extracontent, ticks, useTicks, propertyId, callback, errorCallback) {
    var submission = '';
    submission += 'firstname=' + escape(name) + '&';
    submission += 'email=' + escape(email) + '&';
    submission += 'phone=' + escape(phone) + '&';
    submission += 'comments=' + escape(comments) + '&';
    submission += COOKIE_SUBKEY_ADCODE1 + '=' + escape(readCookieSubkey(COOKIE_ADCODE, COOKIE_SUBKEY_ADCODE1)) + '&';
    submission += COOKIE_SUBKEY_ADCODE2 + '=' + escape(readCookieSubkey(COOKIE_ADCODE, COOKIE_SUBKEY_ADCODE2)) + '&';
    submission += COOKIE_SUBKEY_ADCODE3 + '=' + escape(readCookieSubkey(COOKIE_ADCODE, COOKIE_SUBKEY_ADCODE3)) + '&';
    submission += extracontent;

    $.post(
        '/Total-Access/SubmitTotalAccessFinal',
        {
            buyersellerchoice: buyersellerchoice,
            formvalues: submission,
            useTicks: useTicks,
            ticks: ticks,
            propertyId: propertyId
        },
        function (d) {
            if (d.Success) {
                submitTotalAccessGlobalFinished(d, name, email, phone, callback, errorCallback);
            }
            else {
                if (errorCallback)
                    errorCallback(d);

                showErrorMessage(d.Message);
            }
        }
    );
}

function submitTotalAccessGlobalFinished(arg, name, email, phone, callback, errorCallback) {
    if (arg.Success) {
        setCookieCollection("TotalAccess", "Access=true&Name=" + escape(name) + "&Email=" + escape(email) + "&Phone=" + escape(phone), 30);
        callback(arg);
    }
    else {
        errorCallback(arg);
        showErrorMessage(arg.Message);
    }
}



/*-- extra --*/
$(document).ready(function () {

    /*-- zebra striping --*/
    $(".box:odd").addClass("stripe");
    $("#widget-blog li:even, #widgetbar li:even, #comments li:even, #comments .comment-date:even").addClass("stripe");

    $("#search-properties-button a").click(function () {
        $("#property-search").slideToggle(500);
    });

    /* -- slide out sub menus --*/
    var toggle = function (direction, display) {
        return function () {
            var self = this;
            var ul = $("ul", this);
            if (ul.css("display") == display && !self["block" + direction]) {
                self["block" + direction] = true;
                ul["slide" + direction]("1900", function () {
                    self["block" + direction] = false;
                });
            }
        };
    };
    $("#nav-full li").hover(toggle("Down", "none"), toggle("Up", "block"));
    $("#nav-full li ul").hide();
    $("#nav-full li a").removeAttr("title");

    try { addAdCodeTracking(); }
    catch (e) { alert(e); }
});

function addAdCodeTracking() {
    var ac1 = $.query.get(COOKIE_SUBKEY_ADCODE1);
    var ac2 = $.query.get(COOKIE_SUBKEY_ADCODE2);
    var ac3 = $.query.get(COOKIE_SUBKEY_ADCODE3);

    ac1 = String(ac1).trim();
    ac2 = String(ac2).trim();
    ac3 = String(ac3).trim();

    if (ac1 != '' && ac2 != '' && ac3 != '') {
        setCookieCollection(COOKIE_ADCODE,
            COOKIE_SUBKEY_ADCODE1 + '=' + escape(ac1) + '&' +
            COOKIE_SUBKEY_ADCODE2 + '=' + escape(ac2) + '&' +
            COOKIE_SUBKEY_ADCODE3 + '=' + escape(ac3));
    }
}

function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}
