var DEBUG_MODE = false;

if (typeof Array.indexOf != 'function') {
    Array.prototype.indexOf = function(f, s) {
        if (typeof s == 'undefined') {
            s = 0;
        }
        for (var i = s; i < this.length; i++) {
            if (f === this[i]) return i;
        }
        return -1;
    }
}

function toUnixStamp(strDate, dayOffset) {
    var date = new Date(strDate);
    if (isValidDate(date)) {
        dayOffset = dayOffset != null ? parseInt(dayOffset) : 0;
        return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate() + dayOffset);
    }
    return null;
}

function isValidDate(object) {
    if (Object.prototype.toString.call(object) !== "[object Date]") {
        return false;
    }
    return !isNaN(object.getTime());
}


function escapePeriods(str) {
    var elements = str.split(".");
    if (elements.length > 1) {
        var count = elements.length;
        var escapedString = elements[0] + "\\.";
        for (var index = 1; index < (count - 1); index++) {
            escapedString = escapedString + elements[index] + "\\.";
        }
        escapedString = escapedString + elements[count - 1];
        return escapedString;
    } else {
        return str;
    }
}

function escapePluses(str) {
    var elements = str.split("+");
    if (elements.length > 1) {
        var count = elements.length;
        var escapedString = elements[0] + "\\+";
        for (var index = 1; index < (count - 1); index++) {
            escapedString = escapedString + elements[index] + "\\+";
        }
        escapedString = escapedString + elements[count - 1];
        return escapedString;
    } else {
        return str;
    }
}

function escapeApostrophes(str) {
    var elements = str.split("'");
    if (elements.length > 1) {
        var count = elements.length;
        var escapedString = elements[0] + "\\'";
        for (var index = 1; index < (count - 1); index++) {
            escapedString = escapedString + elements[index] + "\\'";
        }
        escapedString = escapedString + elements[count - 1];
        return escapedString;
    } else {
        return str;
    }
}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
    return pattern.test(emailAddress);
}
function showSuccess(successMsg) {
    if (successMsg == "" || successMsg == null) return;
    Boxy.alert(htmlspecialchars(successMsg), null, {title: 'Success'});
}
function showError(errorMsg) {
    if (errorMsg == "" || errorMsg == null) return;
    Boxy.alert(errorMsg, null, {title: 'Info'});
    if (typeof(pageTracker) !== "undefined") {
        pageTracker._trackEvent("alert", "error", errorMsg.substr(0, 32));
    }
}

function Hash() {
    this.content = [];
    this.size = 0;
}

Hash.prototype = {
    unset: function(key) {
        var tmp_value;
        if (typeof this.content[key] !== 'undefined') {
            this.size--;
            tmp_value = this.content[key];
            delete this.content[key];
        }
        return tmp_value;
    },

    get: function(key) {
        return this.content[key];
    },

    set: function(key, val) {
        if (typeof val !== 'undefined') {
            if (typeof this.content[key] === 'undefined') {
                this.size++;
            }
            this.content[key] = val;
        }
        return val;
    },

    has: function(key) {
        return typeof this.content[key] !== 'undefined';
    }
};

/* url encode */
function urlencode(str) {
    return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}


/* Send an HTTP POST request
 * Session variables will be attached to the HTTP POST request
 * RoleOid session value can be overridden by passing a second parameter
 */
function openUrl(url, roleOid, params) {

    var form = document.createElement("form");
    form.setAttribute("method", "POST");
    form.setAttribute("action", url);

    if (roleOid != undefined) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", "roleOid");
        hiddenField.setAttribute("value", roleOid);
        form.appendChild(hiddenField);
    }

    if (params != null) {
        for (var key in params) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }
    }
    document.body.appendChild(form);    // Not entirely sure if this is necessary
    form.submit();
}

/* daysDiff(String date, String format)
 * Returns the number of days until "date".
 * Use days_diff within format to express days until.
 */
function daysDiff(date) {
    var d, n, days_diff;

    d = date.time;
    n = new Date().getTime();
    days_diff = Math.floor((d - n) / 86400000);
    return (days_diff < 6 && "5" ||
        days_diff < 31 && "30" ||
        days_diff < 61 && "60" ||
        days_diff > 61 && "-60");
}


function binarySearch(array, value) {
    var low, high, mid;
    low = 0;
    high = array.length;
    while (low <= high) {
        mid = (low + high) / 2;
        if (array[mid] > value)
            high = mid - 1;
        else if (array[mid] < value)
            low = mid + 1;
        else
            return mid;
    }
    return -1;
}


function htmlspecialchars(string, quote_style) {
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();

    if (false === (histogram = get_html_translation_table('HTML_SPECIALCHARS', quote_style))) {
        return false;
    }
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    return tmp_str;
}


function get_html_translation_table(table, quote_style) {
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};

    useTable = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');

    // Translate arguments
    constMappingTable[0] = 'HTML_SPECIALCHARS';
    constMappingTable[1] = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }

    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }

    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }

    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    } else {
        throw Error("Table: " + useTable + ' not supported');
        return false;
    }

    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal)
        histogram[symbol] = entities[decimal];
    }
    return histogram;
}


function disablePage() {
    $("#modalDiv").css("display", "");

    var clientBounds = _getClientBounds();
    var clientWidth = clientBounds.clientWidth;
    var clientHeight = clientBounds.clientHeight;

    var width =
        Math.max(Math.max(document.documentElement.scrollWidth,
            document.body.scrollWidth), clientWidth) + 'px';
    var height =
        Math.max(Math.max(document.documentElement.scrollHeight,
            document.body.scrollHeight), clientHeight) + 'px';

    $("#modalDiv").css("zIndex", "10000");
    $("#modalDiv").css("height", height);
    $("#modalDiv").css("width", width);
    $("#moadlDiv").css("padding-top", "20%");
    $("#moadlDiv").css("font-weight", "bold");
}

function enablePage() {
    $("#modalDiv").css("display", "none");
}

function _getClientBounds() {
    var clientWidth;
    var clientHeight;
    if (/Safari[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
        clientWidth = window.innerWidth;
        clientHeight = window.innerHeight;
    } else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        clientWidth = document.documentElement.clientWidth;
        clientHeight = document.documentElement.clientHeight;
    } else if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
        clientWidth = Math.min(window.innerWidth,
            document.body.clientWidth);
        clientHeight = Math.min(window.innerHeight,
            document.body.clientHeight);
    } else {
        clientWidth = Math.min(window.innerWidth,
            document.documentElement.clientWidth);
        clientHeight = Math.min(window.innerHeight,
            document.documentElement.clientHeight);
    }

    return {
        clientWidth  : clientWidth,
        clientHeight : clientHeight
    };
}

var gException = null;
var gMsg = null;
function errh(msg, exception) {
    if (msg == $("#sessionTimedOut").val() || exception.message == 'Your session has timed out. Please re-login.') {
        Boxy.alert(
            $("#sessionTimedOut").val(),
            function() {
                openUrl('/adminmgmt/adminapp/login/loginPage', undefined, {});

            }, {title:'Error'}
        );
        return;
    }

    if (exception.javaClassName == 'java.lang.ClassCastException') {
        Boxy.ask(
            'An error occurred while processing your request.We\'re sorry, but we are unable to display this page at this time. If you continue to get this error, please contact <a href="' + $("#supportLink").val() + '">LPI Technical Support</a>. '
            , ['LPI Home']
            , function(val) {
                if (val == 'LPI Home') {
                    openUrl('/adminmgmt/adminapp/login/secureHome', undefined, {});
                }

            });
        return;
    }

    if (DEBUG_MODE && exception != null) {
        gException = exception;
        gMsg = msg;
        Boxy.alert(htmlspecialchars(msg) + "<br />Debug Mode is ON. <a href='javascript:detailException()'><b>Click Here</b></a> for Detailed Server-Side Exception", null, {title: 'Error'});
    }
    else
        Boxy.alert(htmlspecialchars(msg), null, {title: 'Error'});
}

function detailException() {
    var str_stackTrace = gMsg + "\r\n" + gException.javaClassName + "\r\n";
    if (gException.stackTrace != null) {
        for (var i = 0; i < gException.stackTrace.length; i++) {
            str_stackTrace += "at "
            str_stackTrace += gException.stackTrace[i].className;
            str_stackTrace += "(" + gException.stackTrace[i].fileName + ":";
            str_stackTrace += gException.stackTrace[i].lineNumber + ")\r\n";
        }
    }
    Boxy.alert("Detailed Exception;please attach this to your bug report:<br /><textarea cols='40' rows='20'>" + str_stackTrace + "</textarea>");
}

dwr.engine.setErrorHandler(errh);

function showPrivacy() {
    var policy = "<div style='width:100%;height:300px;overflow: auto;'>" + $("#tosBody").val() + "</div>";
    Boxy.alert(policy, null, {title: $("#tosTitle").val()});
}

function showTOS() {
    var copyrights = "<div style='width:100%;height:300px;overflow: auto;'>" + $("#licenseBody").val() + "</div>";
    Boxy.alert(copyrights, null, {title: $("#licenseTitle").val()});
}


function showCopyrights() {
    var copyrights = "<div style='width:100%;height:300px;overflow: auto;'>" + $("#copyBody").val() + "</div>";
    Boxy.alert(copyrights, null, {title: "Copyrights"});
}


var dtCh = "/";
var minYear = 1900;
var maxYear = 2100;

function isInteger(s) {
    for (var 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 returnString = "";
    for (var 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
}

function validateDate(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 false;
    }
    if (strMonth.length < 1 || month < 1 || month > 12) {
        return false;
    }
    if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > daysInFebruary(year)) || day > daysInMonth[month]) {
        return false;
    }
    if (strYear.length != 4 || year == 0 || year < minYear || year > maxYear) {
        return false;
    }
    if (dtStr.indexOf(dtCh, pos2 + 1) != -1 || isInteger(stripCharsInBag(dtStr, dtCh)) == false) {
        return false;
    }
    return true;
}


function populateSurveyQuestions(response, currentPage) {
    $("#questionsTable").empty();
    var questionNumber = (currentPage - 2) * 10 + 1;
    $("#unansweredDiv").empty();
    for (var j = 0; j < response.unansweredQuestions.length; j++) {
        $("#unansweredDiv").prepend("<li style=\"float: right; margin-left: 4px; list-style-type: none;\">" + response.unansweredQuestions[j] + "</li>");
    }
    if (response.unansweredQuestions.length > 0)
        $("#unansweredDiv").append("<div style='float:right'>Unanswered Questions:</div>");

    for (var i = 0; i < response.questions.length; i++) {
        //  BASE SURVEY QUESTION
        var options = "";
        if (response.questions[i].questionDisplayFormat == "dropdown")
            options = "<select id='answer-" + i + "'>";

        for (var j = 0; j < response.questions[i].options.length; j++) {
            var selected = "";
            if (response.questions[i].options[j].optionOid == response.questions[i].selectedAnswer) {
                if (response.questions[i].questionDisplayFormat == "dropdown")
                    selected = "selected";
                else if (response.questions[i].questionDisplayFormat == "radio")
                    selected = "checked";
            }

            if (response.questions[i].selectedAnswer == null) {
                if (response.questions[i].options[j].optionValue == 0) {
                    if (response.questions[i].questionDisplayFormat == "dropdown")
                        selected = "selected";
                    else if (response.questions[i].questionDisplayFormat == "radio")
                        selected = "checked";
                }
            }

            //options += "<option value='" + response.questions[i].options[j].optionOid + "' " + selected + ">"
            //+ response.questions[i].options[j].optionText + "</option>";

            if (response.questions[i].questionDisplayFormat == "dropdown")
                options += "<option value='" + response.questions[i].options[j].optionOid + "' " + selected + ">"
                    + response.questions[i].options[j].optionText + "</option>";
            else if (response.questions[i].questionDisplayFormat == "radio")
                options += "<input type='radio' id='answer-" + i + "' name='answer-" + i + "' value='" + response.questions[i].options[j].optionOid + "' " + selected + "/> "
                    + response.questions[i].options[j].optionText + "<br/>";

        }
        if (response.questions[i].questionDisplayFormat == "dropdown")
            options += "</select>";

        var cssClass = "odd";

        if (i % 2 == 0) cssClass = "even";

        $("#questionsTable").append("<tr id='q-" + response.questions[i].questionOid + "' style='display: none'><td class='" + cssClass + "'>"
            + "<div style='float:left;width:67%'><ol style='margin-left:30px;' start=" + (questionNumber++) + "><li>"
            + response.questions[i].questionText
            + "</li></ol></div><div style='float:left'>"
            + options + "</div></td></tr>");

        if (i - 1 >= 0)
            $("#questionsTable tr:eq(" + (i - 1) + ")").fadeIn("slow");

    }
    $("#questionsTable tr:eq(" + (i - 1) + ")").fadeIn("slow");

}

function getSelectedAnswerForQuestion(questionIndex) {
    var selectedValue;
    if ($("#answer-" + questionIndex + " :selected").val() != undefined)
        selectedValue = $("#answer-" + questionIndex + " :selected").val();
    else if ($("input[name='answer-" + questionIndex + "']:checked").val() != undefined)
        selectedValue = $("input[name='answer-" + questionIndex + "']:checked").val();
    return selectedValue;
}

function getSelectedAnswersForQuestion(questionIndex) {
    var selectedValue = new Array();
    var i = 0;
    if ($("input[name='answer-" + questionIndex + "']:checked").val() != undefined) {
        selectedValue = new Array();
    }
    $("input[name='answer-" + questionIndex + "']:checked").each(function() {
        selectedValue.push($(this).val());
    });
    return selectedValue;
}


function escapeSingleQuote(str) {
    var elements = str.split("'");
    if (elements.length > 1) {
        var count = elements.length;
        var escapedString = elements[0] + "\\'";
        for (var index = 1; index < (count - 1); index++) {
            escapedString = escapedString + elements[index] + "\\'";
        }
        escapedString = escapedString + elements[count - 1];
        return escapedString;
    } else {
        return str;
    }
}

function escapeEmptySpaces(str) {
    var elements = str.split(" ");
    if (elements.length > 1) {
        var count = elements.length;
        var escapedString = elements[0] + "\\ ";
        for (var index = 1; index < (count - 1); index++) {
            escapedString = escapedString + elements[index] + "\\ ";
        }
        escapedString = escapedString + elements[count - 1];
        return escapedString;
    } else {
        return str;
    }
}
