/*
 * Copyright (c) 2007, YouFig Ltd. All Rights Reserved.
 * Author: Matan Amir
 */

if (panelJS == null) var panelJS = {};
if (panelJS.utils == null) panelJS.utils = {};
if (typeof(utilsJS) == "undefined") var utilsJS = panelJS.utils;

utilsJS.panelNamePlu = "Workspaces";
utilsJS.panelNameSin = "Workspace";

utilsJS.defaultLoadingHTML = '<div align="center"><img src="/images/loading.gif" border="0" width="32" height="32" alt="Loading..." /><br />Loading...</div>';
utilsJS.emailRegex = new RegExp("^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\\-+)|([A-Za-z0-9]+\\.+)|([A-Za-z0-9]+\\++))*[A-Za-z0-9]+@((\\w+\\-+)|(\\w+\\.))*\\w{1,63}\\.[a-zA-Z]{2,6}$", "i");
utilsJS.urlRegex = new RegExp("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\\?\\/.=]+$");
utilsJS.trimRegEx = (/^\s+|\s+$/g);
utilsJS.linkRegEx = /(https?:\/\/\S+)/g;
utilsJS.spaceListRegEx = /[\,,\s]+/g;
utilsJS.nonAlphaNumericRegEx = /[^a-zA-Z0-9\-]/g;
utilsJS.stripMarkupRegEx = /<.*?>/g;
utilsJS.months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
utilsJS.datetypes = ["year", "month", "week", "day", "hour", "minute", "second"];
utilsJS.datetypes2 = ["years", "months", "weeks", "days", "hours", "minutes", "seconds"];

utilsJS.formatLocalDate = function(millis, includeTime, includeSeconds)
{
    var d = new Date(millis);
    var buf = [];
    buf.push(d.getFullYear()); buf.push("-"); buf.push(utilsJS.months[d.getMonth()]); buf.push("-"); buf.push(d.getDate());
    if (includeTime) {
        buf.push(" "); buf.push(utilsJS.padDateDigit(d.getHours())); buf.push(":"); buf.push(utilsJS.padDateDigit(d.getMinutes()));
        if (includeSeconds) {
            buf.push(":"); buf.push(utilsJS.padDateDigit(d.getSeconds()));
        }
    }
    return buf.join("");
};

utilsJS.formatRelativeLocalDate = function(millis)
{
    var n = new Date();
    var d = new Date(millis);
    var seconds = parseInt((n.getTime() - d.getTime()) / 1000);
    var minutes = parseInt(seconds / 60);
    var hours = parseInt(minutes / 60);
    var days = parseInt(hours / 24);
    var weeks = parseInt(days / 7);
    var months = parseInt(days / 30); // not very accurate - but good enough...
    var years = parseInt(days / 365);

    if (years > 0)
        return years + " " + (years > 1 ? utilsJS.datetypes2[0] : utilsJS.datetypes[0]) + " ago";

    if (months > 0)
        return months + " " + (months > 1 ? utilsJS.datetypes2[1] : utilsJS.datetypes[1]) + " ago";

    if (weeks > 0)
        return weeks + " " + (weeks > 1 ? utilsJS.datetypes2[2] : utilsJS.datetypes[2]) + " ago";

    if (days > 0)
        return days + " " + (days > 1 ? utilsJS.datetypes2[3] : utilsJS.datetypes[3]) + " ago";

    if (hours > 0)
        return hours + " " + (hours > 1 ? utilsJS.datetypes2[4] : utilsJS.datetypes[4]) + " ago";

    if (minutes > 0)
        return minutes + " " + (minutes > 1 ? utilsJS.datetypes2[5] : utilsJS.datetypes[5]) + " ago";

    if (seconds > 0)
        return seconds + " " + (seconds > 1 ? utilsJS.datetypes2[6] : utilsJS.datetypes[6]) + " ago";

    return "Just now";
};

utilsJS.padDateDigit = function(num)
{
    return (num < 10) ? ("0" + num + "") : (num + "");
};

utilsJS.popup = function(url, width, height)
{
    var w = 550; var h = 350;
    if (arguments.length > 1) { w = width; h = height; }
    return window.open(url,"","width=" + w + ",height=" + h + ",outerWidth=" + (w + 12) + ",outerHeight=" + (h + 51) + ",resizable=1,scrollbars=1,status=1");
};

utilsJS.userPaneShowing = false;
utilsJS.userPanePreHook = null;

utilsJS.showUserPane = function(params, e)
{
    if (utilsJS.userPanePreHook != null) utilsJS.userPanePreHook.call(null);

    var url = "/a/u/view/summary?" + params;  // todo: remove hardcoded url
    var h = dojo.byId("userHover");
    var s = dojo.byId("userHoverSummary");

    if (utilsJS.userPaneShowing)
        utilsJS.closeUserPane();

    utilsJS.userPaneShowing = true;
    h.style.left = (utilsJS.getMouseX(e) + 15) + "px";
    h.style.top = (utilsJS.getMouseY(e) - 10) + "px";
    s.innerHTML = utilsJS.defaultLoadingHTML;
    utilsJS.show(h);
    utilsJS.loadNode(s, url);
};

utilsJS.getMouseX = function(evt)
{
    if (evt.pageX) return evt.pageX;
    else if (evt.clientX) return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    else return 0;
};

utilsJS.getMouseY = function(evt)
{
    if (evt.pageY) return evt.pageY;
    else if (evt.clientY) return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
    else return 0;
};

utilsJS.getViewableWindowCoords = function(win)
{
    if (!win) win = window;
    var has_inner = typeof(win.innerWidth) == 'number';
    var doc = win.document;
    var has_element = doc.documentElement && doc.documentElement.clientWidth;
    
    var left = has_inner
        ? pageXOffset + win.innerWidth
        : has_element
          ? doc.documentElement.scrollLeft +
            doc.documentElement.clientWidth
          : doc.body.scrollLeft +
            doc.body.clientWidth;

    var top = has_inner
        ? pageYOffset + win.innerHeight
        : has_element
          ? doc.documentElement.scrollTop +
            doc.documentElement.clientHeight
          : doc.body.scrollTop +
            doc.body.clientHeight;

    return [left, top];
};

utilsJS.resizeHeightToWindow = function(nodes)
{
    var windowHeight = utilsJS.getViewableWindowCoords()[1];
    if (windowHeight < 1) return 0;

    for (var n = 0; n < nodes.length; n++)
        dojo.byId(nodes[n].node).style.height = (windowHeight - nodes[n].offset) + "px";
    
    return windowHeight;
};

utilsJS.closeUserPane = function()
{
    utilsJS.hide("userHover");
    utilsJS.removeChildren("userSummary");
    utilsJS.userPaneShowing = false;
};

utilsJS.toggleDiv = function(divName)
{
    var div = dojo.byId(divName);
    if (utilsJS.isShowing(div))
        utilsJS.hide(div);
    else
        utilsJS.show(div);
};

utilsJS.toggleDivs = function(divs)
{
    for (var n = 0; n < divs.length; n++)
    {
        utilsJS.toggleDiv(divs[n]);
    }
};

utilsJS.show = function(node)
{
    node = dojo.byId(node);
    if (node == null) return;
    node.style.display = "";
};

utilsJS.hide = function(node)
{
    node = dojo.byId(node);
    if (node == null) return;
    node.style.display = "none";
};

utilsJS.isEmailAddress = function(email)
{
    if (email == null) return false;
    return utilsJS.emailRegex.test(email);
};

utilsJS.isUrl = function(url)
{
    if (url == null) return false;
    return utilsJS.urlRegex.test(url);
};

utilsJS.isShowing = function(node)
{
    node = dojo.byId(node);
    if (node == null) return;
    return (node.style.display != "none");
};

utilsJS.loadJS = function(url, oncompletejs, cache)
{
    utilsJS.loadUrl(url, function(response) {
        if (response) {
            eval(response);
            if (oncompletejs) oncompletejs.call(oncompletejs);
        }
    }, cache);
};

utilsJS.loadNode = function(node, url, oncompleteload, cache)
{
    node = dojo.byId(node);
    if (node == null) return null;
    node.innerHTML = utilsJS.defaultLoadingHTML;
    utilsJS.loadUrl(url, function(response) {
        if (response) {
            utilsJS.removeChildren(node);
            node.innerHTML = response;
            if (oncompleteload) oncompleteload.call(oncompleteload);
        }
    }, cache);
};

utilsJS.loadUrl = function(url, oncomplete, cache)
{
    var useCache = (arguments.length > 2) ? cache : false;
    dojo.xhrGet({
        url: url,
        preventCache: !useCache,
        load: function(response, args) {
            if (response.indexOf("<!--plm-->") > -1) {
                window.location.reload(true);
            } else {
                if (oncomplete) oncomplete.call(oncomplete, response);
            }
        }
    });
};

utilsJS.removeNode = function(node)
{
    if (node.parentNode && node.parentNode != null) node.parentNode.removeChild(node);
};

utilsJS.removeChildren = function(node)
{
    if (node == null) return;
    while (node.firstChild) { node.removeChild(node.firstChild); }
};

utilsJS.moveChildren = function(nodeFrom, nodeTo, trim)
{
    if (trim) {
        while (nodeFrom.hasChildNodes() && nodeFrom.firstChild.nodeType == 3) { nodeFrom.removeChild(nodeFrom.firstChild); }
        while (nodeFrom.hasChildNodes() && nodeFrom.lastChild.nodeType == 3) { nodeFrom.removeChild(nodeFrom.lastChild); }
    }
    while (nodeFrom.hasChildNodes()) { nodeTo.appendChild(nodeFrom.firstChild); }
};

utilsJS.trim = function(str)
{
    return str.replace(utilsJS.trimRegEx, "");
};

utilsJS.linkURLs = function(str)
{
    return str.replace(utilsJS.linkRegEx, "<a href=\"$1\" target=\"_blank\">$1</a>");
};

utilsJS.splitList = function(list)
{
    return utilsJS.trim(list).replace(utilsJS.spaceListRegEx, " ").split(" ");
};

utilsJS.filterNonAlphaNumeric = function(str)
{
    return utilsJS.trim(str).replace(utilsJS.nonAlphaNumericRegEx, "")
};

utilsJS.filterMarkup = function(str)
{
    return str.replace(utilsJS.stripMarkupRegEx, "");
};

utilsJS.escapeXml = function(str, noSingleQuotes)
{
    str = str.replace(/&/gm, "&amp;").replace(/</gm, "&lt;").replace(/>/gm, "&gt;").replace(/"/gm, "&quot;");
    if(!noSingleQuotes){ str = str.replace(/'/gm, "&#39;"); }
    return str;
};

utilsJS.escapeJS = function(str)
{
    str = str.replace(/'/gm, "\\'").replace(/"/gm, "\\\"");
    return str;
};

utilsJS.highlight = function(node, nodeColor, startColor, duration, oncomplete)
{
    node = dojo.byId(node);
    var anim = dojo.animateProperty({
        node: node,
        properties: { backgroundColor: { start: startColor, end: nodeColor } },
        duration: duration
    });
    dojo.connect(anim, "beforeBegin", anim, function() { node.style.backgroundColor = startColor; });
    if (oncomplete) dojo.connect(anim, "onEnd", null, oncomplete);
    anim.play();
};

// --------- Form Utils ----------------------------------
if (panelJS.utils.form == null) panelJS.utils.form = {};
if (formJS == null) var formJS = panelJS.utils.form;

formJS.hasLength = function( list )
{
    return (list != null) && (typeof(list.length) != "undefined");
};

formJS.selectAll = function( srcList )
{
    if ( srcList.options.length < 1) return;
    for( var i = 0; i < srcList.options.length; i++ )
        srcList.options[i].selected = true;
};

formJS.getRadioValue = function( radioList )
{
    if (radioList == null) return null;

    if (formJS.hasLength(radioList)) {
        for (var n = 0; n < radioList.length; n++)
            if (radioList[n].checked) return radioList[n].value;
        
        return null;
    } else {
        return radioList.value;
    }
};

formJS.clearRadios = function( radioList )
{
    if (radioList == null) return null;

    if (formJS.hasLength(radioList)) {
        for (var n = 0; n < radioList.length; n++)
            radioList[n].checked = false;
    } else {
        return radioList.checked = false;
    }
};

formJS.setRadios = function( radioList, value )
{
    if (radioList == null) return;

    if (formJS.hasLength(radioList)) {
        for (var n = 0; n < radioList.length; n++)
            if (radioList[n].value == value)  {
                radioList[n].checked = true;
                break;
            }
    } else {
        radioList.checked = (radioList.value == value);
    }
};
