// JavaScript Document

//page load function
$(document).ready(function() {
    //load custom radio buttons and select boxs
    $("select").selectbox();
    $('input[type=radio]').checkbox({
        empty: '/images/spacer.gif'

    });
    $('input[type=checkbox]').checkbox({
        empty: '/images/spacer.gif'


    });

}
);

$("#rateSelect").change(function() {
    var opt

    opt = $("#rateSelect").val();
    switch (opt) {
        case 1:
            $(table.one).show();
            $(table.two).hide();
            $(table.three).hide();
            break;
        case 2:
            $(table.one).hide();
            $(table.two).show();
            $(table.three).hide();
            break;
        case 3:
            $(table.one).hide();
            $(table.two).show();
            $(table.three).hide();
            break;
        default:
            $(table.one).show();
            $(table.two).hide();
            $(table.three).hide();
            break;
    }
});

//function called when timer hits 0
function timeup() {
    window.location = "session_expired.html"
}
//function called after thickbox is loaded
function tbreload() {
    activateTips();

}

//function to hide and element takes :
// slide:string id or class of element to be shown
// hide:string id or class of element to be hidden
// tips: boolean value wether the new element has a tooltip box
function slideHide(slide, hide, tips) {
    slideHide(slide, hide, tips, null);

}

function slideHide(slide, hide, tips, focus) {
    $(hide).slideUp(300, function() {
        $("select").parents('.jquery-selectbox').unselectbox();
        $(slide).slideDown(800, function() {
            $("select").selectbox();
            if (tips) {
                activateTips()
                $("select").selectbox();
            }

            if (focus != null)
                document.getElementById(focus).focus();

            return false;
        });
    });

}

function listView() {
    $('#mapview').hide();
    $('#listview').show();
    $('a.listview').addClass("selected");
    $('a.mapview').removeClass("selected");
}
function mapView() {
    $('#mapview').show();
    $('#listview').hide();
    $('a.listview').removeClass("selected");
    $('a.mapview').addClass("selected");
}

//function activates the tooltip rate table
function activateTips() {
    $(".roomTable tr.avail td.share.tool span").each(function() {
        var htmlStr = $(this).html();
        $(this).simpletip(htmlStr, {
            hook: { target: 'rightMiddle', tooltip: 'topLeft' },
            offset: [-35, -25],
            border: { size: 0, radius: 0 },
            hideOn: { element: '.price', event: 'mouseout' },
            hideOthers: 'true',
            showEffect: 'none',
            hideEffect: 'none',
            delay: 0
        });
    });
    $(".roomTable tr.sold td.share.tool span").each(function() {
        var htmlStr = $(this).html();
        $(this).simpletip(htmlStr, {
            hook: { target: 'rightMiddle', tooltip: 'topLeft' },
            offset: [-35, -25],
            border: { size: 0, radius: 0 },
            hideOn: { element: '.price', event: 'mouseout' },
            hideOthers: 'true',
            showEffect: 'none',
            hideEffect: 'none',
            contentClass: 'sold',
            delay: 0
        });
    });
    $("select").selectbox();

    //activat the switch box to change the current table
    $("#rateSelect").change(function() {
        var opt
        opt = $("#rateSelect").val();
        switch (opt) {
            case "one":
                $("table.one").show();
                $("table.two").hide();
                $("table.three").hide();
                break;
            case "two":
                $("table.one").hide();
                $("table.two").show();
                $("table.three").hide();
                break;
            case "three":
                $("table.one").hide();
                $("table.two").hide();
                $("table.three").show();
                break;
        }
    });
}

function popup(mylink, windowname) {
    if (!window.focus) return true;
    var href;
    if (typeof (mylink) == 'string')
        href = mylink;
    else
        href = mylink.href;

    window.open(href, windowname.replace(' ', ''), 'width=700,height=500,resizable=yes,scrollbars=yes');
    return false;
}

function renderControls() {
    $("select").selectbox();
    $('input[type=radio]').checkbox({
        empty: '/images/spacer.gif'
    });
    $('input[type=checkbox]').checkbox({
        empty: '/images/spacer.gif'
    });
}

function createJsonParams(dataItems) {
    var jsonValue = "";

    for (var index in dataItems) {
        if (jsonValue.length > 0)
            jsonValue += ",";

        var dataItemValue = dataItems[index];
        jsonValue += index + ":"
        jsonValue += jsonStringify(dataItems[index]);
    }

    return "{" + jsonValue + "}";
}

function floorCents(amount) {
    return Math.floor(amount * 100) / 100;
}

function validate() {
    $.validity.setup({ outputMode: 'summary' });
    $.validity.start();
    $(".val-required").require('#{field} is required.');
    $(".val-email").match('email', '#{field} must be formatted correctly.');
    $(".val-password").require('#{field} is required.').minLength(6, 'Password must be a minimum of 6 characters.').equal('Passwords do not match.');
    $(".val-creditcard").assert(isValidCCNumber, 'Credit card number is invalid.');
    $(".val-ccv").minLength(3, 'CCV must be at least 3 digits.');
    $(".val-dropdown").greaterThan(0, '#{field} is required.');
    $(".val-date").match(/^((31(?! (Feb|FEB|Apr|APR|Jun|JUN|Sep|SEP|Nov|NOV)))|((30|29)(?! Feb|FEB))|(29(?= Feb|FEB (((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\d|2[0-8]) (Jan|JAN|Feb|FEB|Mar|MAR|May|MAY|Apr|APR|Jul|JUL|Jun|JUN|Aug|AUG|Oct|OCT|Sep|SEP|Nov|NOV|Dec|DEC) ((1[6-9]|[2-9]\d)\d{2})$/);
    $(".val-watermark").require('#{field} is required.').assert((!$(".val-watermark").hasClass('watermark')), '#{field} is required.');
    

    var result = $.validity.end();

    return result.valid;
}

    function isValidCCNumber(element) {

        var s = element.value;
        var i, n, c, r, t;
        // First, reverse the string and remove any non-numeric characters.
        r = "";
        for (i = 0; i < s.length; i++) {
            c = parseInt(s.charAt(i), 10);
            if (c >= 0 && c <= 9)
                r = c + r;
        }

        // Check for a bad string.
        if (r.length <= 2)
            return false;

        var firstNumber = parseInt(s.substring(0, 1));
        var secondNumber = parseInt(s.substring(1, 2));

        if (firstNumber != 4 && firstNumber != 5)
            return false;

        if (firstNumber == 5) {
            if (secondNumber < 1 || secondNumber > 5)
                return false;
        }

        // Now run through each single digit to create a new string. Even digits
        // are multiplied by two, odd digits are left alone.
        t = "";
        for (i = 0; i < r.length; i++) {
            c = parseInt(r.charAt(i), 10);
            if (i % 2 != 0)
                c *= 2;
            t = t + c;
        }

        // Finally, add up all the single digits in this string.
        n = 0;
        for (i = 0; i < t.length; i++) {
            c = parseInt(t.charAt(i), 10);
            n = n + c;
        }

        // If the resulting sum is an even multiple of ten (but not zero), the
        // card number is good.
        if (n != 0 && n % 10 == 0)
            return true;
        else
            return false;
    }

function clearDivHeights(div1, div2) {
    $(div1).height("auto");
    $(div2).height("auto");
}

function setDivHeights(div1, div1adjustment, div2, div2adjustment, minHeight) {

    clearDivHeights(div1, div2);

    var div1Height = $(div1).height();
    var div2Height = $(div2).height();
    var setHeight = 0;

    if (div1Height > div2Height) {
        setHeight = div1Height;
    }
    else if (div1Height < div2Height) {
        setHeight = div2Height;
    }

    if (setHeight < minHeight) {
        setHeight = minHeight;
    }

    if (setHeight > 0) {
        $(div1).height(setHeight + div1adjustment);
        $(div2).height(setHeight + div2adjustment);
    }
}

function callService(service, method, data, success) {
    $.ajax({
        url: "/" + service + "WebService.asmx/" + method,
        data: createJsonParams(data),
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            success(result.d);
        },
        error: function(data) {
            window.location = '/Error.aspx';
        }
    });
}

function callPageService(url, data, success) {
    $.ajax({
        url: url,
        data: createJsonParams(data),
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            success(result.d);
        },
        error: function (data) {
            
            window.location = '/Error.aspx';
        }
    });
}

function trim(s) {
    return rtrim(ltrim(s));
}

function ltrim(s) {
    var l = 0;
    while (l < s.length && s[l] == ' ')
    { l++; }
    return s.substring(l, s.length);
}

function rtrim(s) {
    var r = s.length - 1;
    while (r > 0 && s[r] == ' ')
    { r -= 1; }
    return s.substring(0, r + 1);
}

var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;


function jsonStringify(value) {
    gap = '';
    indent = '';
    
    return str('', { '': value });
}

function str(key, holder) {
    var i, 
            k,
            v,
            length,
            mind = gap,
            partial,
            value = holder[key];
    if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
        value = value.toJSON(key);
    }
    if (typeof rep === 'function') {
        value = rep.call(holder, key, value);
    }
    switch (typeof value) {
        case 'string':
            return quote(value);
        case 'number':
            return isFinite(value) ? String(value) : 'null';
        case 'boolean':
        case 'null':
            return String(value);
        case 'object':
            if (!value) {
                return 'null';
            }
            gap += indent;
            partial = [];
            if (Object.prototype.toString.apply(value) === '[object Array]') {
                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }
                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }
            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }
            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
    }
}

function quote(string) {
    escapable.lastIndex = 0;
    return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
}

function clearSession() {
    $.ajax({
        url: "/BuildingWebService.asmx/ClearSession",
        data: "",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function () {
            $(".session-container").animate({ "margin-top": "-=100px" }, "slow");
        },
        error: function (data) {
            window.location = '/Error.aspx';
        }
    });
}

