/** Javascript for the theme.typl , should allow for better caching. */
dojo.require("dijit.layout.ContentPane");
dojo.require("net_ipov._utils");
dojo.require("net_ipov._logger");


dojo.addOnLoad( function(){

    // Add row highlights to all tables w/ class "Highlightable"
    var clsName = "HighlightedRow";
    var fnOver = function (e) {
        dojo.addClass(this, clsName);
    };
    var fnOut = function (e) {
        dojo.removeClass(this, clsName);
    };

    var myRows = dojo.query("table.Highlightable tbody tr");
    myRows.connect("onmouseover", fnOver);
    myRows.connect("onmouseout", fnOut);

    // Add mouseover hightlight to the CCBoxV2 in the folder-grid.tpl
    var fnCCOver = function (e) {
        dojo.addClass(this, 'CCBoxV2Over');
    };
    var fnCCOut = function (e) {
        dojo.removeClass(this, 'CCBoxV2Over');
    };
    var myRows = dojo.query(".CCBoxV2")
    myRows.connect("onmouseover", fnCCOver);
    myRows.connect("onmouseout", fnCCOut);

    // For help system.
    dojo.query("span.helpLink").forEach(function(node) {
        dojo.attr(node.parentNode, "target", "_helpWindow");
    });

    //Expanding Searchbox behavior:
    var eleSeachBar = dojo.byId('searchBarMain');
    var eleSearchContent = dojo.byId('searchPopupContent');
    if ((eleSeachBar) && (eleSearchContent)) {
        //eleSearchContent.parentNode.removeChild( eleSearchContent );
        //var popup = new dijit.

        var popupWidget = new dijit.layout.ContentPane({}, eleSearchContent);

        var _isShowing = false;
        var _seachPopupTimer = null;

        var fnShow = function () {
            if (null != _seachPopupTimer) {
                clearTimeout(_seachPopupTimer);
                _seachPopupTimer = null;
            }
            if (!_isShowing) {
                dijit.popup.open({
                    popup: popupWidget,
                    around: eleSeachBar,
                    orient: {'BL':'TL', 'BR':'TR', 'TL':'BL', 'TR':'BR'},
                    onClose: function(){
                        _isShowing = false;
                    }
                });
                if (eleSeachBar.offsetWidth > eleSearchContent.offsetWidth){
                    var adjustNode = null;
                    adjustNode = eleSearchContent.parentNode;
                    var oldRight = adjustNode.offsetLeft + adjustNode.offsetWidth;

                    // make menu at least as wide as the button
                    dojo.marginBox(eleSearchContent, {w: eleSeachBar.offsetWidth});
                    if(adjustNode){
                        adjustNode.style.left = oldRight - eleSeachBar.offsetWidth + "px";
                    }
                }
                //this.popupStateNode.setAttribute("popupActive", "true");

                _isShowing = true;
            }
        };
        var fnHide = function () {
            dijit.popup.close(popupWidget);
            _isShowing = false;
        };
        var fnTmrHide = function () {
            if (null == _seachPopupTimer) {
                _seachPopupTimer = setTimeout(fnHide, 400);
            }
        };

        dojo.connect(eleSeachBar, "onmouseenter", fnShow);
        dojo.connect(eleSeachBar, 'onmouseleave', fnTmrHide);
        dojo.connect(popupWidget.domNode, 'onmouseenter', function () {
            if (null != _seachPopupTimer) {
                clearTimeout(_seachPopupTimer);
                _seachPopupTimer = null;
            }
        });
        dojo.connect(popupWidget.domNode, 'onmouseleave', fnTmrHide);

    }

    setTimeout(function(){
        dojo.query('div.RMsgBox.gxSuccess').forEach(function(node){
            var href = null;
            var lnks = dojo.query('a.RedirectLink', node);
            if ((lnks) && (lnks.length == 1)) {
                href = dojo.attr(lnks[0], 'href');
            }

            var ani = dojo.fadeOut({node:node, duration:3000});
            ani.onEnd = function(){
                node.parentNode.removeChild(node);
                if (href) {
                    location.href = href;
                }
            };
            ani.play();
        });
    }, 4500);
    
    net_ipov._utils.styleHoverButtons( dojo.body() );

});

//Call firebug logging in a 'safe' manner, e.g. exisitance of firebug is checked.
function fbugCall(fbData,fbFunc) {
  if (!fbFunc) { fbFunc = 'log'; }
  net_ipov._logger[fbFunc](fbData);
}


function flashTestAndPromt() {
    // at this point the swfobject code should be loaded...
    var fpver = swfobject.getFlashPlayerVersion();
    //alert(fpver.major + "." + fpver.minor + "." + fpver.release);
    if (fpver.major < 9) {
        var e = dojo.byId('snifferWarningMsg');
        if (e) {
            e.innerHTML = 'You need Adobe Flash Player 9 or above to view this site properly, but it appears that you ' +
                ((fpver.major > 0) ? 'currently have version ' + fpver.major : 'do not have it installed' ) +
                '. You can upgrade to the latest version of the Flash Player from ' +
                '<a class="LinkExternal" href="'+ location.protocol + '//www.adobe.com/go/EN_US-H-GET-FLASH">Adobe\'s site</a>. ' +
                'If you are unable to install software please contact your Help Desk / IT/IS department for assistance.';
            dojo.byId('snifferBoxContainer').style.display = 'block';
        }
    }
}

/** Used as a onclick replacement for an anchor link (e.g. javascript driven. */
function praisGotoPage(url, target, itemId) {
    url = url.replace(/&amp;/g, '&');
    if (itemId) {
        url = url.replace(/__ITEM_ID__/, itemId);
    }
    if ((target) && ('_self' != target)) {
        window.open(url, target);
    } else {
        location.href = url;
    }
}


// From http://eriwen.com/javascript/js-stack-trace/
// WARNING : May cause server problems in IE if the stack trace contains recursion!
function getStackTrace() {
    var callstack = [];
    var isCallstackPopulated = false;
    try {
        i.dont.exist+=0; //does not exist - that's the point
    } catch(e) {
        if (e.stack) { //Firefox
            var lines = e.stack.split("\n");
            for (var i = 0, len = lines.length; i < len; i++) {
                if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
                    callstack.push(lines[i]);
                }
            }
            //Remove call to printStackTrace()
            callstack.shift();
            isCallstackPopulated = true;
        }
        else if (window.opera && e.message) { //Opera
            var lines = e.message.split("\n");
            for (var i = 0, len = lines.length; i < len; i++) {
                if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
                    var entry = lines[i];
                    //Append next line also since it has the file info
                    if (lines[i+1]) {
                        entry += " at " + lines[i+1];
                        i++;
                    }
                    callstack.push(entry);
                }
            }
            //Remove call to printStackTrace()
            callstack.shift();
            isCallstackPopulated = true;
        }
    }
    if (!isCallstackPopulated) { //IE and Safari
        var currentFunction = arguments.callee.caller;
        while (currentFunction) {
            var fn = currentFunction.toString();
            //If we can't get the function name set to "anonymous"
            var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf("(")) || "anonymous";
            callstack.push(fname);
            currentFunction = currentFunction.caller;
        }
    }
    // since we want it as a string.
    return callstack.join("\n");
}

/** This is a re-usable popup menu for the child items listed in a folder. */
function buildFolderChildItemMenu() {

    //childItemsMenu._targetItemId
    var childItemsMenu = new dijit.Menu({id:'childItemsMenu'});

    // I think we should be able to set this right before the menu appears and have the functions work as intended...
    childItemsMenu._currentData = null;

    //Email Link
    var mnuItm_0 = new dijit.MenuItem({
        iconClass:"ccsGridMnuEmail",
        label: _t['email'],
        onClick: function(){
            loadDialog( ccslnk_SendEmail.replace(/__ITEM_ID__/, childItemsMenu._currentData.id),
                'iPOVmailDialog', _t['email'],
                 null, null, null, ['dijit.form.ComboBox','dojox.data.QueryReadStore','net_ipov.MultiCompleteComboBox']);
        }
    });
    childItemsMenu.addChild(mnuItm_0);

    // Edit Properties
    var mnuItm_1 = new dijit.MenuItem({
        iconClass:"ccsGridMnuProperties",
        label: _t['editProps'],
        onClick: function(){
            praisGotoPage(ccslnk_EditProps, '_self', childItemsMenu._currentData.id);
        }
    });
    childItemsMenu.addChild(mnuItm_1);

    // People/Permissions
    var mnuItm_2 = new dijit.MenuItem({
        iconClass:"ccsGridMnuPermissions",
        label: _t['viewPermissions'],
        onClick: function() {
            loadQuickPermissionsDialog( ccslnk_ViewPermissions.replace(/__ITEM_ID__/, childItemsMenu._currentData.id),
                 'quickPermissionsDialog', _t['permissionsDlgTitle'] + ' ' + childItemsMenu._currentData.title );
        }
    });
    childItemsMenu.addChild(mnuItm_2);

    // Download
    var mnuItm_3 = new dijit.MenuItem({
        iconClass:"ccsGridMnuDownload",
        label: _t['download'],
        onClick: function(){
            praisGotoPage(ccslnk_download, '_blank', childItemsMenu._currentData.id );
        }
    });
    childItemsMenu.addChild(mnuItm_3);

    childItemsMenu.startup();

    // get this list of menu 'buttons' that will trigger the menu to open:
    var fnOpenMenu = function (evt) {
        evt.stopPropagation(); 	// so the 'onclick' for the background won't trigger.

        var node = this;
        if (!node.ccsData) {
            var nodeData = dojo.attr(node, 'dojoData');
            if (nodeData) {
                node.ccsData = eval( '({' + nodeData + '})' );
            } else {
                return;
            }
        }

        childItemsMenu._currentData = node.ccsData;

        mnuItm_3.setDisabled( ! node.ccsData.canDownload );

        var fnClose = function(){
            dijit.popup.close(childItemsMenu);
        };

        // hide any tooltip, kind of a hack to make work...:
        if (dijit._masterTT) {
            dijit._masterTT.hide( dijit._masterTT.aroundNode );
        }

        dijit.popup.open({
            parent: node,
            popup: childItemsMenu,
            around: node,
            orient: ['BR', 'BL', 'TR', 'TL'],
            onExecute: fnClose,
            onCancel: fnClose
        });
        childItemsMenu.focus();
    };


    // take care of when the menu looses focus to actually hide it:
    childItemsMenu._onBlur = function () {
        console.log("Popup menu onblur.");
        this.inherited('_onBlur', arguments);
        dijit.popup.close(childItemsMenu);
    };

    var fnHover = function () {
        dojo.addClass(this, 'MnuMoreHover');
    };
    var fnBlur = function () {
        dojo.removeClass(this, 'MnuMoreHover');
    };

    dojo.query('.MnuChildItemMore').forEach(function(node, index, arr) {
        dojo.connect(node, 'onclick', node, fnOpenMenu);
        dojo.connect(node, 'onmouseenter', node, fnHover);
        dojo.connect(node, 'onmouseleave', node, fnBlur);
        dojo.connect(node, 'onfocus', node, fnHover);
        dojo.connect(node, 'onblur', node, fnBlur);
    });
}
