﻿// NewRiver namespace
NEWRIVER = {};

//////////////////////////////////////////////////////
// Place all common functions for the app within here
//////////////////////////////////////////////////////

NEWRIVER.common = {

    lockBackgroundWithZIndex: function(flag, topMost) {
        if (flag) {
            var topZindex = $.topZIndex();
            if (topMost) {
                $("#lockBackground").css("z-index", topZindex + 1);
            }
            else {
                $("#lockBackground").css("z-index", 99);
            }
            $("#lockBackground").css("background-color", "#000000");
            $("#lockBackground").css("opacity", "0.0");
            $("#lockBackground").css("position", "absolute");
            $("#lockBackground").css("top", "0px");
            $("#lockBackground").css("left", "0px");
            $("#lockBackground").css("height", "100%");
            $("#lockBackground").css("width", "100%");
            $("#lockBackground").stop().animate({ opacity: 0.5 }, 600);
        }
        else {
            $("#lockBackground").css("opacity", "0");
            $("#lockBackground").css("height", "0px");
            $("#lockBackground").css("width", "0px");
        }
    },

    lockBackground: function(flag) {
        NEWRIVER.common.lockBackgroundWithZIndex(flag, false);
    },

    validateCreditCard: function(s) {
        // remove non-numerics
        var v = "0123456789";
        var w = "";
        for (i = 0; i < s.length; i++) {
            x = s.charAt(i);
            if (v.indexOf(x, 0) != -1)
                w += x;
        }
        // validate number
        j = w.length / 2;
        if (j < 6.5 || j > 8 || j == 7) return false;
        k = Math.floor(j);
        m = Math.ceil(j) - k;
        c = 0;
        for (i = 0; i < k; i++) {
            a = w.charAt(i * 2 + m) * 2;
            c += a > 9 ? Math.floor(a / 10 + a % 10) : a;
        }
        for (i = 0; i < k + m; i++) c += w.charAt(i * 2 + 1 - m) * 1;
        return (c % 10 == 0);
    },

    hasDigits: function(str) {
        var digits = false;
        for (i = 0; i < str.length; i++) {
            var ch = str.charAt(i);
            if ("0123456789".indexOf(ch) != -1) {
                digits = true;
            }
        }

        return digits;
    },

    hasCaps: function(str) {
        var hasCap = false;
        for (i = 0; i < str.length; i++) {
            var ch = str.charAt(i);
            if (ch == ch.toUpperCase() && "0123456789".indexOf(ch) == -1) {
                hasCap = true;
            }
        }

        return hasCap;
    },

    validPassword: function(pwd) {
        var errorMsg = null;

        if (!NEWRIVER.common.hasDigits(pwd))
            errorMsg = "Passwords must contain at least one number.";

        if (!NEWRIVER.common.hasCaps(pwd))
            errorMsg = "Passwords must contain at least one uppercase letter.";

        if (pwd.length < 8) {
            errorMsg = "Password must be a minimum of 8 characters in length.";
        }

        return errorMsg;
    },

    verifyPageHeight: function(section) {
        NEWRIVER.common.recalcSliderHeight();
        //NEWRIVER.common.recalcWorkflowHeight();
        //NEWRIVER.common.recalcPageHeight();
    },

    verifyPageLayout: function(section) {
        if (section == undefined) { section = ""; }

        $("input").customInput(section);
        $("input").customInput(".page:not(.cloned) ");

        NEWRIVER.common.formatInputMasks(section);
        NEWRIVER.common.verifyPageHeight();
    },

    formatInputMasks: function(section) {
        if (section == undefined) { section = ""; }

        $.preferCulture('en-US');
        $(section + " input.moneyInput").each(function() {
            $(this).unbind();
            $(this).maskMoney();
        });
        $(section + " input.phoneInput").each(function() {
            $(this).unbind();
            $(this).mask("(999) 999-9999");
        });
        $(section + " input.zipCodeInput").each(function() {
            $(this).unbind();
            $(this).mask("99999?-9999");
        });
        $(section + " input.einInput").each(function() {
            $(this).unbind();
            $(this).mask("99-9999999");
        });
        $(section + " input.ssnCodeInput").each(function() {
            $(this).unbind();
            $(this).mask("999-99-9999");
        });
        $(section + " input.numericInput").each(function() {
            $(this).unbind();
            $(this).numeric();
        });
    },

    formatCurrency: function(num) {
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num))
            num = "0";

        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);
    },

    // All code for the formatDate is taken from http://github.com/phstc/jquery-dateFormat
    formatDate: function(value, format) {
        var parseMonth = function(value) {
            switch (value) {
                case "Jan":
                    return "01";
                case "Feb":
                    return "02";
                case "Mar":
                    return "03";
                case "Apr":
                    return "04";
                case "May":
                    return "05";
                case "Jun":
                    return "06";
                case "Jul":
                    return "07";
                case "Aug":
                    return "08";
                case "Sep":
                    return "09";
                case "Oct":
                    return "10";
                case "Nov":
                    return "11";
                case "Dec":
                    return "12";
                default:
                    return value;
            }
        };

        var parseTime = function(value) {
            var retValue = value;
            if (retValue.indexOf(".") !== -1) {
                retValue = retValue.substring(0, retValue.indexOf("."));
            }

            var values3 = retValue.split(":");

            if (values3.length === 3) {
                hour = values3[0];
                minute = values3[1];
                second = values3[2];

                return {
                    time: retValue,
                    hour: hour,
                    minute: minute,
                    second: second
                };
            } else {
                return {
                    time: "",
                    hour: "",
                    minute: "",
                    second: ""
                };
            }
        };

        try {
            var year = null;
            var month = null;
            var dayOfMonth = null;
            var time = null; //json, time, hour, minute, second
            if (typeof value.getFullYear === "function") {
                year = value.getFullYear();
                month = value.getMonth() + 1;
                dayOfMonth = value.getDate();
                time = parseTime(value.toTimeString());
            } else {
                var values = value.split(" ");

                switch (values.length) {
                    case 6: //Wed Jan 13 10:43:41 CET 2010
                        year = values[5];
                        month = parseMonth(values[1]);
                        dayOfMonth = values[2];
                        time = parseTime(values[3]);
                        break;
                    case 2: //2009-12-18 10:54:50.546
                        var values2 = values[0].split("-");
                        year = values2[0];
                        month = values2[1];
                        dayOfMonth = values2[2];
                        time = parseTime(values[1]);
                        break;
                    default:
                        return value;
                }
            }
            var pattern = "";
            var retValue = "";
            //Issue 1 - variable scope issue in format.date 
            //Thanks jakemonO
            for (var i = 0; i < format.length; i++) {
                var currentPattern = format.charAt(i);
                pattern += currentPattern;
                switch (pattern) {
                    case "dd":
                        retValue += dayOfMonth;
                        pattern = "";
                        break;
                    case "MM":
                        retValue += month;
                        pattern = "";
                        break;
                    case "yyyy":
                        retValue += year;
                        pattern = "";
                        break;
                    case "HH":
                        retValue += time.hour;
                        pattern = "";
                        break;
                    case "hh":
                        retValue += (time.hour === 0 ? 12 : time.hour < 13 ? time.hour : time.hour - 12);
                        pattern = "";
                        break;
                    case "mm":
                        retValue += time.minute;
                        pattern = "";
                        break;
                    case "ss":
                        retValue += time.second;
                        pattern = "";
                        break;
                    case "a":
                        retValue += time.hour > 12 ? "PM" : "AM";
                        pattern = "";
                        break;
                    case " ":
                        retValue += currentPattern;
                        pattern = "";
                        break;
                    case "/":
                        retValue += currentPattern;
                        pattern = "";
                        break;
                    case ":":
                        retValue += currentPattern;
                        pattern = "";
                        break;
                    default:
                        if (pattern.length === 2 && pattern.indexOf("y") !== 0) {
                            retValue += pattern.substring(0, 1);
                            pattern = pattern.substring(1, 2);
                        } else if ((pattern.length === 3 && pattern.indexOf("yyy") === -1)) {
                            pattern = "";
                        }
                }
            }
            return retValue;
        } catch (e) {
            console.log(e);
            return value;
        }
    },

    convertToDecimal: function(str) {
        var num = 0.0;
        var str = str.toString().replace(/\$|\,/g, '');
        if (isNaN(str))
            return "NaN";

        return parseInt(str);
    },

    hideRightColumn: function() {
        $("#rightContentContainer").hide();
        $("#centerContentContainer").width("780px");
    },

    hideBothColumns: function() {
        $("#rightContentContainer").hide();
        $("#vertMenuContainer").hide();
        $("#centerContentContainer").width("925px");
        $("#centerContentContainer").css("margin-left", "30px");
    },

    hideLeftColumn: function() {
        $("#vertMenuContainer").hide();
        $("#centerContentContainer").width("615px");
        $("#centerContentContainer").css("margin-left", "30px");
    },

    displayPageAsModule: function(width) {
        $("#headerContainer").hide();
        $("#horizMenuContainer").hide();
        $("#vertMenuContainer").hide();
        $("#rightContentContainer").hide();
        $("#footerContainer").hide();
        $("#footerBorder").hide();

        $("#mainContainer").css("padding", "0");
        $("#centerContentContainer").css("padding", "0");
        $("#centerContentContainer").width(width);
    },

    embedModule: function(divId, page, title, width, height, closeFunction) {
        var hostDiv = "#" + divId;

        $(hostDiv).css("overflow", "hidden");
        $(hostDiv).dialog({
            autoOpen: false,
            title: title,
            resizable: false,
            width: width,
            height: height,
            draggable: false,
            close: function(event, ui) {
                closeFunction();
            }
        });

        $(hostDiv).dialog("open");
        $(hostDiv).html('<iframe id="embedFrame" src="' + page + '" frameborder="0" scrolling="no"></iframe>');
    },

    showDirectSellGutter_close: function() {
        $("#rightContentContainer").show();
    },

    showDirectSellGutter: function(page, title) {
        var left = $("#rightContentContainer").position().left + 13;
        $("#rightContentContainer").hide();

        NEWRIVER.common.embedModule("sellDialog", page, title, 295, 550, NEWRIVER.common.showDirectSellGutter_close);

        $(".ui-dialog").css("top", "120px");
        $(".ui-dialog").css("left", left);

        var h = $("#centerContentContainer").height() - 65;
        $("#sellDialog").height(h);
        $("#embedFrame").attr("height", h);
    },

    closeDirectSellGutter: function(redirectUrl) {
        $("#sellDialog").dialog("close");
        if (redirectUrl != null && redirectUrl.length > 0)
            window.parent.location = redirectUrl;
    },

    recalcPageHeight: function() {
        var h1 = $("#centerContentContainer").height();
        var h2 = $("#vertMenuContainer").height();
        var h3 = $("#rightContentContainer").height();

        var h = 0;
        if (h1 > h) h = h1;
        if (h2 > h) h = h2;
        if (h3 > h) h = h3;

        $("#vertMenuContainer").height(h);
        $("#centerContentContainer").height(h);
        $("#rightContentContainer").height(h);
    },

    recalcSliderHeight: function() {
        var p1 = $(".panel1").height() + 150;
        var p2 = $(".panel2").height() + 150;
        var d1 = $("#detailTabs").height() + 110;

        var h = p1;
        if (p2 > h) h = p2;
        if (d1 > h) h = d1;

        var lh = $("#vertMenuContainer").height();
        var rh = $("#rightContentContainer").height();
        var ch = $("#centerContentContainer").height();

        if (lh > h) h = lh;
        if (rh > h) h = rh;
        if (ch > h) h = ch;

        //if (h1 < h2) h = h1;

        $("#sliderPanel").height(h);
        $("#vertMenuContainer").height(h);
        $("#centerContentContainer").height(h);
        $("#rightContentContainer").height(h);
    },

    recalcWorkflowHeight: function() {
        var h1 = $("#centerContentContainer form").height() + 80;
        var h2 = $("#vertMenuContainer").height();
        var h3 = $("#rightContentContainer").height();

        var h = 0;
        if (h1 > h) h = h1;
        if (h2 > h) h = h2;
        if (h3 > h) h = h3;

        if (h1 < h2)
            h = h1;

        $("#vertMenuContainer").height(h);
        $("#centerContentContainer").height(h);
        $("#rightContentContainer").height(h);
    },

    selectChevron: function(chevronContainer) {
        var chevronId = "#" + chevronContainer;
        var selected = $(chevronId).attr("selection");
        if (selected != null && selected.length > 0) {
            var selectedStep = parseInt(selected);
            var numSteps = $(chevronId + " .linkContainerUnSelected").size();

            if (selectedStep <= 1) {
                $(chevronId + " .leftOpenerUnSelected").addClass("leftOpenerSelected").removeClass("leftOpenerUnSelected");
                $(chevronId + " .sepContainerUnSelected").eq(0).addClass("sepContainerSelected").removeClass("sepContainerUnSelected");
                $(chevronId + " .linkContainerUnSelected").eq(0).addClass("linkContainerSelected").removeClass("linkContainerUnSelected");
            }
            else if (selectedStep >= numSteps) {
                $(chevronId + " .rightClosedUnSelected").addClass("rightClosedSelected").removeClass("rightClosedUnSelected");
                $(chevronId + " .sepContainerUnSelected").eq(selectedStep - 2).addClass("sepContainerSelectedNext").removeClass("sepContainerUnSelected");
                $(chevronId + " .linkContainerUnSelected").eq(selectedStep - 1).addClass("linkContainerSelected").removeClass("linkContainerUnSelected");
            }
            else {
                $(chevronId + " .sepContainerUnSelected").eq(selectedStep - 2).addClass("sepContainerSelectedNext").removeClass("sepContainerUnSelected");
                $(chevronId + " .sepContainerUnSelected").eq(selectedStep - 2).addClass("sepContainerSelected").removeClass("sepContainerUnSelected");
                $(chevronId + " .linkContainerUnSelected").eq(selectedStep - 1).addClass("linkContainerSelected").removeClass("linkContainerUnSelected");
            }
        }
    },

    createToolTip: function() {
        $(".withTooltip[title]").tooltip({
            position: "center right",
            offset: [0, 10],
            effect: "fade"
        });
    },

    createOverlay: function() {
        $(".overlayTrigger[rel]").overlay({
            exMask: {
                color: "#000",
                loadSpeed: 200,
                opacity: 0.6
            },
            closeOnClick: false
        });
    },

    createQtip: function(id, strText, strTitle, iWidth, position) {
        var txtTooltip = "bottomMiddle";
        var txtTarget = "topMiddle";

        if (position == "bottom") {
            txtTooltip = "topMiddle";
            txtTarget = "bottomMiddle";
        }
        else if (position == "left") {
            txtTooltip = "rightMiddle";
            txtTarget = "leftMiddle";
        }
        else if (position == "right") {
            txtTooltip = "leftMiddle";
            txtTarget = "rightMiddle";
        }
        else if (position == "top") {
            txtTooltip = "bottomMiddle";
            txtTarget = "topMiddle";
        }

        $('#' + id).qtip({
            content: { text: strText, title: { text: strTitle} },
            position: {
                type: 'fixed',
                corner: {
                    tooltip: txtTooltip,
                    target: txtTarget
                }
            },
            style: {
                border: { color: '#336699', width: 2 },
                width: { min: iWidth, max: iWidth },
                padding: 10,
                textAlign: 'left',
                background: '#FFFFFF',
                'font-size': 12,
                'font-family': 'Arial',
                title: { 'color': '#336699', 'font-size': 12, 'font-family': 'Arial' },
                tip: true
            }
        });
    },


    configureEvents: function(submitEvents) {
        $(".workflow-event").each(function() {
            var event = $(this).find(".workflow-event-type").html();
            var selector = $(this).find(".workflow-event-selector").html();
            var execute = $(this).find(".workflow-event-execute").text();

            if (event == "init") {
                $.globalEval(execute);
            } else if (event == "submit") {
                submitEvents[submitEvents.length] = execute;
            } else {
                $(selector).bind(event, { execute: execute }, function(event) {
                    $.globalEval(event.data.execute);
                });
            }
            $(this).remove();
        });
    },


    //////////////////////////////////////////////////////////
    // configureQTips()
    //////////////////////////////////////////////////////////
    configureQTips: function() {
        $(".workflow-qtip").each(function() {
            var qtid = $(this).find(".workflow-qtip-id").html();
            var txtTitle = $(this).find(".workflow-qtip-title").html();
            var txtText = $(this).find(".workflow-qtip-text:last").html();
            var txtPosition = $(this).find(".workflow-qtip-position").html();
            var txtWidth = $(this).find(".workflow-qtip-width").html();

            var iWidth = parseInt(txtWidth);
            if (isNaN(iWidth))
                iWidth = 250;

            var txtTooltip = "bottomMiddle";
            var txtTarget = "topMiddle";
            if (txtPosition == "bottom") {
                txtTooltip = "topMiddle";
                txtTarget = "bottomMiddle";
            }
            if (txtPosition == "left") {
                txtTooltip = "rightMiddle";
                txtTarget = "leftMiddle";
            }
            if (txtPosition == "right") {
                txtTooltip = "leftMiddle";
                txtTarget = "rightMiddle";
            }

            $("#" + qtid).qtip({
                content: {
                    text: txtText,
                    title: {
                        text: txtTitle
                    }
                },
                position: {
                    type: 'fixed',
                    corner: {
                        tooltip: txtTooltip,
                        target: txtTarget
                    }
                },
                style: {
                    border: {
                        color: '#336699',
                        width: 2
                    },
                    width: {
                        min: iWidth,
                        max: iWidth
                    },
                    padding: 10,
                    textAlign: 'left',
                    background: '#FFFFFF',
                    'font-size': 12,
                    'font-family': 'Arial',
                    title: {
                        'color': '#336699',
                        'font-size': 12,
                        'font-family': 'Arial'
                    },
                    tip: true
                }
            });

            $("#" + qtid).css("text-decoration", "none");

            $(this).remove();
        });
    }
}

