// JavaScript Document

init = function() {

    //--------------------------------Show popup
    var currentPopup = ""; // This variable save the id of the active popup

    showPopup = function(myElement, parent, myPopup, elmNum) {

        var popup = document.getElementById(myPopup);
        popup.style.top = "0px";
        popup.style.left = "0px";
        popup.style.display = "block";

        // get the popup arrow

        var popupArrow = DOM.getChildren(
                DOM.get(myPopup)
                )[1];

        if (popupArrow) popupArrow.className = "popupArrow";

        /* set popup position */

        //-- For IE
        var windowYOffset = 0;
        var windowHeight = 0;
        var windowWidth = 0;
        var windowXOffset = 0;

        if (YAHOO.env.ua.ie > 0)
        {
            windowYOffset = document.documentElement.scrollTop;
            windowXOffset = document.documentElement.scrollLeft;

            windowHeight = document.documentElement.offsetHeight;
            windowWidth = document.documentElement.offsetWidth;
        }
        else
        {
            windowYOffset = window.pageYOffset;
            windowXOffset = window.pageXOffset;

            windowHeight = window.innerHeight;
            windowWidth = window.innerWidth;
        }

        popup.style.zIndex = "11009";

        var myElementOffset = Element.cumulativeOffset(myElement);

        // Set the position of the popup.
        var popupXPosition = myElementOffset[0] - 20;
        var popupYPosition = myElementOffset[1] - popup.offsetHeight + 10;

        popupYPosition = Math.round(popupYPosition);

        if (popupYPosition < windowYOffset)
        {
            if (windowYOffset - popupYPosition > myElement.offsetHeight / 2)
            {
                var temp = popupYPosition;
                popupYPosition += popup.offsetHeight + myElement.offsetHeight;

                if (popupArrow) popupArrow.className = "popupArrow2";

            }
            else
                popupYPosition += windowYOffset - popupYPosition;
        }

        if (popupXPosition + popup.offsetWidth > windowWidth)
        {
            popupXPosition -= popupXPosition + popup.offsetWidth - windowWidth + 20;
        }

        popup.style.marginTop = popupYPosition + "px";
        popup.style.marginLeft = popupXPosition + "px";

        //set the x position of the popup arrow
        var popupArrowXPosition = myElementOffset[0] + myElement.offsetWidth / 2 - popupXPosition;

        if (popupArrow) {
            popupArrow.style.left = 0;
            popupArrow.style.marginLeft = popupArrowXPosition + "px";
        }

        if (currentPopup != "" && currentPopup != myPopup)
            document.getElementById(currentPopup).style.display = "none";

        currentPopup = myPopup;

    }

    showToDoPopup = function(myElement, parent, myPopup, elmNum) {

        var popup = document.getElementById(myPopup);

        /* set popup position */
        //-- For IE
        var windowYOffset = 0;
        var windowHeight = 0;

        //define universal dsoc left point
        var dsocleft = 0;
        //define universal dsoc top point
        var dsoctop = 0;
        dsocleft = document.getElementById("todo_list_container").offsetLeft;
        dsoctop = document.getElementById("todo_list_container").offsetTop;
        if (YAHOO.env.ua.ie > 0)
        {
            windowYOffset = document.documentElement.scrollTop;
            windowXOffset = document.documentElement.scrollLeft;

            windowHeight = document.documentElement.offsetHeight;
            windowWidth = document.documentElement.offsetWidth;
        }
        else
        {
            windowYOffset = window.pageYOffset;
            windowXOffset = window.pageXOffset;

            windowHeight = window.innerHeight;
            windowWidth = window.innerWidth;
        }

        popup.style.top = dsoctop + "px";
        popup.style.left = dsocleft + "px";
        popup.style.display = "block";
        popup.style.zIndex = "11009";
        popup.style.visibility = "visible";

        var popupYPosition = 0;

        if (parent != null)
            popupYPosition = parent.offsetTop + myElement.offsetTop - popup.offsetHeight + 10;
        else
            popupYPosition = 403 - popup.offsetHeight + 10;


        popupYPosition = Math.round(popupYPosition);

        // set the y position of the popup
        if (popupYPosition < windowYOffset)
        {
            if (windowYOffset - popupYPosition > myElement.offsetHeight / 2)
            {
                popupYPosition += popup.offsetHeight + myElement.offsetHeight;
            }
            else
                popupYPosition += windowYOffset - popupYPosition;
        }

        //set the x position of the popup
        var popupXPosition = 0;

        if (parent != null)
            popupXPosition = parent.offsetLeft + myElement.offsetLeft - 20;
        else
            popupXPosition = 186 * elmNum - 20;


        if (popupXPosition + popup.offsetWidth > windowWidth)
        {
            popupXPosition -= popupXPosition + popup.offsetWidth - windowWidth + 20;
        }

        popup.style.marginTop = popupYPosition + "px";
        popup.style.marginLeft = popupXPosition + "px";

        if (currentPopup != "" && currentPopup != myPopup)
            document.getElementById(currentPopup).style.display = "none";

        currentPopup = myPopup;
        parent.parentNode.parentNode.appendChild(popup);
    }

    // show the popup in the table results
    showPopupResults = function(itemNum, myPopup) {

        var popup = document.getElementById(myPopup);

        popup.style.top = "0px";
        popup.style.left = "0px";

        popup.style.display = "block";


        popup.style.marginTop = (itemNum * 70) + "px";
        popup.style.marginLeft = "200px";

        if (currentPopup != "" && currentPopup != myPopup)
            document.getElementById(currentPopup).style.display = "none";

        currentPopup = myPopup;

    }
    closeToDoPopup = function(myPopup) {
        var element = document.getElementById(currentPopup);
        element.style.display = "none";
        element.style.visibility = "hidden";
    }
    removeToDoPopup = function(myPopup) {
        var element = document.getElementById(currentPopup);
        element.style.display = "none";
        element.style.visibility = "hidden";
        element.id = element.id + "closed";
    }
    closePopup = function(myPopup) {
        document.getElementById(myPopup).style.display = "none";
        currentPopup = "";
    }

    hidePopup = function() {
        if (currentPopup != "")
        {
            document.getElementById(currentPopup).style.display = "none";
            currentPopup = "";
        }
    }


    //------------------- Show the modalbox

    var popupDialogBox;

    showPopup3 = function(message) {


        //Set the attributes for the modal box
        popupDialogBox = new YAHOO.widget.Panel("popupDialogBox",
        { width: "681px",
            height: "227px",
            fixedcenter: true,
            close: false,
            draggable: true,
            zindex:10001,
            modal: true,
            visible: false
        }
                );


        //Render the box
        var body = '<div class="popup_hd"><a href="javascript:void(1);" onclick="hidePopup3();">Close</a></div><br/><br/><div style="font-size:18px; font-weight:bold;">' + message + '</div>';

        popupDialogBox.setBody(body);
        popupDialogBox.render(document.body);

        // Show the Panel
        popupDialogBox.show();

        // if IE6
        if (YAHOO.env.ua.ie == 6)
        {
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.backgroundImage = "none";
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.backgroundColor = "#000";
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.filter = "alpha(opacity=70)";
        }

    }
    showPopup31 = function(message) {


        //Set the attributes for the modal box
        popupDialogBox = new YAHOO.widget.Panel("popupDialogBox",
        { width: "681px",
            height: "227px",
            fixedcenter: true,
            close: false,
            draggable: true,
            zindex:10001,
            modal: true,
            visible: false
        }
                );


        //Render the box
        var body = '<div class="popup_hd"><a href="javascript:void(1);" onclick="hidePopup3();">Close</a></div><div style="font-size:18px; font-weight:bold;">' + message + '</div>';

        popupDialogBox.setBody(body);
        popupDialogBox.render(document.body);

        // Show the Panel
        popupDialogBox.show();

        // if IE6
        if (YAHOO.env.ua.ie == 6)
        {
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.backgroundImage = "none";
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.backgroundColor = "#000";
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.filter = "alpha(opacity=70)";
        }

    }

    showPopup4 = function(message) {


        //Set the attributes for the modal box
        popupDialogBox = new YAHOO.widget.Panel("popupDialogBox",
        { width: "681px",
            height: "167px",
            fixedcenter: true,
            close: false,
            draggable: true,
            zindex:10001,
            modal: true,
            visible: false
        }
                );


        //Render the box
        var body = '<div class="popup_hd"><a href="javascript:void(1);" onclick="hidePopup3();">Close</a></div><br/><br/><div style="font-size:18px; font-weight:bold;">' + message + '</div>';

        popupDialogBox.setBody(body);
        popupDialogBox.render(document.body);

        // Show the Panel
        popupDialogBox.show();

        // if IE6
        if (YAHOO.env.ua.ie == 6)
        {
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.backgroundImage = "none";
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.backgroundColor = "#000";
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.filter = "alpha(opacity=70)";
        }

    }
    showPopup5 = function(message, name, description) {
        message = message.replace('@name@', name);
        message = message.replace('@description@', description);

        //Set the attributes for the modal box
        popupDialogBox = new YAHOO.widget.Panel("popupDialogBox",
        { width: "681px",
            height: "167px",
            fixedcenter: true,
            close: false,
            draggable: true,
            zindex:10001,
            modal: true,
            visible: false
        }
                );

        //Render the box
        var body = '<div class="popup_hd"><a href="javascript:void(1);" onclick="hidePopup3();">Close</a></div><br/><br/><div style="font-size:18px; font-weight:bold;">' + message + '</div>';

        popupDialogBox.setBody(body);
        popupDialogBox.render(document.body);

        // Show the Panel
        popupDialogBox.show();

        // if IE6
        if (YAHOO.env.ua.ie == 6)
        {
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.backgroundImage = "none";
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.backgroundColor = "#000";
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.filter = "alpha(opacity=70)";
        }

    }

    hidePopup3 = function()
    {
        popupDialogBox.hide();
        popupDialogBox.destroy();
    }

    confirmAction = function(textConfirm, jsForOk, showReject, jsForReject) {

        //Set the attributes for the modal box
        popupDialogBox = new YAHOO.widget.Panel("popupDialogBox",
        { width: "671px",
            height: "150px",
            fixedcenter: true,
            close: false,
            draggable: true,
            zindex:10001,
            modal: true,
            visible: false
        }
                );
        var buttons;

        if (showReject) {
            buttons = '<div style="padding: 50px 0 5px 270px;"><a href="javascript:;" class="button2" onclick="' + jsForOk + '"><span>YES</span></a><a href="javascript:;" class="button2" onclick="' + jsForReject + '"><span>NO</span></a><a href="javascript:;" class="button2" onclick="hidePopup3();"><span>CANCEL</span></a></div>'
        } else {
            buttons = '<div style="padding: 50px 0 5px 300px;"><a href="javascript:;" class="button2" onclick="' + jsForOk + '"><span>YES</span></a><a href="javascript:;" class="button2" onclick="hidePopup3();"><span>CANCEL</span></a></div>'
        }


        var message = '<div style="text-align: left;">'
                + '<div style="font-size: 12px; font-weight: bold; color:#000; padding: 30 0 5px 5px;"><span style="padding-left:20px;">' + textConfirm + '</span></div>'
                + buttons
                + '</div>';

        //Render the box
        var body = '<div class="popup_hd"><a href="javascript:void(1);" onclick="hidePopup3();">Close</a></div><br/><br/><div style="font-size:18px; font-weight:bold;">' + message + '</div>';

        popupDialogBox.setBody(body);
        popupDialogBox.render(document.body);

        // Show the Panel
        popupDialogBox.show();

        // if IE6
        if (YAHOO.env.ua.ie == 6)
        {
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.backgroundImage = "none";
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.backgroundColor = "#000";
            YAHOO.util.Dom.getElementsByClassName('mask')[0].style.filter = "alpha(opacity=70)";
        }
    }

    //---------------------------------------------- Expand / Collapse

    expandCollapse = function(link_ico, content, ico_type) {

        hidePopup();

        if (document.getElementById(content).style.height != "0px")
        {
            var collapse = new YAHOO.util.Anim(content, { height: {to: 0}, paddingTop: {to: 0} , paddingBottom: {to: 0} }, 0.2);
            collapse.animate();

            link_ico.style.height = "16px";
            link_ico.style.width = "10px";

            if (ico_type == "active")
                link_ico.style.backgroundImage = 'url(images/arrow_expand.png)';
            else
                link_ico.style.backgroundImage = 'url(images/arrow_upcoming_expand.png)';

        }
        else
        {
            var expand = new YAHOO.util.Anim(content, { height: {to: 134}, paddingTop: {to: 10}, paddingBottom: {to: 10} }, 0.2);
            expand.animate();

            link_ico.style.height = "10px";
            link_ico.style.width = "16px";

            if (ico_type == "active")
                link_ico.style.backgroundImage = 'url(images/arrow_collapse.png)';
            else
                link_ico.style.backgroundImage = 'url(images/arrow_upcoming_collapse.png)';

        }

    }

    // Expand / collapse functionality in portfolio page
    expandCollapse2 = function(link_ico, content, container) {

        if (document.getElementById(content).style.display == "none")
        {
            document.getElementById(content).style.display = "block";
            link_ico.style.backgroundImage = 'url(images/profile_contest_collapse.png)';
            link_ico.style.width = "16px";
            link_ico.style.height = "9px";
            //document.getElementById(container).style.backgroundImage = 'url(images/profile_contest_bg2.png)';
        }
        else
        {
            document.getElementById(content).style.display = "none";
            link_ico.style.backgroundImage = 'url(images/profile_contest_expand.png)';
            link_ico.style.width = "9px";
            link_ico.style.height = "16px";
            //document.getElementById(container).style.backgroundImage = 'url(images/profile_contest_bg.png)';
        }

    }

    // Expand / collapse message
    showHideMessage = function(content, messageRead, messageId) {
        var link_ico = document.getElementById('icon' + messageId);
        if (document.getElementById(content).style.display == "none")
        {
            document.getElementById(content).style.display = "block";
            link_ico.style.backgroundImage = 'url(images/message_collapse.png)';
        }
        else
        {
            document.getElementById(content).style.display = "none";
            link_ico.style.backgroundImage = 'url(images/message_expand.png)';
        }
        if (messageRead != 'true') {
            MyXanthus.markMessageRead(messageId);
        }
    }

    // Expand / collapse message
    showHideMessageSection = function(link_ico, content) {
        if (document.getElementById(content).style.display == "none")
        {
            document.getElementById(content).style.display = "block";
            link_ico.style.backgroundImage = 'url(images/message_collapse.png)';
        }
        else
        {
            document.getElementById(content).style.display = "none";
            link_ico.style.backgroundImage = 'url(images/message_expand.png)';
        }
    }

    //---------------------------------------------------------------------------------------- tabs

    showHideTab = function(itemIndex) {

        if (document.getElementById("tabs") == null) return;

        var tabsItemsNode = document.getElementById("tabs").childNodes;
        var menuIndex = 0;

        for (var i = 0; i < tabsItemsNode.length; ++i)
        {
            if (tabsItemsNode[i].nodeName == "LI")
            {
                if (menuIndex == itemIndex)
                    tabsItemsNode[i].className += ' on';
                else
                {
                    while (tabsItemsNode[i].className.search("on") != -1)
                        tabsItemsNode[i].className = tabsItemsNode[i].className.replace(/on/, "");
                }

                ++menuIndex;
            }
        }


        var tabsContentNode = document.getElementById("tabsContent").childNodes;
        var tabsIndex = 0;

        for (var i = 0; i < tabsContentNode.length; ++i)
        {
            if (tabsContentNode[i].nodeName == "DIV" && tabsContentNode[i].className.search("tabsContent") != -1)
            {
                if (tabsIndex != itemIndex)
                {
                    tabsContentNode[i].style.display = "none";
                }
                else
                {
                    tabsContentNode[i].style.display = "block";
                    if (tabsIndex == 6) {
                        if ($('regularAccountContent').style.display != 'none') {
                            $('regularAccountContentIframe').src = 'showAccountContent.action';
                        }
                    } else if (tabsIndex == 5) {
                        MyXanthus.getMessages();
                    } else if (tabsIndex == 4) {
                        MyXanthus.getGroups();
                    } else if (tabsIndex == 3) {
                        MyXanthus.getCollaborators();
                    } else if (tabsIndex == 2) {
                        MyXanthus.getFriends();
                        //                    } else if (tabsIndex == 1) {
                        //                        MyXanthus.getPortfolio();
                    } else if (tabsIndex == 0) {
                        MyXanthus.getUpdates();
                    }
                }

                ++tabsIndex;
            }
        }
    }
    showHideTabBreakDown = function(itemIndex) {

        if (document.getElementById("tabs") == null) return;

        var tabsItemsNode = document.getElementById("tabs").childNodes;
        var menuIndex = 0;

        for (var i = 0; i < tabsItemsNode.length; ++i)
        {
            if (tabsItemsNode[i].nodeName == "LI")
            {
                if (menuIndex == itemIndex)
                    tabsItemsNode[i].className += ' on';
                else
                {
                    while (tabsItemsNode[i].className.search("on") != -1)
                        tabsItemsNode[i].className = tabsItemsNode[i].className.replace(/on/, "");
                }

                ++menuIndex;
            }
        }


        var tabsContentNode = document.getElementById("tabsContent").childNodes;
        var tabsIndex = 0;

        for (var i = 0; i < tabsContentNode.length; ++i)
        {
            if (tabsContentNode[i].nodeName == "DIV" && tabsContentNode[i].className.search("tabsContent") != -1)
            {
                if (tabsIndex != itemIndex)
                {
                    tabsContentNode[i].style.display = "none";
                }
                else
                {
                    tabsContentNode[i].style.display = "block";
                }

                ++tabsIndex;
            }
        }
    }
    showHideTabContests = function(itemIndex) {

        if (document.getElementById("tabs") == null) return;

        var tabsItemsNode = document.getElementById("tabs").childNodes;
        var menuIndex = 0;

        for (var i = 0; i < tabsItemsNode.length; ++i)
        {
            if (tabsItemsNode[i].nodeName == "LI")
            {
                if (menuIndex == itemIndex)
                    tabsItemsNode[i].className += ' on';
                else
                {
                    while (tabsItemsNode[i].className.search("on") != -1)
                        tabsItemsNode[i].className = tabsItemsNode[i].className.replace(/on/, "");
                }

                ++menuIndex;
            }
        }

        var tabsContentNode = document.getElementById("tabsContent").childNodes;
        var tabsIndex = 0;

        for (var i = 0; i < tabsContentNode.length; ++i)
        {
            if (tabsContentNode[i].nodeName == "DIV" && tabsContentNode[i].className.search("tabsContent") != -1)
            {
                if (tabsIndex != itemIndex)
                {
                    tabsContentNode[i].style.display = "none";
                }
                else
                {
                    tabsContentNode[i].style.display = "block";
                }

                ++tabsIndex;
            }
        }
    }

    showHideTabPublic = function(itemIndex) {

        if (document.getElementById("tabs") == null) return;

        var tabsItemsNode = document.getElementById("tabs").childNodes;
        var menuIndex = 0;

        for (var i = 0; i < tabsItemsNode.length; ++i)
        {
            if (tabsItemsNode[i].nodeName == "LI")
            {
                if (menuIndex == itemIndex)
                    tabsItemsNode[i].className += ' on';
                else
                {
                    while (tabsItemsNode[i].className.search("on") != -1)
                        tabsItemsNode[i].className = tabsItemsNode[i].className.replace(/on/, "");
                }

                ++menuIndex;
            }
        }


        var tabsContentNode = document.getElementById("tabsContent").childNodes;
        var tabsIndex = 0;

        for (var i = 0; i < tabsContentNode.length; ++i)
        {
            if (tabsContentNode[i].nodeName == "DIV" && tabsContentNode[i].className.search("tabsContent") != -1)
            {
                if (tabsIndex != itemIndex)
                {
                    tabsContentNode[i].style.display = "none";
                }
                else
                {
                    tabsContentNode[i].style.display = "block";
                    if (tabsIndex == 3) {
                        viewGroups();
                    } else if (tabsIndex == 2) {
                        viewCollaborators();
                    } else if (tabsIndex == 1) {
                        viewFriends();
                    }
                    //                    else if (tabsIndex == 2) {
                    //                        MyXanthus.getFriends();
                    ////                    } else if (tabsIndex == 1) {
                    ////                        MyXanthus.getPortfolio();
                    //                    } else if (tabsIndex == 0) {
                    //                        MyXanthus.getUpdates();
                    //                    }
                }

                ++tabsIndex;
            }
        }
    }

    //	showHideTab(0); // Init the default active tab ( 0 for the first tab , 1 for the second ...)

    getTabElement = function (itemIndex) {
        var tabsContentNode = document.getElementById("tabsContent").childNodes;
        var tabsIndex = 0;

        for (var i = 0; i < tabsContentNode.length; ++i)
        {
            if (tabsContentNode[i].nodeName == "DIV" && tabsContentNode[i].className.search("tabsContent") != -1)
            {
                if (tabsIndex == itemIndex)
                {
                    return tabsContentNode[i];
                }

                ++tabsIndex;
            }
        }
        return null;
    }

    // Move items between select lists

    addItem = function(sourceListId, destListId) {

        var sourceList = document.getElementById(sourceListId);
        var destList = document.getElementById(destListId);

        var itemIndex = 0;

        var listLength = sourceList.options.length;

        for (var i = 0; i < listLength; ++i)
        {
            if (sourceList.options[i - itemIndex].selected && !sourceList.options[i - itemIndex].disabled)
            {
                destList.appendChild(sourceList.options.item(i - itemIndex));
                ++itemIndex;
            }
        }

        sourceList.selectedIndex = -1;
        destList.selectedIndex = -1;
        sortList(sourceList);
        sortList(destList);
    }

    function compareOptionText(a, b) {
        return a.text != b.text ? a.text < b.text ? -1 : 1 : 0;
    }

    selectAllItems = function (destListId) {
        var destList = document.getElementById(destListId);
        for (var i = 0; i < destList.options.length; ++i)
        {
            destList.options[i].selected = true;
        }
    }

    function sortList(list) {
        var items = list.options.length;
        var tmpArray = new Array(items);
        for (i = 0; i < items; i++) {
            tmpArray[i] = new Option(list.options[i].text, list.options[i].value);
            tmpArray[i].disabled = list.options[i].disabled;
        }
        tmpArray.sort(compareOptionText);
        for (i = 0; i < items; i++) {
            list.options[i] = new Option(tmpArray[i].text, tmpArray[i].value);
            list.options[i].disabled = tmpArray[i].disabled;
            ;
        }
    }

    //-- Result box hover effect
    winnerBoxMouseover = function(currentBox) {
        currentBox.style.border = '2px solid #CCC';
        currentBox.style.margin = '0 1px';
        currentBox.style.height = '124px';
        currentBox.style.width = '170px';
    }

    winnerBoxMouseout = function(currentBox) {
        currentBox.style.border = 'none';
        currentBox.style.margin = '0 2px';
        currentBox.style.height = '128px';
        currentBox.style.width = '170px';
    }

    //-------------------------- Thumbs UP /DOWN
    chooseThumbsUp = function(thumbs1, thumbs2, carouselNodeId) {
        var status = DOM.getChildren(DOM.get(carouselNodeId))[7].innerHTML;

        if (status == 1) {
            document.getElementById(thumbs1).style.backgroundImage = "url(images/thumbs_up.png)";
            DOM.getChildren(DOM.get(carouselNodeId))[7].innerHTML = '0';
        } else {
            document.getElementById(thumbs1).style.backgroundImage = "url(images/thumbs_up_active.png)";
            document.getElementById(thumbs2).style.backgroundImage = "url(images/thumbs_down.png)";
            DOM.getChildren(DOM.get(carouselNodeId))[7].innerHTML = '1';
        }
    }

    chooseThumbsDown = function(thumbs1, thumbs2, carouselNodeId) {
        var status = DOM.getChildren(DOM.get(carouselNodeId))[7].innerHTML;

        if (status == -1) {
            document.getElementById(thumbs2).style.backgroundImage = "url(images/thumbs_down.png)";
            DOM.getChildren(DOM.get(carouselNodeId))[7].innerHTML = '0';
        } else {
            document.getElementById(thumbs1).style.backgroundImage = "url(images/thumbs_up.png)";
            document.getElementById(thumbs2).style.backgroundImage = "url(images/thumbs_down_active.png)";
            DOM.getChildren(DOM.get(carouselNodeId))[7].innerHTML = '-1';
        }
    }

    chooseFilter = function(filter) {
        var carouselNodesArray = DOM.getChildren("carousel-list");
        var count = 0;
        for (var i = 0; i < carouselNodesArray.length; ++i) {
            var status = DOM.getChildren(carouselNodesArray[i])[7].innerHTML;

            carouselNodesArray[i].style.display = 'none';
            if (filter == 'up' && status == 1) {
                carouselNodesArray[i].style.display = 'block';
                count ++;
            } else if (filter == 'down' && status == -1) {
                carouselNodesArray[i].style.display = 'block';
                count ++;
            } else if (filter == 'undecided' && status == 0) {
                carouselNodesArray[i].style.display = 'block';
                count ++;
            } else if (filter == 'all') {
                carouselNodesArray[i].style.display = 'block';
                count ++;
            }
        }

        // update the submissions count
        DOM.getFirstChild(DOM.get('submissionsNumber')).innerHTML = '' + count + ' submissions';
        DOM.get('submissionSize').value = count;
        carousel.carousel.scrollTo(0);
    }

    clearThumbs = function() {
        var carouselNodesArray = DOM.getChildren("carousel-list");
        for (var i = 0; i < carouselNodesArray.length; ++i) {
            document.getElementById('thumbsUp' + (i + 1)).style.backgroundImage = "url(images/thumbs_up.png)";
            document.getElementById('thumbsDown' + (i + 1)).style.backgroundImage = "url(images/thumbs_down.png)";
            DOM.getChildren(carouselNodesArray[i])[7].innerHTML = '0';
        }
        chooseFilter('all');
    }

    //-------------------------- Character counter

    countCharacters = function(fieldId, remainingChar, maxChar) {

        var myField = document.getElementById(fieldId);

        if (myField.value.length > maxChar)
            myField.value = myField.value.substring(0, maxChar);
        else
            document.getElementById(remainingChar).innerHTML = maxChar - myField.value.length;
    }


    //------------------------------------------------------------------ carousel
    carousel = new Carousel("mycarousel",
    { prevElement:"prev-arrow", nextElement:"next-arrow" });

}

/*-------- Carousel ----------------------------------------*/

var carousel;

var Carousel = function(carouselElementID, carouselCfg) {
    this.init(carouselElementID, carouselCfg);
};

Carousel.prototype = {
    init: function(id, cfg) {
        var config = {
            numVisible:        5,
            animationSpeed:    0.15,
            scrollInc:         1,
            navMargin:         20,
            size:              12,
            prevButtonStateHandler: this.handlePrevButtonState,
            nextButtonStateHandler: this.handleNextButtonState
        };

        for (var key in cfg) {
            if (!cfg.hasOwnProperty(key)) {
                continue;
            }
            config[key] = cfg[key];
        }

        this.carousel = new YAHOO.extension.Carousel(id, config);
    },

    handlePrevButtonState: function(type, args) {
        var enabling = args[0];
        var leftImage = args[1];
        if (!leftImage)return;
        if (enabling) {
            leftImage.src = "images/arrow-prev.png";
        } else {
            leftImage.src = "images/arrow-prev.png";
        }
    },

    handleNextButtonState: function(type, args) {
        var enabling = args[0];
        var rightImage = args[1];
        if (!rightImage)return;
        if (enabling) {
            rightImage.src = "images/arrow-next.png";
        } else {
            rightImage.src = "images/arrow-next.png";
        }
    }
};


YAHOO.util.Event.addListener(window, 'load', init);

function executeSearch(page) {
    var sUrl = "ajaxSearch.action?"

    if (document.getElementById('search_type')) {
        sUrl += "&searchType=" + document.getElementById('search_type').value;
    }

    if (document.getElementById('first_name')) {
        sUrl += "&searchText=" + document.getElementById('first_name').value;
    }

    if (!page) {
        page = 1;
    }

    sUrl += "&pageNumber=" + page;

    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl + "&preventCache=" + new Date().getTime(), {
        success    : function(response) {
            document.getElementById('search_result_container').innerHTML = response.responseText;
        },

        failure : function(response) {
            document.getElementById('search_result_container').innerHTML = 'There was an error while performing search.';
        }
    });

    return false;
}

function activateTab(itemIndex) {
    hidePageMessages();

    if (document.getElementById("tabs") == null) return;

    var tabsItemsNode = document.getElementById("tabs").childNodes;
    var menuIndex = 0;

    for (var i = 0; i < tabsItemsNode.length; ++i)
    {
        if (tabsItemsNode[i].nodeName == "LI")
        {
            if (menuIndex == itemIndex)
                tabsItemsNode[i].className += ' on';
            else
            {
                while (tabsItemsNode[i].className.search("on") != -1)
                    tabsItemsNode[i].className = tabsItemsNode[i].className.replace(/on/, "");
            }

            ++menuIndex;
        }
    }

}

function viewPortfolio() {
    //	activateTab(0);

    var sUrl = "ajaxViewPortfolio.action?preventCache=" + new Date().getTime();
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            setAjaxContent('portfolioTabContent', response.responseText);
        },

        failure : function(response) {
            document.getElementById('portfolioTabContent').innerHTML = 'There was an error while performing portfolio retrieval.';
        }
    });

    return false;
}

function viewFriends() {
    //	activateTab(1);

    var sUrl = "ajaxViewFriends.action?preventCache=" + new Date().getTime();
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            setAjaxContent('friendsTabContent', response.responseText);
        },

        failure : function(response) {
            document.getElementById('friendsTabContent').innerHTML = 'There was an error while performing friends retrieval.';
        }
    });

    return false;
}

function viewCollaborators() {
    //	activateTab(2);

    var sUrl = "ajaxViewCollaborators.action?preventCache=" + new Date().getTime();
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            setAjaxContent('collaboratorsTabContent', response.responseText);
        },

        failure : function(response) {
            document.getElementById('collaboratorsTabContent').innerHTML = 'There was an error while performing collaborators retrieval.';
        }
    });

    return false;
}

function viewGroups() {
    //	activateTab(3);

    var sUrl = "ajaxViewGroups.action?preventCache=" + new Date().getTime();
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            setAjaxContent('groupsTabContent', response.responseText);
        },

        failure : function(response) {
            document.getElementById('groupsTabContent').innerHTML = 'There was an error while performing groups retrieval.';
        }
    });

    return false;
}

function viewGroupMessageBoard() {
    activateTab(0);

    var sUrl = "ajaxViewGroupMessageBoard.action?preventCache=" + new Date().getTime();
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            setAjaxContent('tabsContent', response.responseText);
        },

        failure : function(response) {
            document.getElementById('tabsContent').innerHTML = 'There was an error while performing group messages retrieval.';
        }
    });

    return false;
}

function viewGroupUpdates() {
    activateTab(1);

    var sUrl = "ajaxViewGroupUpdates.action?preventCache=" + new Date().getTime();
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            setAjaxContent('tabsContent', response.responseText);
        },

        failure : function(response) {
            document.getElementById('tabsContent').innerHTML = 'There was an error while performing group updates retrieval.';
        }
    });

    return false;
}

function viewGroupMembers() {
    activateTab(2);

    var sUrl = "ajaxViewGroupMembers.action?preventCache=" + new Date().getTime();
    YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            setAjaxContent('tabsContent', response.responseText);
        },

        failure : function(response) {
            document.getElementById('tabsContent').innerHTML = 'There was an error while performing group members retrieval.';
        }
    });

    return false;
}

function viewGroupFollowers() {
    activateTab(3);

    var sUrl = "ajaxViewGroupFollowers.action?preventCache=" + new Date().getTime();
    YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            setAjaxContent('tabsContent', response.responseText);
        },

        failure : function(response) {
            document.getElementById('tabsContent').innerHTML = 'There was an error while performing group followers retrieval.';
        }
    });

    return false;
}

function addAsFriend() {
    hidePageMessages();
    var msg = document.getElementById('add_friend_message').value;
    var sUrl = "ajaxAddAsFriend.action?message=" + msg;
    var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            updatePageMessages(eval("(" + response.responseText + ")"));
            hidePopup3();
        },

        failure : function(response) {
            document.getElementById('tabsContent').innerHTML = 'There was an error while sending invitations.';
        }
    });
}


function sendMessageToFriend() {
    hidePageMessages();
    var msg = document.getElementById('send_friend_message').value;
    var subject = document.getElementById('send_friend_subject').value;
    var sUrl = "ajaxSendMessageToFriend.action?message=" + msg + "&subject=" + subject;
    var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            updatePageMessages(eval("(" + response.responseText + ")"));
            hidePopup3();
        },

        failure : function(response) {
            document.getElementById('tabsContent').innerHTML = 'There was an error while sending group request.';
        }
    });
}

function sendMessageToGroup() {
    hidePageMessages();
    var msg = document.getElementById('send_group_message').value;
    var subject = document.getElementById('send_group_subject').value;
    var sUrl = "ajaxSendMessageToGroup.action?message=" + msg + "&subject=" + subject;
    var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            updatePageMessages(eval("(" + response.responseText + ")"));
            hidePopup3();
        },

        failure : function(response) {
            document.getElementById('tabsContent').innerHTML = 'There was an error while sending group message.';
        }
    });
}

function joinCurrentGroup() {
    hidePageMessages();
    var msg = document.getElementById('join_group_message').value;
    var sUrl = "ajaxJoinGroup.action?message=" + msg;
    var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            var json = eval("(" + response.responseText + ")");
            updatePageMessages(json);
            if (json.success) {
                document.getElementById('joinGroupButton').style.display = 'none';
            }
            hidePopup3();
        },

        failure : function(response) {
            document.getElementById('tabsContent').innerHTML = 'There was an error while sending message.';
        }
    });
}

function hidePageMessages() {
    document.getElementById("pageMessages").style.display = 'none';
}

function removeFromGroup(userId) {
    var sUrl = "ajaxRemoveUserFromGroup.action?memberId=" + userId;
    YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            hidePopup3();
            setAjaxContent('tabsContent', response.responseText);
        },

        failure : function(response) {
            document.getElementById('tabsContent').innerHTML = 'There was an error while removing user from group.';
        }
    });
}

function followGroup(userId) {
    var sUrl = "ajaxFollowGroup.action";
    YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            var json = eval("(" + response.responseText + ")");
            updatePageMessages(json);
            if (json.success) {
                document.getElementById('followGroupButton').style.display = 'none';
            }
        },

        failure : function(response) {
            document.getElementById('tabsContent').innerHTML = 'There was an error while removing user from group.';
        }
    });
}

function updatePageMessages(response) {
    if (response.success) {
        document.getElementById("pageMessages").innerHTML = '<span class="msgInfo">' + response.msg + '</span>';
    } else {
        document.getElementById("pageMessages").innerHTML = '<span class="msgError">' + response.msg + '</span>';
    }

    document.getElementById("pageMessages").style.display = 'block';
}

function sendMessageToContacts(formId) {
    hidePageMessages();
    var sUrl = "sendMessageToContacts.action";
    YAHOO.util.Connect.setForm(document.getElementById(formId));
    YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            var json = eval("(" + response.responseText + ")");
            if (json.success) {
                hidePopup3();
                updatePageMessages(json);
            } else {
                alert(json.msg);
            }
        },
        failure : function(response) {
            alert('There was an error while sending message, If you continue to experience this, please contact support.');
        }
    });
}

function sendAdminMessage(formObject) {
    hidePageMessages();
    var sUrl = "sendMessageByFilter.action";
    YAHOO.util.Connect.setForm(formObject);
    YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            var json = eval("(" + response.responseText + ")");
            updatePageMessages(json);
        },
        failure : function(response) {
            alert('There was an error while sending message, If you continue to experience this, please contact support.');
        }
    });
}

function retrieveMemberEmails(formObject, targetElement, fullInfo) {
    var sUrl = "getUsersToSend.action";
    YAHOO.util.Connect.setForm(formObject);
    YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            var json = eval("(" + response.responseText + ")");
            var users = json.users;
            var userList = "";
            for (var i = 0; i < users.length; i++) {
                if (userList.length > 0) userList += fullInfo ? "<br/>" : ",\r\n";
                if (!fullInfo) {
                    userList += users[i].firstName + "<" + users[i].email + ">";
                } else {
                    userList += users[i].firstName + " " + users[i].lastName + "(" + users[i].city + " " + users[i].province + " " + users[i].country + ")";
                }
            }
            targetElement.innerHTML = userList;
        },
        failure : function() {
            alert('There was an error while sending message, If you continue to experience this, please contact support.');
        }
    });
}


// refreshes the displayed image with the one uploaded to the session
function refreshGroupPhoto() {
    var sUrl = "ajaxDisplayGroupPhoto.action";
    YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            setAjaxContent('group_image_container', response.responseText);
        },
        failure : function(response) {
            setAjaxContent('group_image_container', 'There was an error loading the photo.');
        }
    });
}

function updateCommunityProfile(checkbox) {
    hidePageMessages();
    checkbox.disabled = true;
    var sUrl = "updateCommunityProfile.action?publiclyAvailable=" + checkbox.checked;
    YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            checkbox.disabled = false;
        },
        failure : function(response) {
            checkbox.disabled = false;
        }
    });
}

function updateUserStatus() {
    document.getElementById('pageMessages').innerHTML = '<span class="msgInfo">Updating status...</span>';
    var status = document.getElementById('user_status').value;
    var sUrl = "updateUserStatus.action?userStatus=" + status;
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            document.getElementById('pageMessages').innerHTML = '<span class="msgInfo">Status was updated</span>';
            getTabElement(0).innerHTML = response.responseText;
        },

        failure : function(response) {
            getTabElement(0).innerHTML = 'There was an error while sending update status request.';
        }
    });
}

function uploadGroupPhoto(formObject) {
    // the second argument is true to indicate file upload.
    YAHOO.util.Connect.setForm(formObject, true);
    YAHOO.util.Connect.asyncRequest('POST', 'uploadGroupPhoto.action', {
        upload: function(response) {
            document.getElementById("group_image").value = '';
            refreshGroupPhoto();
        },

        failure : function(response) {
            document.getElementById('pageMessages').innerHTML = '<span class="msgError">There was an error while uploading the photo.</span>';
        }
    });
}

function deleteGroupImage() {
    var sUrl = "ajaxDeleteGroupPhoto.action";
    YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            setAjaxContent('group_image_container', response.responseText);
        },
        failure : function(response) {
            setAjaxContent('group_image_container', 'There was an error loading the photo.');
        }
    });
}

function createGroup(formObject) {
    hidePageMessages();
    var sUrl = "ajaxCreateGroup.action";
    YAHOO.util.Connect.setForm(formObject);
    YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            var json = eval("(" + response.responseText + ")");
            if (json.success) {
                document.location.href = "inviteToGroup.action?groupId=" + json.groupId;
            } else {
                updatePageMessages(json);
            }
        },
        failure : function(response) {
            document.getElementById('pageMessages').innerHTML = '<span class="msgError">There was an error while creating the group.</span>';
        }
    });
}

function editGroup(formObject) {
    hidePageMessages();
    var sUrl = "ajaxEditGroup.action";
    YAHOO.util.Connect.setForm(formObject);
    YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            var json = eval("(" + response.responseText + ")");
            if (json.success) {
                document.location.href = "viewGroupProfile.action?groupId=" + json.groupId;
            } else {
                updatePageMessages(json);
            }
        },
        failure : function(response) {
            document.getElementById('pageMessages').innerHTML = '<span class="msgError">There was an error while updating the group.</span>';
        }
    });
}

function purgeGroup() {
    var sUrl = "ajaxRemoveGroup.action";
    YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            var json = eval("(" + response.responseText + ")");
            updatePageMessages(json);
            if (json.success) {
                document.location.href = "viewMyProfile.action";
            }
        },

        failure : function(response) {
            document.getElementById('tabsContent').innerHTML = 'There was an error while removing user from group.';
        }
    });
}

function setAjaxContent(divId, html) {
    $(divId).update(html);
}

function clickAHref(theLink) {
    var loadLink = document.getElementById(theLink);

    if (document.dispatchEvent) { // W3C
        var oEvent = document.createEvent("MouseEvents");
        oEvent.initMouseEvent("click", true, true, window, 1, 1, 1, 1, 1, false, false, false, false, 0, loadLink);
        loadLink.dispatchEvent(oEvent);
    } else if (document.fireEvent) { // IE
        loadLink.fireEvent("onclick");
    }
}

// format a given numeric value as ##,##0.00
// if the number terminates with .00, remove this also
// nStr - numeric value; can be number or string
function formatCurrency(nStr)
{
    nStr += '';
    nStr = nStr.replace("$", "");
    nStr = parseFloat(nStr).toFixed(2);
    x = nStr.split('.');
    x1 = x[0];
    x2 = x[1] == '00' ? '' : '.' + x[1];
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

var progressBarHandler;
var conversionId;

function showVideoContent(path, videoName, divName, shareable, width, height) {
    var targetDiv = document.getElementById(divName);

    try {
        if (!progressBarHandler) {
            targetDiv.innerHTML = '<span style="font-size:13px;">Converting video:</span>&nbsp;<span id="ajaxVideoConversionStatus"></span>'
                    + '<br/><span id="timeElapsed" style="font-size:10px;"></span>'
                    + '<br/><span id="rate" style="font-size:10px;"></span>';
            progressBarHandler = new JS_BRAMUS.jsProgressBar(
                    $('ajaxVideoConversionStatus'),
                    1,
            {

                barImage    : Array(
                        path + '/images/bramus/percentImage_back4.png',
                        path + '/images/bramus/percentImage_back3.png',
                        path + '/images/bramus/percentImage_back2.png',
                        path + '/images/bramus/percentImage_back1.png'
                        )
            }
                    );
            progressBarHandler.setPercentage('1');
        }
    } catch(e) {
        progressBarHandler = null;
    }

    var sUrl = conversionId
            ? "ajaxVideoConversionStatus.action?conversionId=" + conversionId
            : "ajaxVideoConversionStatus.action?videoContent=" + videoName;
    YAHOO.util.Connect.asyncRequest('GET', sUrl + "&preventCache=" + new Date().getTime(), {
        success    : function(response) {
            try {
                var jsonResponse = eval("(" + response.responseText + ")");
                if ('' + jsonResponse.success == 'true') {
                    if ('' + jsonResponse.next == 'false') {
                        if (!conversionId) showVideoContent1(path, videoName, divName, shareable, width, height);
                        else {
                            progressBarHandler.setPercentage('100');
                            if (width && height) {
                                setTimeout("showVideoContent1('" + path + "', '" + videoName + "', '" + divName + "', '"
                                        + shareable
                                        + "', '" + width + "', '" + height + "')",
                                        3000);
                            } else {
                                setTimeout("showVideoContent1('" + path + "', '" + videoName + "', '" + divName
                                        + "', '" + shareable + "')", 3000);
                            }
                        }
                    } else {
                        if (jsonResponse.progress) {
                            if (progressBarHandler) progressBarHandler.setPercentage('' + jsonResponse.progress);
                            $('timeElapsed').update(jsonResponse.elapsedTime);
                            var rate = '';
                            if (jsonResponse.rate < 1024) {
                                rate = jsonResponse.rate + "b/s";
                            } else if (jsonResponse.rate < 1024 * 1024) {
                                rate = (jsonResponse.rate / 1024).toFixed(2) + "Kb/s";
                            } else {
                                rate = (jsonResponse.rate / (1024 * 1024)).toFixed(2) + "Mb/s";
                            }
                            $('rate').update("Conversion rate: " + (rate) + "." + jsonResponse.eta);
                        } else {
                            if (progressBarHandler) progressBarHandler.setPercentage('1');
                        }
                        conversionId = jsonResponse.conversionId;
                        if (width && height) {
                            setTimeout("showVideoContent('" + path + "', '" + videoName + "', '" + divName + "', '"
                                    + shareable
                                    + "', '" + width + "', '" + height + "')",
                                    1000);
                        } else {
                            setTimeout("showVideoContent('" + path + "', '" + videoName + "', '" + divName
                                    + "', '" + shareable + "')", 1000);
                        }
                    }
                } else {
                    targetDiv.innerHTML = 'Cannot convert the file. Back to upload page and try again. If problem persists, inform site administrators.';
                }
            } catch(e) {
                if (width && height) {
                    setTimeout("showVideoContent('" + path + "', '" + videoName + "', '" + divName + "', '"
                            + shareable
                            + "', '" + width + "', '" + height + "')",
                            5000);
                } else {
                    setTimeout("showVideoContent('" + path + "', '" + videoName + "', '" + divName
                            + "', '" + shareable + "')", 5000);
                }
            }
        },

        failure : function(response) {
            var jsonResponse = eval("(" + response.responseText + ")");
            targetDiv.innerHTML = jsonResponse.msg;
        },
        timeout: 30000
    });
}

function showVideoContent1(path, videoName, divName, shareable, width, height) {
    if (videoName == null || videoName == 'null' || videoName == '') {
        return;
    }

    if (!width) {
        width = 490;
    }
    if (!height) {
        height = 366;
    }

    var flashvars = {
        vPath:        'submissionContent?name=' + videoName + ';' + new Date().getTime(),
        videoInfo:    'submissionContent?xml=' + videoName + ';' + new Date().getTime() + ";HD",
        mailerPath: 'mail.action',
        preloader: 'preloader.swf',
        shareable: shareable ? shareable : 'yes'
    };
    var params = {
        allowfullscreen:    'true',
        wmode:                'transparent'
    };
    var attributes = {};
    swfobject.embedSWF(path + '/tongal_flash_player.swf', divName, '' + width, '' + height, '9', false, flashvars, params, attributes);
}


function addSubmission(submissionId) {
    var clickable = document.getElementById('submissionC' + submissionId);
    if (clickable) {
        clickable.style.display = 'none';
    }
    var nonClickable = document.getElementById('submissionNC' + submissionId);
    if (nonClickable) {
        nonClickable.style.display = 'block';
    }
}


function removeSubmission(submissionId) {
    var clickable = document.getElementById('submissionC' + submissionId);
    if (clickable) {
        clickable.style.display = 'block';
    }
    var nonClickable = document.getElementById('submissionNC' + submissionId);
    if (nonClickable) {
        nonClickable.style.display = 'none';
    }
}

// standard ajax retrieval js
// url: url to do GET from
// fn:  callback method after GET completes
function retrieveURL(url, elementToUpdate) {
    if (window.XMLHttpRequest) { // Non-IE browsers
        var req = new XMLHttpRequest();
        req.onreadystatechange = function() {
            processStateChange(elementToUpdate, req);
        };
        try {
            req.open("GET", url + "&preventCache=" + new Date().getTime(), true);
        } catch (e) {
            alert(e);
        }
        req.send(null);

    } else if (window.ActiveXObject) { // IE
        var req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() {
                processStateChange(elementToUpdate, req);
            };
            req.open("GET", url + "&preventCache=" + new Date().getTime(), true);
            req.send();
        }
    }
}

//The XMLHttpRequest/Microsoft.XMLHTTP object calls this method once the
//server has completed sending back its response.
//elementToUpdate: name of component to update
//req: XMLHttpRequest object
function processStateChange(elementToUpdate, req) {
    if (req.readyState == 4) { // Complete
        if (req.status == 200) { // OK response
            document.getElementById(elementToUpdate).innerHTML = req.responseText;
        } else {
            alert("Problem: " + req.statusText);
        }
    }
}
// simulate AJAX for file upload using a hidden iFrame
// http://viralpatel.net/blogs/2008/11/ajax-style-file-uploading-using-hidden-iframe.html
// form - form to be submitted
// action_url - URL to post form to
// div_id - the div id of the component to copy the result to
function fileUpload(form, action_url, div_id)
{
    // Create the iframe...
    var iframe = document.createElement("iframe");
    iframe.setAttribute("id", "upload_iframe");
    iframe.setAttribute("name", "upload_iframe");
    iframe.setAttribute("width", "0");
    iframe.setAttribute("height", "0");
    iframe.setAttribute("border", "0");
    iframe.setAttribute("style", "width: 0; height: 0; border: none;");

    // Add to document...
    form.parentNode.appendChild(iframe);
    window.frames['upload_iframe'].name = "upload_iframe";

    iframeId = document.getElementById("upload_iframe");

    // Add event...
    var eventHandler = function() {

        if (iframeId.detachEvent)
            iframeId.detachEvent("onload", eventHandler);
        else
            iframeId.removeEventListener("load", eventHandler, false);

        // Message from server...
        if (iframeId.contentDocument) {
            content = iframeId.contentDocument.body.innerHTML;
        } else if (iframeId.contentWindow) {
            content = iframeId.contentWindow.document.body.innerHTML;
        } else if (iframeId.document) {
            content = iframeId.document.body.innerHTML;
        }

        document.getElementById(div_id).innerHTML = content;

        // Del the iframe...
        setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
    }

    if (iframeId.addEventListener)
        iframeId.addEventListener("load", eventHandler, true);
    if (iframeId.attachEvent)
        iframeId.attachEvent("onload", eventHandler);

    // save original values
    var oldAction = form.getAttribute("action");
    var oldTarget = form.getAttribute("target");

    // Set properties of form...
    form.setAttribute("target", "upload_iframe");
    form.setAttribute("action", action_url);
    form.setAttribute("method", "post");
    form.setAttribute("enctype", "multipart/form-data");
    form.setAttribute("encoding", "multipart/form-data");

    // Submit the form...
    form.submit();

    // set back to original values
    form.setAttribute("action", oldAction);
    form.setAttribute("target", oldTarget);
}

/**
 * Loads the user's contacts for auto complete feature for message sending popup which appears on clicking
 * "New Message" link on "Messages" tab on MyXanthus.
 */
function loadContacts() {
    var list = document.getElementById("contacts");
    var listLength = list.options.length;
    var contactsList = [];
    contactsList.length = listLength;
    for (var i = 0; i < contactsList.length; ++i) {
        contactsList[i] = list.options[i].innerHTML + " (" + list.options[i].value + ")";
    }


    var contactsListDS = new YAHOO.util.LocalDataSource(contactsList);

    var contactsListAutoComp = new YAHOO.widget.AutoComplete("to", "toAutoCompleteContainer", contactsListDS);
    contactsListAutoComp.applyLocalFilter = true;
    contactsListAutoComp.forceSelection = true;
    contactsListAutoComp.queryMatchContains = true;
    contactsListAutoComp.delimChar = [",", ";", " "];
}


function showAdvancedUploadDialog(fileType) {
    return window.open("uploadDialog.action?type=" + fileType,
            null, 'screenX=200;screenY=200;dialogWidth=900px;dialogHeight=640px;resizable=yes;help=no;unadorned=yes;location=no;menubar=no;toolbar=no;center:yes');
}

function addToTop10PredictionSubmission(id, index, textContent, imageContent, videoContent, contextPath) {
    DOM.get('leftArea').style.display = 'block';

    var carouselIdOfNodeBeingAdded = "mycarousel-item-" + index;
    var curElementOnCarousel = DOM.get(carouselIdOfNodeBeingAdded);

    var newTitle = DOM.getFirstChild(DOM.getChildren(curElementOnCarousel)[1]).innerHTML;
    var newAuthor = DOM.getChildren(curElementOnCarousel)[2].innerHTML;

    DOM.getChildren(DOM.get("videoTitle"))[0].innerHTML = newTitle;
    DOM.getChildren(DOM.get("videoTitle"))[1].innerHTML = newAuthor;
    DOM.getChildren(DOM.get("mainVideo"))[0].style.display = DOM.getChildren(curElementOnCarousel)[5].style.display;
    DOM.getChildren(DOM.get("mainVideo"))[1].style.display = DOM.getChildren(curElementOnCarousel)[6].style.display;
    DOM.getChildren(DOM.get("mainVideo"))[2].innerHTML = "item-" + index;

    if (textContent != '') {
        DOM.getChildren(DOM.get("votingPitchVideo"))[0].innerHTML = textContent;
        DOM.getChildren(DOM.get("votingPitchVideo"))[0].style.display = "block";
        DOM.getChildren(DOM.get("votingPitchVideo"))[1].style.display = "none";
        DOM.getChildren(DOM.get("votingPitchVideo"))[2].style.display = "none";
    } else if (imageContent != '') {
        DOM.getChildren(DOM.get("votingPitchVideo"))[1].innerHTML = '<img src="imageContent?name=' + imageContent + '&width=400&height=300&default=images/placeholder_400x300.png" />';
        DOM.getChildren(DOM.get("votingPitchVideo"))[0].style.display = "none";
        DOM.getChildren(DOM.get("votingPitchVideo"))[1].style.display = "block";
        DOM.getChildren(DOM.get("votingPitchVideo"))[2].style.display = "none";
    } else if (videoContent != '') {
        showVideoContent(contextPath, videoContent, 'mainPlayer', 'yes');
        DOM.getChildren(DOM.get("votingPitchVideo"))[0].style.display = "none";
        DOM.getChildren(DOM.get("votingPitchVideo"))[1].style.display = "none";
        DOM.getChildren(DOM.get("votingPitchVideo"))[2].style.display = "block";
    }
    DOM.getChildren(DOM.get("votingPitchVideo"))[3].innerHTML =
    '<p class="videoTitle">'
            + '    <br/>'
            + '    <div style="font:large;"><b style="color:white;float:left;">NEW!&nbsp;</b><a href="submissionDetail.action?id=' + id + '">Discuss&Suggest</a></div>'
            + '    <br/>'
            + '</p>';
}

function updateArea(discussionArea, t, i, ft) {
    var callback = {
        success: function(response) {
            $(discussionArea + 'Indicator').hide();
            setAjaxContent(discussionArea, response.responseText);
        },
        failure: function(response) {
            document.getElementById('pageMessages').innerHTML = '<span class="msgError">There was an error while procesing request. Try to refresh the page.</span>';
        }
    }
    $(discussionArea + 'Indicator').show();
    YAHOO.util.Connect.asyncRequest('GET', "viewDiscussionThread.action?&discussionArea=" + discussionArea + "&t=" + t + "&i=" + i + "&ft=" + ft, callback);
    return false;
}

function replyTo(feedback, discussionArea, t, i, ft, userId) {
    if ('' == userId) {
        return notLoggedMessage('post', ft + 's');
    }
    var callback = {
        success: function(o) {
            showPopup3(o.responseText);
            $('feedback_text' + discussionArea).focus();
        },
        failure: function(o) {
            document.getElementById('pageMessages').innerHTML = '<span class="msgError">There was an error while procesing request.</span>';
        }
    }
    YAHOO.util.Connect.asyncRequest('GET', 'commentReplyForm.action?fi=' + feedback + "&discussionArea=" + discussionArea + "&t=" + t + "&i=" + i + "&ft=" + ft, callback);
    return false;
}

function escapeChar(c)
{
    if(c == "\"" || c == "\\") return "\\" + c;
    else if (c == "\b") return "\\b";
    else if (c == "\f") return "\\f";
    else if (c == "\n") return "\\n";
    else if (c == "\r") return "\\r";
    else if (c == "\t") return "\\t";
    var hex = c.charCodeAt(0).toString(16);
    if(hex.length == 1) return "\\u000" + hex;
    else if(hex.length == 2) return "\\u00" + hex;
    else if(hex.length == 3) return "\\u0" + hex;
    else return "\\u" + hex;
};


/* encode a string into JSON format */

function escapeString(s)
{
    /* The following should suffice but Safari's regex is b0rken
       (doesn't support callback substitutions)
       return "\"" + s.replace(/([^\u0020-\u007f]|[\\\"])/g,
       escapeJSONChar) + "\"";
    */

    /* Rather inefficient way to do it */
    var parts = s.split("");
    for(var i=0; i < parts.length; i++) {
	var c =parts[i];
	if(c == '"' ||
	   c == '\\' ||
	   c.charCodeAt(0) < 32 ||
	   c.charCodeAt(0) >= 128)
	    parts[i] = escapeChar(parts[i]);
    }
    return parts.join("");
};


function postReply(reason, id, discussionArea, t, i, ft) {
    if (reason == '') {
        alert("Please, provide the message.");
        return;
    }
    var sUrl = "postCommentReply.action?comment=" + escapeString(reason) + "&fi=" + id + "&discussionArea=" + discussionArea + "&t=" + t + "&i=" + i + "&ft=" + ft;
    YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            setAjaxContent(discussionArea, response.responseText);
            hidePopup3();
        },
        failure : function() {
            alert('There was an error while confirming your action. If you continue to experience this, please contact support.');
        }
    });
}

function commentVote(commentId, commentValue, updateArea, feedbackType, userId) {
    if ('' == userId) {
        return notLoggedMessage('vote for', feedbackType + 's');
    }
    var sUrl = "feedbackVote.action?i=" + commentId + "&comment=" + escapeString(commentValue) + "&ft=" + feedbackType;
    sUrl = sUrl.replace("+", "%2B");
    YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            setAjaxContent(updateArea, response.responseText);
        },

        failure : function() {
            alert("Request to server has failed. Please, try again later.");
        }
    });

    return false;
}

function replySuggestion(id, accept, t, i, ft, userId) {
    var action = (accept ? "accept" : "reject");

    if ('' == userId) {
        return notLoggedMessage(action, ft + 's');
    }

    var callback = {
        success: function(o) {
            showPopup3(o.responseText);
        },
        failure: function(o) {
            document.getElementById('pageMessages').innerHTML = '<span class="msgError">There was an error while procesing request.</span>';
        }
    }
    YAHOO.util.Connect.asyncRequest('GET', 'askConfirmationSuggestion.action?t=' + action + "&i=" + id + "&ft=" + ft, callback);
    return false;
}

function confirmSuggestionAction(reason, id, saction) {
    if (reason == '') {
        alert("Please, provide the reason.");
        return;
    }
    var sUrl = "confirmSuggestionAction.action?comment=" + escapeString(reason) + "&i=" + id + "&t=" + saction + "&discussionArea=suggestionsArea";
    YAHOO.util.Connect.asyncRequest('GET', sUrl, {
        success    : function(response) {
            setAjaxContent('suggestionsArea', response.responseText);
            hidePopup3();
        },
        failure : function(response) {
            alert('There was an error while confirming your action. If you continue to experience this, please contact support.');
        }
    });
}

function notLoggedMessage(action, feedback) {
    if (confirm("To " + action + " " + feedback + " you need to log in.\r\nIf you don't have account on our site press [OK] to register\r\nOthwerwise click [Cancel] and log in.")) {
        showQuickRegistrationPopup();
        return true;
    } else {
        return false;
    }
}

function updateSubscriptions(formObject, element) {
    var sUrl = "updateNotificationsSubscriptions.action" + "?preventCache=" + new Date().getTime();
    YAHOO.util.Connect.setForm(formObject);
    $(element + "_content").update('');
    $(element + "Indicator").show();
    YAHOO.util.Connect.asyncRequest('POST', sUrl, {
        success    : function(response) {
            $(element + "_content").update(response.responseText);
            $(element + "Indicator").hide();
            showHideMessageSection($('expandNotifications'), 'userNotificationsView');
        },
        failure : function(response) {
            document.getElementById('pageMessages').innerHTML = '<span class="msgError">There was an error while updating subsriptions.</span>';
        }
    });
}


function deleteSubmission(id, contestId, contestTitle, removable) {
    var sUrl = "removeSubmission.action" + "?id=" + id + "&contestId=" + contestId + "&removable=" + removable + "&preventCache=" + new Date().getTime()+ "&contestTitle=" + contestTitle ;
    if (confirm('Are you sure you want to remove this submission?\r\nThis operation can be undone only by the administrator!')) {
        YAHOO.util.Connect.asyncRequest('GET', sUrl, {
            success    : function(response) {
                var result = eval("(" + response.responseText + ")");
                if (result.removed) {
                    alert("The submission has been removed.");
                    changePhaseTypeClick();
                    onclick_ShowSubmission(result.id, result.contestId, result.title, result.contestTitle,
                            result.textContent, result.imageContent, result.videoContent,
                            result.shareable, result.removable, result.reason, result.currentUserAdmin);
                } else {
                    alert("The submission has NOT been removed: " + result.errorMessage + ".\r\n Sometimes refreshing the page and repeating the operation may help.");
                }
            },
            failure : function(response) {
                document.getElementById('pageMessages').innerHTML = '<span class="msgError">There was an error while updating subsriptions.</span>';
            }
        });
    }
    return false;
}

function restoreSubmission(id, contestId, contestTitle, removable) {
    var sUrl = "restoreSubmission.action" + "?id=" + id + "&contestId=" + contestId + "&removable=" + removable + "&preventCache=" + new Date().getTime()+ "&contestTitle=" + contestTitle ;
    if (confirm('Are you sure you want to restore this submission?')) {
        YAHOO.util.Connect.asyncRequest('GET', sUrl, {
            success    : function(response) {
                var result = eval("(" + response.responseText + ")");
                if (result.restored) {
                    alert("The submission has been restored.");
                    changePhaseTypeClick();
                    onclick_ShowSubmission(result.id, result.contestId, result.title, result.contestTitle,
                            result.textContent, result.imageContent, result.videoContent,
                            result.shareable, result.removable, result.reason, result.currentUserAdmin);
                } else {
                    alert("The submission has NOT been restored: " + result.errorMessage + ".\r\n Sometimes refreshing the page and repeating the operation may help.");
                }
            },
            failure : function(response) {
                document.getElementById('pageMessages').innerHTML = '<span class="msgError">There was an error while updating subsriptions.</span>';
            }
        });
    }
    return false;
}


function onclick_ShowSubmission(id, contestId, title, contestTitle, textContent, imageContent, videoContent, shareable, removable, reason, isadmin) {
    var content = '';

    if (removable && reason == '') {
        content += '<a href="#" class="button6" style="float:right;" onclick="return deleteSubmission(' + id + ', ' + contestId + ', \'' + contestTitle.replace('\'', '\\\'') + '\', \'' + removable + '\')">Remove</a>';
    }

    if (reason != '') {
        if (isadmin) {
            content += '<a href="#" class="button6" style="float:right;" onclick="return restoreSubmission(' + id + ', ' + contestId + ', \'' + contestTitle.replace('\'', '\\\'') + '\', \'' + removable + '\')">Restore</a>';
        }
        content += '<div style="font-weight:bold;">Submission is rejected: ' + reason + '</div><br/><br/>';
    }

    content += title
            + '<a href="contestDetail.action?id=' + contestId + '" class="contestTitle">' + contestTitle + '</a>';
    
    if (textContent != null && textContent != '') {
        content += '<div class="video">'
                + '<p>' + textContent + '</p>'
                + '</div>';
    } else if (imageContent != null && imageContent != '') {
        content += '<div class="video">'
                + '<img class="pitchImage" src="submissionContent?name=' + imageContent + '" />'
                + '</div>';
        content +=
          '<p class="videoTitle">'
          +'    <br/>'
          +'    <a style="font-size:16px;" href="submissionContent?name=' + imageContent + '">Download the original file</a>'
          +'    <br/>'
          +'</p>';
    } else if (videoContent != null && videoContent != '') {
        content += '<div class="player">'
                + '<div id="mainPlayer">'
                + '<p><strong>You need to upgrade your Flash Player</strong></p>'
                + '<p><a href="http://get.adobe.com/flashplayer">Download the flash player</a></p>'
                + '</div>' + '</div>';
    }
    if (shareable == 'yes') {
        content +=
        '<p class="videoTitle">'
                + '    <br/>'
                + '    <div style="font:large;"><b style="color:white;float:left;">NEW!&nbsp;</b><a href="submissionDetail.action?id=' + id + '">Discuss&Suggest</a></div>'
                + '    <br/>'
                + '</p>';
    }
    showSubmission(content);
    showVideoContent('./', videoContent, 'mainPlayer', shareable);
}

function rejectDocumentByUser(userDocumentId, documentTitle) {
    if (confirm("Are you sure you want to remove your document \"" + documentTitle + "\"? This operation cannot be undone, and you'll have to re-upload it.")) {
        var jsonrpc = new JSONRpcClient("JSON-RPC");
        jsonrpc.documentManager.rejectUserDocument(userDocumentId);
        $('userDocument' + userDocumentId).hide();
        parent.clickAHref('loadPendingDocumentsHref');
    }
}

var rejectionUrl;

function rejectUserDocument(url) {
    rejectionUrl = url;
    showPopup3($('confirmationDialog').innerHTML);
}

function setDocumentRejectionReason(reason) {
    rejectionUrl += '&reason=' + reason;
    
     YAHOO.util.Connect.asyncRequest('GET', rejectionUrl, {
        success    : function(response) {
            hidePopup3();
            $('documents').update(response.responseText);
        },
        failure : function(response) {
            document.getElementById('pageMessages').innerHTML = '<span class="msgError">There was an error while rejecting the document.</span>';
        }
    });
}