﻿
$(document).ready(function() {
    if ($.browser.msie && parseInt($.browser.version) < 7)
        document.execCommand("BackgroundImageCache", false, true);
    setDatePicker($(".datepicker"));
});

function setDatePicker(sel) {
    if (sel.datepicker) {
        sel.datepicker(
        { dateFormat: 'dd/mm/yy',
            changeYear: true,
            showMonthAfterYear: true,
            yearRange: '-70:+10'
        });
    }
}


function clearTextField(field,val) {
    var currentValue = $(field).val();
    if (currentValue == val) {
        $(field).val("");
    }
}

function setTextField(field,val) {
    var currentValue = $(field).val();
    if (currentValue == "") {
        $(field).val(val);
    }
}

function addOption(sel, name, value) {
    if ($.browser.msie && parseInt($.browser.version) < 7)
        sel[0].options[sel[0].options.length] = new Option(name, value);
    else {
        sel.append($('<option></option>').val(value).html(name));
    }
}

function deleteOptions(sel) {
    if ($.browser.msie && parseInt($.browser.version) < 7) {
        for (var i = sel[0].options.length - 1; i >= 0; i--) {
            sel[0].remove(i);
        }
    } else
        sel.find('option').remove();
}

function addOptionSelected(sel, name, value, isSelected) {
    if ($.browser.msie && parseInt($.browser.version) < 7) {
        var opt = new Option(name, value);
        opt.selected = isSelected;
        sel[0].options[sel[0].options.length] = opt;
    } else {
        addOption(sel, name, value);
        if (isSelected)
            sel.val(value);
    }
}
/*
function displayLookup(results, sel, unselText) {
    sel.options.length = 0;
    for (i = 0; i < results.length; i++) {
        if (results[i] == "")
            addOption(sel, unselText, "");
        else
            addOption(sel, results[i], results[i]);
    }
}
*/
function displayKeyValue(results, sel, unselText) {
    //sel.length = 0;
    for (i = 0; i < results.length; i++) {
        if (results[i] == "")
            addOption(sel, unselText, "");
        else
            addOption(sel, results[i].value, results[i].key);
    }
}

function showHide(theid) {
    if (document.getElementById) {
        var switch_id = document.getElementById(theid);
        switch_id.style.display = (switch_id.style.display == "none") ? "block" : "none";
    }
}

function show(theid) {
    //theid.style.display = "block";
    theid.css("display", "block");
}

function hide(theid) {
    //theid.style.display = "none";
    theid.css("display", "none");
}

function onFailed(a, b, c) {
    var divWait = $('img[src*=/images/loading3.gif]').parent();
    if (divWait.length > 0)
        divWait.hide();
        
    var dov = $(".overlay")
    if (dov.length > 0)
        dov.hide();
        
    if (a._statusCode == 401) {
        document.location = document.URL;
    }
    else {
        showErrorMessage(a)
    }
}

function showErrorMessage(a) {
    if (a._exceptionType == "Autolease.Global.Exceptions.DBTimeoutException" ||
            a._exceptionType == "System.ServiceModel.CommunicationException" ||
            a._exceptionType == "System.Net.WebException" ||
            a._exceptionType == "System.TimeoutException")
        alert("Our servers are currently very busy. Please try again later.");
    else if (a._exceptionType == "Autolease.Global.Exceptions.InvalidSessionException")
        alert("Please log out. Your session has expired.");
    else if (a._exceptionType == "Autolease.Global.Exceptions.ValidationException") {
        alert(a._message);
    }
    else if (a._exceptionType == "Autolease.Global.Exceptions.ServiceException") {
        if (confirm("Sorry, there was a problem. Would you like to report it to the service desk?"))
            document.location = "ErrorPage.aspx";
    }
    else {
        alert("Sorry, there was a problem with processing your input. Please contact the service desk");
    }

}

StringBuffer = function() {
    var that = this;
    this.buffer = [];
    this.length = function length() {
        return that.buffer.length;
    };
    this.toString = function toString() {
        return that.buffer.join("");
    };
    this.append = function append(string) {
        that.buffer[that.buffer.length] = string;
        return that;
    };
}

function showWaiting(div) {
    show(div);
    showSpinning(div);
    var existingHTML = div.html();
    div.html( existingHTML + "<br />Please wait..." );
}

function showSpinning(div) {
    show(div);
    div.html( "<img src='/images/loading3.gif'>" );
}

/*
function KeyEvent(event) {
    // press key "Enter"
    if (event.keyCode == 13 || event.charCode == 13) {
        event.cancelBubble = true;
        if (event.stopPropagation)
            event.stopPropagation();
        if (event.preventDefault)
            event.preventDefault();

        doKeyPress(event);

        return false;
    }
    else
        return true;
}

function doKeyPress(event) {
    // please leave empty!!
}

function doPageLoad() {
    // please leave empty!!
}

function moveToMouse(el, e) {
    e = e || window.event;

    var x, y;
    if (e.pageX || e.pageY) {
        x = e.pageX;
        y = e.pageY;
    }
    else {
        var de = document.documentElement;
        var b = document.body;
        x = e.clientX - (de.clientLeft || 0);
        y = e.clientY - (de.clientTop || 0);
    }

    el.style.left = (x - 150) + "px";
    el.style.top = (y + 15) + "px";
}
*/
function isValidEmail(address) {
    var myRegExp = /([a-zA-Z]|[0-9])@(?=[a-zA-Z])/;
    var matchPos = address.search(myRegExp);
    if (matchPos == -1)
        return false;
    else
        return true;
}

function convertToValidDate(dateStr) {
    var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
    if (re.test(dateStr)) {
        var dArr = dateStr.split("/");

        var d = new Date(dArr[2], parseInt(dArr[1], 10) - 1, dArr[0]);
        if (d.getDate() == dArr[0] && d.getMonth() + 1 == dArr[1] && d.getFullYear() == dArr[2]) {
            {
                d.setUTCDate(dArr[0]);
                d.setUTCMonth(parseInt(dArr[1], 10) - 1);
                d.setUTCFullYear(dArr[2]);
                d.setUTCHours(0);
                d.setUTCMinutes(0);
                d.setUTCSeconds(0);
                return d;
            }
        }
    }
    else
        return null;
}

function convertNullDate(dateStr) {
    var dt;
    dt = dateStr == null ? convertToValidDate("01/01/1900") : dateStr;
    return dt;
}

function isDate(dateStr) {
    return convertToValidDate(dateStr) != null;
}

var DateFormat = {
    getMonthName: function(i) {
        var m = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        var mnthName = '';
        if (isNaN(i))
            return m[0];
        else
            return m[i];
    }
}



function clearForm() {
    $("input").val("");
    $("textarea").val("");
    $("input:checkbox").each(function() {
        this.checked = false;
    });
    $("select").each(function() {
        this.selectedIndex = 0;
    });
}

/* functions for underlining of links on div panels */

function underlineAllOurOffers() {
    $('#allOurOffers a').css({ 'text-decoration': 'underline' });
}
function clearAllOurOffers() {
    $('#allOurOffers a').css({ 'text-decoration': 'none' });
}

function underlineHomepageLozengeGreen() {
    $('#greenBlock a').css({ 'text-decoration': 'underline' });
}
function clearHomepageLozengeGreen() {
    $('#greenBlock a').css({ 'text-decoration': 'none' });
}

function underlineContactAndLocations() {
    $('#ContactsAndLocationsLink').css({ 'text-decoration': 'underline' });
}
function clearContactAndLocations() {
    $('#ContactsAndLocationsLink').css({ 'text-decoration': 'none' });
}

function underlineCustomerLogin() {
    $('#customerLoginLink a').css({ 'text-decoration': 'underline' });
}
function clearCustomerLogin() {
    $('#customerLoginLink a').css({ 'text-decoration': 'none' });
}

function underlineWhatCar() {
    $('#roadLibrary a').css({ 'text-decoration': 'underline' });
}
function clearWhatCar() {
    $('#roadLibrary a').css({ 'text-decoration': 'none' });
}

(function($) {
    $.toJSON = function(o) {
        var i, k;
        var type = typeof (o); if (o === null) { return "null"; }
        if (type === "undefined") { return undefined; }
        if (type === "number" || type === "boolean") { return o + ''; }
        if (type === "string") { return $.quoteString(o); }
        if (type === 'object') {
            if (o.constructor === Date || o instanceof Date) {
                return '"\\\/Date(' + o.getTime() + ')\\\/"';
            }
            if (o.constructor === Array) {
                var ret = [];
                for (i = 0; i < o.length; i++) {
                    ret.push($.toJSON(o[i]) || "null");
                }
                return "[" + ret.join(",") + "]";
            }
            var pairs = []; for (k in o) {
                var name; type = typeof k;
                if (type === "number") { name = '"' + k + '"'; }
                else {
                    if (type === "string") { name = $.quoteString(k); }
                    else { continue; }
                }
                if (typeof o[k] === "function") { continue; }
                var val = $.toJSON(o[k]); pairs.push(name + ":" + val);
            }
            return "{" + pairs.join(", ") + "}";
        }
    }; $.evalJSON = function(src) {
        if (typeof (JSON) === 'object' && JSON.parse) { return JSON.parse(src); }
        return eval("(" + src + ")");
    }; $.secureEvalJSON = function(src) {
        if (typeof (JSON) === 'object' && JSON.parse) { return JSON.parse(src); }
        var filtered = src; filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@'); filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'); filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
        if (/^[\],:{}\s]*$/.test(filtered)) { return eval("(" + src + ")"); } else { throw new SyntaxError("Error parsing JSON, source is not valid."); }
    }; $.quoteString = function(string) {
        if (string.match(_escapeable)) {
            return '"' + string.replace(_escapeable, function(a)
            { var c = _meta[a]; if (typeof c === 'string') { return c; } c = a.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"';
        }
        return '"' + string + '"';
    }; var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g; var _meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' };
})(jQuery);

String.prototype.format12 = function() {
    var formatted = this, i;
    for (i = 0; i < arguments.length; i++) {
        formatted = formatted.replace("{" + i + "}", arguments[i]);
    }
    return formatted;
};


$.toDate = function(data) {
    if (data) {
        $.each(data, function(id, value) {
            if (typeof (value) === 'string' && value.substring(0, 6) === '/Date(') {
                data[id] = new Date(parseInt(value.substr(6), 10));
            } else if (typeof (value) === 'object') $.toDate(value);
        });
    }
}

function callService(path, func, d, onSuccess, onFailure, context) {
    $.ajax({
        type: "POST",
        url: "/services/" + path + ".svc/" + func,
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: $.toJSON(d),
        dataType: "json",
        success: function(r) {
            if (onSuccess) {
                $.toDate(r);
                onSuccess(r, context);
            }
        },
        error: function(r) {
            if (onFailure) {
                onFailure(
                    {
                        "_statusCode": r.status,
                        "_exceptionType": $.parseJSON(r.responseText) ? $.parseJSON(r.responseText).ExceptionType : "System.Net.WebException",
                        "_message": $.parseJSON(r.responseText) ? $.parseJSON(r.responseText).Message : ""
                    },
                    context);
            }
        }
    });
}
