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';
        }
    });
}

//page load function
$(document).ready(function() {
    //load custom radio buttons and select boxes
    $("select").selectbox();
    $('input[type=radio]').checkbox({
        empty: '/images/spacer.gif'
    });
    $('input[type=checkbox]').checkbox({
        empty: '/images/spacer.gif'
    });

}
);

function slideHide(slide, hide, tips) {
    slideHide(slide, hide, tips, null);

}

function slideHide(slide, hide, tips, focus) {
    $(hide).slideUp(300, function() {
        $(slide).slideDown(800, function() {

            if (focus != null)
                document.getElementById(focus).focus();


            return false;
        });
    });

}


function showModal() {
    $('div#modal-bg').addClass("modal-bg");
};


function closeModal() {
    closeModal(false);
};

function closeModal(forceClose) {
    if (!forceClose) {


        if (typeof Page_IsValid != "undefined") {
            if (!Page_IsValid)
                return;
        }
    }
    $('div#modal-bg').removeClass("modal-bg");

};

function renderControls() {
    $("select").selectbox();
    $('input[type=radio]').checkbox({
        empty: '/images/spacer.gif'
    });
    $('input[type=checkbox]').checkbox({
        empty: '/images/spacer.gif'
    });
}

function floorCents(amount) {
    return Math.floor(amount * 100) / 100;
}

function createJsonParams(dataItems) {
    var jsonValue = "";

    for (var index in dataItems) {
        if (jsonValue.length > 0)
            jsonValue += ",";

        var dataItemValue = dataItems[index];

        jsonValue += index + ":"
        jsonValue += jsonStringify(dataItemValue);
    }

    return "{" + jsonValue + "}";
}

function addProductToSession(tourDateID, buildingID, roomTypeID, peopleSharing) {
    var data = { "tourDateID": tourDateID, "buildingID": buildingID, "roomTypeID": roomTypeID, "peopleSharing": peopleSharing };

    $.ajax({
        url: "/User/Bookings/BuildingWebService.asmx/AddProductToSession",
        data: createJsonParams(data),
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            window.location = '/User/Bookings/SelectRooms.aspx';
        },
        error: function(data) {
            window.location = '/Error.aspx';
        }
    });
}

function callService(service, method, data, success) {
    $.ajax({
        url: "/User/Bookings/" + 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';
        }
    });
}

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 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);
}


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('Password is required.').minLength(6, 'Password must be a minimum of 6 characters.');
    $(".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-creditcard").assert(isValidCCNumber, 'Credit card number is invalid.');
    $(".val-ccv").minLength(3, 'CCV must be at least 3 digits.');

    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 showLoading(message) {

    if (message != "") {
        $("div#modal-loading span.message").text(message);
    }
    else {
        $("div#modal-loading span.message").text("Working...");
    }

    $("div#modal-loading").show();
}



function hideLoading() {
    $("div#modal-loading").hide();
}


function showModal(message) {

    if (message != "") {
        $("div#modal-loading span.message")
        $("div#modal-loading span.message").text(message);
    }
    else {
        $("div#modal-loading span.message").text("Warning");
    }

    $("div#modal-loading div.loading-fg").hide();
    $("div.modal-ok").show();
    $("div#modal-loading").show();
}

function hideModal() {
    $("div#modal-loading").hide();
    $("div.modal-ok").hide();
    $("div#modal-loading div.loading-fg").show();
}


function currencyFormatted(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}


