﻿
/*** AJAX ***/

function postJSONtoMVC(url, data, callback_success, callback_error) {
    return $.ajax({
        url: url,
        type: "POST",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: callback_success,
        error: callback_error
    });
}

function processAjaxError(xhr) {
        clog(xhr);
    if (xhr.responseText) {
        //dumpProps(xhr);
        //alert(xhr.responseText);
    } else {
        //alert(xhr.get_message());
    }
    return;
}


/*** DEBUGGING ***/

// reveals all properties of an object through confirm method (ok/cancel)
function dumpProps(obj, parent) {
    // Go through all the properties of the passed-in object
    for (var i in obj) {
        // if a parent (2nd parameter) was passed in, then use that to
        // build the message. Message includes i (the object's property name)
        // then the object's property value on a new line
        if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
        // Display the message. If the user clicks "OK", then continue. If they
        // click "CANCEL" then quit this level of recursion
        if (!confirm(msg)) { return; }
        // If this property (i) is an object, then recursively process the object
        if (typeof obj[i] == "object") {
            if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
        }
    }
}

// Console debug
function clog(obj) {
    if (typeof (console) !== 'undefined' && console != null) {
        console.log(obj);
    }
}


function addButtonIcon(button) {
    var icoUrl = button.attr('data-icon');
    var spn = button.find('span');
    clog(spn);
    spn.css('background-image', 'url(' + icoUrl + ')');
}



/*** EXTEND JQUERY ***/

// Vertical Centering jQuery Extender
(function ($) {
    $.fn.vCenter = function (options) {
        var pos = {
            sTop: function () {
                return window.pageYOffset || document.documentElement && document.documentElement.scrollTop || document.body.scrollTop;
            },
            wHeight: function () {
                return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body.clientHeight;
            }
        };

        return this.each(function (index) {
            if (index == 0) {
                var $this = $(this);
                var elHeight = $this.height();
                var elTop = pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2);
                $this.animate({ top: elTop }, "slow");

                $this.css({
                    position: 'absolute',
                    marginTop: '0',
                    top: elTop
                });

            }
        });
    };

    $.fn.rc_htmlParsed = function (data) {
        this.html(data);
        $('button.js-icon').each(function () {
        addButtonIcon($(this));
        });
        return this;
    };

})(jQuery);

/**
* @author Alexander Farkas
* v. 1.02
*/
(function ($) {
    $.extend($.fx.step, {
        backgroundPosition: function (fx) {
            if (fx.state === 0 && typeof fx.end == 'string') {
                var start = $.curCSS(fx.elem, 'backgroundPosition');
                start = toArray(start);
                fx.start = [start[0], start[2]];
                var end = toArray(fx.end);
                fx.end = [end[0], end[2]];
                fx.unit = [end[1], end[3]];
            }
            var nowPosX = [];
            nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
            nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
            fx.elem.style.backgroundPosition = nowPosX[0] + ' ' + nowPosX[1];

            function toArray(strg) {
                strg = strg.replace(/left|top/g, '0px');
                strg = strg.replace(/right|bottom/g, '100%');
                strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g, "$1px$2");
                var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
                return [parseFloat(res[1], 10), res[2], parseFloat(res[3], 10), res[4]];
            }
        }
    });
})(jQuery);

/*** USEFUL METHODS ***/

function selectOptionByText(selectField, text) {
    selectField.find("option").each(function () {
        var thisText = $(this).text();
        if (thisText == text) {
            $(this).attr("selected", "selected");
        }
    });
}

function readablizeBytes(bytes) {
    var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
    var e = Math.floor(Math.log(bytes) / Math.log(1024));
    return (bytes / Math.pow(1024, Math.floor(e))).toFixed(2) + " " + s[e];
}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function guid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function addNumericOptionsToSelectList(identifier, floor, ceiling, clearExistingOptions) {
    var inputList = $(identifier);
    if (clearExistingOptions == true) inputList.html("");
    for (i = floor; i <= ceiling; i++) {
        inputList.append("<option value=\"" + i + "\">" + i + "</option>\n");
    }
}

function getNumericOptionsForSelectList(floor, ceiling, selectedValue) {
    var optionsList = "";
    if (typeof selectedValue == 'undefined') selectedValue = -1;
    var isSelected = "";
    for (i = floor; i <= ceiling; i++) {
        if (selectedValue == i) isSelected = " selected";
        optionsList += "<option value=\"" + i + "\"" + isSelected + ">" + i + "</option>\n";
        isSelected = "";
    }
    return optionsList;
}


String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function () {
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function () {
    return this.replace(/\s+$/, "");
}

Number.prototype.toDecimals = function (n) {
    n = (isNaN(n)) ? 2 : n;
    var nT = Math.pow(10, n);
    function pad(s) {
        s = s || '.';
        return (s.length > n) ?
                s :
                pad(s + '0');
    }
    return (isNaN(this)) ?
        this :
        (new String(
            Math.round(this * nT) / nT
        )).replace(/(\.\d*)?$/, pad);
}

Number.prototype.toCurrency = function () {
    num = this;
    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 + '.' + cents);
}


function searchStringArray(arrayToSearch, searchTerm, exact) {
    var notFound = true;
    for (i = 0; i < arrayToSearch.length; i++) {
        if (exact == true) {
            if (arrayToSearch[i] == searchTerm) {
                notFound = false;
                return true;
            }
        } else {
            if (arrayToSearch[i].indexOf(searchTerm) >= 0) {
                notFound = false;
                return true;
            }
        }
    }

    if (notFound == true) return false;
}

/*** VALIDATION ***/

// check if valid email address
function emailCheck(str) {
    var at = "@"
    var dot = "."
    var lat = str.indexOf(at)
    var lstr = str.length
    var ldot = str.indexOf(dot)

    if (str.indexOf(at) == -1) {
        return false
    }

    if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
        return false
    }

    if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
        return false
    }

    if (str.indexOf(at, (lat + 1)) != -1) {
        return false
    }

    if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) {
        return false
    }

    if (str.indexOf(dot, (lat + 2)) == -1) {
        return false
    }

    if (str.indexOf(" ") != -1) {
        return false
    }

    return true
}

// check if valid URL
function isUrl(s) {
    var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
    return regexp.test(s);
}

// check if valid date
function checkDate(minYear, maxYear) {
    var dtCh = "/";

    function isInteger(s) {
        var i;
        for (i = 0; i < s.length; i++) {
            // Check that current character is number.
            var c = s.charAt(i);
            if (((c < "0") || (c > "9"))) return false;
        }
        // All characters are numbers.
        return true;
    }

    function stripCharsInBag(s, bag) {
        var i;
        var returnString = "";
        // Search through string's characters one by one.
        // If character is not in bag, append to returnString.
        for (i = 0; i < s.length; i++) {
            var c = s.charAt(i);
            if (bag.indexOf(c) == -1) returnString += c;
        }
        return returnString;
    }

    function daysInFebruary(year) {
        // February has 29 days in any year evenly divisible by four,
        // EXCEPT for centurial years which are not also divisible by 400.
        return (((year % 4 == 0) && ((!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28);
    }
    function DaysArray(n) {
        for (var i = 1; i <= n; i++) {
            this[i] = 31
            if (i == 4 || i == 6 || i == 9 || i == 11) { this[i] = 30 }
            if (i == 2) { this[i] = 29 }
        }
        return this
    }

    this.isDate = function(dtStr) {
        var daysInMonth = DaysArray(12)
        var pos1 = dtStr.indexOf(dtCh)
        var pos2 = dtStr.indexOf(dtCh, pos1 + 1)
        var strMonth = dtStr.substring(0, pos1)
        var strDay = dtStr.substring(pos1 + 1, pos2)
        var strYear = dtStr.substring(pos2 + 1)
        strYr = strYear
        if (strDay.charAt(0) == "0" && strDay.length > 1) strDay = strDay.substring(1)
        if (strMonth.charAt(0) == "0" && strMonth.length > 1) strMonth = strMonth.substring(1)
        for (var i = 1; i <= 3; i++) {
            if (strYr.charAt(0) == "0" && strYr.length > 1) strYr = strYr.substring(1)
        }
        month = parseInt(strMonth)
        day = parseInt(strDay)
        year = parseInt(strYr)
        if (pos1 == -1 || pos2 == -1) {
            return "format";
        }
        if (strMonth.length < 1 || month < 1 || month > 12) {
            return "invalid month";
        }
        if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]) {
            return "invalid day";
        }
        if (strYear.length != 4 || year == 0 || year < minYear || year > maxYear) {
            return "invalid year";
        }
        if (dtStr.indexOf(dtCh, pos2 + 1) != -1 || isInteger(stripCharsInBag(dtStr, dtCh)) == false) {
            return "invalid date";
        }
        return true
    }
}

/* MODAL POP-UP */
var modalPopupTotalMargin = 30;
var modalPopupIframeUrl = '';
var modalPopupIframeTitle = '';
var modalPopupIframeHeight = '';

function loadModal_iframe(targetUrl, popupTitle, overlayClose, width, height) {
    modalPopupIframeUrl = targetUrl;
    modalPopupIframeTitle = popupTitle;
    modalPopupIframeHeight = height - modalPopupTotalMargin;

    loadModal_template('/content/ajax_templates/modal/modal_block.html',
        overlayClose,
        width,
        height,
        loadIframeInModalContent
    );
}

function loadIframeInModalContent() {
    var iframeHtml = '<iframe onload="rentcycle.interactive.unblockElement(\'#modContainer div.middle .inner\');" id="mod_iFrameContainer" src="' + modalPopupIframeUrl + '" style="height: ' + modalPopupIframeHeight + 'px;" width="100%" frameborder="0"></iframe>';

    // block ui
    rentcycle.interactive.blockElement("#modContainer div.middle .inner");

    // load iframe
    $('#modContainer div.middle .inner').prepend(iframeHtml);

    // set modal popup title
    $('#modContainer div.header h3').text(modalPopupIframeTitle);
}

function loadModal_ajax(targetUrl, modalTitle, overlayClose, width, height, callback) {
    loadModal_template('/content/ajax_templates/modal/modal_block.html',
        overlayClose,
        width,
        height,
        function () {
            // set modal popup title
            $("#modContainer div.header h3").text(modalTitle);

            // block placeholder
            rentcycle.interactive.blockElement("#modContainer div.middle .inner");

            $.ajax({
                url: targetUrl,
                cache: true,
                success: function (html) {
                    // load content
                    $('#modContainer div.middle .inner')
                        .css('max-height', height + 'px')
                        .css('overflow', 'auto')
                        .prepend(html);

                    // un-block placeholder
                    rentcycle.interactive.unblockElement("#modContainer div.middle .inner");

                    callback;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });
        }
    );
}

function loadModal_template(targetFile, overlayClose, width, height, callback) {
    $.modal('<div id="modContainer"></div>', {
        containerCss: {
            width: width,
            height: height,
            backgroundColor: 'transparent',
            border: 'none'
        },
        overlayClose: overlayClose,
        onOpen: function (dialog) {
            dialog.overlay.fadeIn('fast', function () {
                dialog.data.show();
                dialog.container.show();
            })
        },
        onClose: function (dialog) {
            dialog.data.fadeOut('fast', function () {
                dialog.container.fadeOut('fast');
                dialog.overlay.fadeOut('fast', function () {
                    $.modal.close();
                });
            });
        },
        onShow: function () {
            loadModalAjaxContent(targetFile, callback);
        }
    });
}

function loadModalAjaxContent(targetFile, callback) {
    $.ajax({
        url: targetFile,
        cache: true,
        success: function (html) {
            $("#modContainer").html(html);
            if ((callback != null) && (callback != 'undefined')) callback(html);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}

function randomString() {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 8;
    var randomstring = '';
    for (var i = 0; i < string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum, rnum + 1);
    }
    return randomstring;
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value + '; path=/';
}

function getCookie(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 deleteCookie(name) {
    createCookie(name, "", -1);
}
