﻿/***
Filename:       dashboard.js
Date:           02/11/2007
Author:         James Condliffe
Description:    Sets up the Members dashboard
***/


/***
Set up the dashboard panels
***/
(function()
{
    YAHOO.util.Event.onDOMReady(init);
        
    function init()
    {
        var panels = YAHOO.util.Dom.getElementsByClassName("panel");
	    var panelobjects = new Array();
	    var ypos = -1;
	    var line = 0;

        // Fix the height of the panel container
        YAHOO.util.Dom.setStyle("modulespage","height",YAHOO.util.Dom.getStyle("modulespage","height"));

        // Retrieve the member id from the markup
        Nisa.memberId = YAHOO.util.Dom.get("memberid").firstChild.nodeValue;

        // Create the overlay manager
        var manager = new YAHOO.widget.OverlayManager();

        // Start the initialisation process
        Nisa.initialisingPanels = true;
        
            
        // Iterate backwards through the floated panels
        for(var i = (panels.length-1); i > -1; i--)
        {
            var panelxy;
            var panelz;
            
            // Use positioning information from the backend if available
            if(panels[i].getAttribute("x") > 0 && panels[i].getAttribute("y") > 0)
            {
                panelxy = [parseInt(panels[i].getAttribute("x")), parseInt(panels[i].getAttribute("y"))];
            }
            else // Otherwise 'absolutize' the floated position
            {            
                panelxy = YAHOO.util.Dom.getXY(panels[i]);            
            }
            
            // Use z axis positioning information from the backend if available
            if(panels[i].getAttribute("z") > 0)
            {
                panelz = parseInt(panels[i].getAttribute("z"));
                //console.log(panelz);
            }
            
            // Panels can be fixed, normal or modal
            if(YAHOO.util.Dom.hasClass(panels[i], "Normal"))
            {
            
                // Remove the 'panel' class to get rid of the JS-free CSS styles
                YAHOO.util.Dom.removeClass(panels[i], "panel");
                
                // Create and render the panel
	            panelobjects[i] = new Nisa.NisaPanel(panels[i],
	                {xy: panelxy,
	                zIndex: panelz,
	                draggable: true,
	                resizeable: true,
	                close: true,
	                effect: {effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25},
	                underlay: "none"} );
    	            
	            panelobjects[i].render();
    		
	            // Register the new panel with the overlay manager
	            manager.register(panelobjects[i]);
	        }
	        else if(YAHOO.util.Dom.hasClass(panels[i], "Modal"))
	        {
	            
	            // Remove the 'panel' class to get rid of the JS-free CSS styles
                YAHOO.util.Dom.removeClass(panels[i], "panel");
                
                if(panels[i].id == 'panel19')
                {
                // Create and render the panel
	            panelobjects[i] = new Nisa.NisaPanel(panels[i], 
	                {fixedcenter: true, 
	                close: false,
	                resizeable: false, 
	                closeButtonID: "tour-close", 
	                notifyWebservice: false} );
	            }
	            else{
	            panelobjects[i] = new Nisa.NisaPanel(panels[i], 
	                {fixedcenter: true, 
	                close: false,
	                resizeable: false, 
	                closeButtonID: "ocs-info-close", 
	                notifyWebservice: false} );
	            }    
	            panelobjects[i].render();
    		
	            // Register the new panel with the overlay manager
	            manager.register(panelobjects[i]);
	        }
	        
	        manager.bringToTop("panel19");
        }
        
        Nisa.initialisingPanels = false;
    }
})();




/***
Set up the Bulletin Board registration form
***/
(function()
{
    YAHOO.util.Event.onDOMReady(init);
    
    var NOEMAIL_CHECKBOX_ID = "noemail_noemail";
    var NOEMAIL_WARNING_CLASS = "noemailwarning";
    var EMAIL_FIELD_ID = "email";
    var FIELDCONTAINER_CLASS = "fieldcontainer";
    var ALERTCONTAINER_CLASS = "alert";
    var ALERTCONTAINER_ID = "alertcontainer";
    var CONTINUEBUTTON_ID = "bulletinemail_submit";    
    
    // Main HTML form
    var form;
    
    // Email fields
    var emailField;
    
    // Various Email Check elements
    var emailValid;
    var alertContainer;
    
    // Various Terms and Conditions elements
    var tandcContainer;
    var tandcCheckbox
    var tandcCheckboxLabel
    var tandcView;

    function init()
    {
        // Cancel out if no email field
        if(!YAHOO.util.Dom.get(EMAIL_FIELD_ID))
        {
            return;
        }
    
        try
        {
            // Hide the warning initially
            YAHOO.util.Dom.getElementsByClassName(NOEMAIL_WARNING_CLASS, "div", document, function(){YAHOO.util.Dom.setStyle(this,"display","none");});
            
            // Apply an event handler to the checkbox
            YAHOO.util.Event.on(NOEMAIL_CHECKBOX_ID, "click", emailToggle);
            
            // Apply an event handler to the text field to check the email address using the webservice
            YAHOO.util.Event.on(EMAIL_FIELD_ID, "keyup", checkEmail);
            
            // Create an alert area in the DOM
            alertContainer = document.createElement("div");
            alertContainer.appendChild(document.createTextNode(""));            
            alertContainer.id = ALERTCONTAINER_ID;
            YAHOO.util.Dom.addClass(alertContainer, ALERTCONTAINER_CLASS);
            YAHOO.util.Dom.insertAfter(alertContainer, YAHOO.util.Dom.get(EMAIL_FIELD_ID));
            
            emailField = YAHOO.util.Dom.get(EMAIL_FIELD_ID);
            
            // Check the email address initially if present
            if(emailField.value.length > 0)
            {
                checkEmail(null);
            }
            
            // Grab the T&C related objects
            tandcContainer = YAHOO.util.Dom.getElementsByClassName("tandc", "div", document)[0];
            tandcCheckboxLabel = YAHOO.util.Dom.get("tandcagree_agree_label");
            tandcCheckbox = YAHOO.util.Dom.get("tandcagree_agree");
            
            // Hide the T&Cs initially
            YAHOO.util.Dom.setStyle(tandcContainer, "display", "none");            
            
            // Add 'View' command
            tandcView = document.createElement("a");
            tandcView.appendChild(document.createTextNode("(view)"));
            YAHOO.util.Dom.setStyle(tandcView, "margin-left", "5px");
            YAHOO.util.Dom.setStyle(tandcView, "cursor", "pointer");
            YAHOO.util.Event.addListener(tandcView, "click", termsToggle);
            tandcCheckboxLabel.appendChild(tandcView);
            
            // Attach event handler to form
            form = YAHOO.util.Dom.get("bulletinemail");
            YAHOO.util.Event.addListener(form, "submit", validateForm);
        }
        catch(e)
        {
            console.log(e);
        }        
    }
    
    function termsToggle(e, o)
    {
        var a = this;
    
        if(YAHOO.util.Dom.getStyle(tandcContainer, "display") == "none")
        {
            YAHOO.util.Dom.setStyle(tandcContainer, "display", "block");
            a.innerHTML = "(hide)";
        }
        else
        {
            YAHOO.util.Dom.setStyle(tandcContainer, "display", "none");
            a.innerHTML = "(view)";
        }
    
        YAHOO.util.Event.stopEvent(e);
    }
    
    function emailToggle(e)
    {
        var displayMessage = "";
        var displayField = "";
        
        if(this.checked)
        {
            displayField = "none";
        }
        else
        {
            displayMessage = "none";
        }
        
        // Warning
        YAHOO.util.Dom.getElementsByClassName(NOEMAIL_WARNING_CLASS, "div", document, function(){YAHOO.util.Dom.setStyle(this,"display",displayMessage);} );
            
        // Field
        var fieldcontainer = YAHOO.util.Dom.getAncestorByClassName(YAHOO.util.Dom.get(EMAIL_FIELD_ID), FIELDCONTAINER_CLASS);
        YAHOO.util.Dom.setStyle(fieldcontainer, "display", displayField);
        
        // Enable the button
        YAHOO.util.Dom.get(CONTINUEBUTTON_ID).disabled = false;
    }

    function checkEmail(e)
    {        
        var operation = "checkForumEmailUnique";
        var postdata = "EmailAddress=" + emailField.value;
        
        YAHOO.util.Connect.asyncRequest("POST", Nisa.WEBSERVICE_URI + operation, {success: checkEmailSuccess}, postdata);
    }
    
    function checkEmailSuccess(o)
    {
        var xmldoc = o.responseXML;
        result = xmldoc.documentElement.firstChild.nodeValue;
        
        if(result == 1)
        {
            YAHOO.util.Dom.addClass(alertContainer, "available")
            alertContainer.firstChild.nodeValue = "Available and valid";
            YAHOO.util.Dom.get(CONTINUEBUTTON_ID).disabled = false;
        }
        else
        {
            YAHOO.util.Dom.removeClass(alertContainer, "available")
            alertContainer.firstChild.nodeValue = "Not available or invalid";
            YAHOO.util.Dom.get(CONTINUEBUTTON_ID).disabled = true;
        }
    }
    
    function validateForm(e)
    {    
        if(tandcCheckbox.checked == false)
        {
            if(confirm("Do you agree to the Terms & Conditions?"))
            {
                tandcCheckbox.checked = true;
            }
            else
            {
                YAHOO.util.Event.stopEvent(e);
            }
        }
    }

})();

/***
Member tour
***/
(function()
{
    YAHOO.util.Event.onDOMReady(init);
    
    var MODULE_ID = 19;        
    var TOUR_ID = "membertour";
    var TOUR_WIDGETS_ID = "tourwidgets";
        
    var tour;
    var currentPage;
    
    var previousButton;
    var nextButton;

    function init()
    {
        // Only if the tour is in the markup
        if(!YAHOO.util.Dom.get(TOUR_ID))
        {
            return;
        }
        
        
        tour = new YAHOO.widget.TabView(TOUR_ID);
        
        // Add controls
        var tourWidgets = YAHOO.util.Dom.get(TOUR_WIDGETS_ID);
        YAHOO.util.Dom.setStyle(tourWidgets, "display", "block");

        previousButton = YAHOO.util.Dom.get("tour-previous");
        YAHOO.util.Event.addListener(previousButton, "click", changePage);
        previousButton.disabled = true;
        
        nextButton = YAHOO.util.Dom.get("tour-next");
        YAHOO.util.Event.addListener(nextButton, "click", changePage);
        
        var displayAgain = document.createElement("div");
        
        var displayAgainCheckbox = YAHOO.util.Dom.get("tour-displayagain");
        YAHOO.util.Event.addListener(displayAgainCheckbox, "click", updateDisplayAgain);
    }
    
    function changePage(e)
    {
        // Get the current tab position
        var current = tour.get("activeIndex");
        
        // Increment or decrement the position
        if(this.id == "tour-previous")
        {
            current--;
        }
        else
        {
            current++;
        }
        
        // Change the page to current
        tour.set("activeIndex", current);
        
        // Disable / enable buttons if appropriate
        if(current == 0)
        {
            previousButton.disabled = true;
        }
        else
        {
            previousButton.disabled = false;
        }
        
        if(current == (tour.get("tabs").length-1))
        {
            nextButton.disabled = true;
        }
        else
        {
            nextButton.disabled = false;
        }
    }
    
    function updateDisplayAgain(e)
    {   
        var operation;
        
        if(this.checked == true)
        {
            operation = "OpenModuleLocation";
        }
        else
        {
            operation = "CloseModuleLocation";
        }
        
        var postdata = "MemberId=" + Nisa.memberId + "&ModuleId=" + MODULE_ID;
        YAHOO.util.Connect.asyncRequest("POST", Nisa.WEBSERVICE_URI + operation, null, postdata);
    }

})();

/***
OCS Info Window
***/
(function()
{
    YAHOO.util.Event.onDOMReady(init);
    
    var MODULE_ID = 40;        
    var PANEL_ID = "panel40_c";
    var TOUR_WIDGETS_ID = "ocs-info-widgets";
        
    var tour;

    function init()
    {
        // Only if the tour is in the markup
        if(!YAHOO.util.Dom.get(PANEL_ID))
        {
            return;
        }

        var displayAgain = document.createElement("div");
        
        var displayAgainCheckbox = YAHOO.util.Dom.get("ocs-info-displayagain");
        YAHOO.util.Event.addListener(displayAgainCheckbox, "click", updateDisplayAgain);
    }
    
    function updateDisplayAgain(e)
    {   
        var operation;
        
        if(this.checked == false)
        {
            operation = "OpenModuleLocation";
        }
        else
        {
            operation = "CloseModuleLocation";
        }
        
        var postdata = "MemberId=" + Nisa.memberId + "&ModuleId=" + MODULE_ID;
        YAHOO.util.Connect.asyncRequest("POST", Nisa.WEBSERVICE_URI + operation, null, postdata);
    }

})();

/* Load Documents from WebService */
(function()
{
    var Connect = YAHOO.util.Connect;
    var TreeView = YAHOO.widget.TreeView;
    var HTMLNode = YAHOO.widget.HTMLNode;
    var Dom = YAHOO.util.Dom;
    
    var TREE_CONTAINER = "documentsTree";    
    
    var tree;

    YAHOO.util.Event.addListener(window, "load", init);

    function init()
    {
        if(!Dom.get(TREE_CONTAINER))
        {
            return;
        }        
        
        // Get the Document XML
        var uri = Nisa.WEBSERVICE_URI + "GetDocumentsXML?memberid=" + Dom.get("memberid").firstChild.nodeValue;
        var request = Connect.asyncRequest("GET", uri, {success: requestSuccess, failure: requestFailure});
    }
    
    function buildTreeFromXML(xml)
    {
        // Instantiate the treeview
        tree = new TreeView(TREE_CONTAINER);
        Dom.addClass(TREE_CONTAINER, "loaded");
        
        // Kick things off
        addNodes(xml.documentElement, tree.getRoot());

        // Render the tree
        tree.draw();
    }
    
    function addNodes(xmlNode, treeNode)
    {
        var immediateChildren = xmlNode.childNodes;
                        
        for(var i=0; i < immediateChildren.length; i++)
        {
            var item = immediateChildren[i];
            
            if(item.nodeName == "group")
            {
                var node = new HTMLNode(item.getAttribute("displayName"), treeNode, false, true);
                addNodes(item, node);                
            }
            else if(item.nodeName == "Item")
            {                
                var html = "<a class=\"" + item.getAttribute("type") + "\" href=\"" + item.getAttribute("filePath") + "\">" + item.getAttribute("displayName") + "</a>"
                var node = new HTMLNode(html, treeNode, false, true);
            }            
        }
    }
    
    
    /* Callback functions for the AJAX request */
    function requestSuccess(response)
    {
        if(response.responseText !== undefined)
        {
            // o.tId, o.status, o.statusText, o.getAllResponseHeaders, o.responseText
            buildTreeFromXML(response.responseXML);
        }    
    }
    
    function requestFailure(response)
    {
        if(response.responseText !== undefined)
        {
            //  o.tId, o.status, o.statusText
            console.log("Error during AJAX request")
        }
    }    
    
}());

/* Set up bulletins module behaviours */
(function()
{
    YAHOO.util.Event.onDOMReady(init);
    
    var u = YAHOO.util;
    
    var bulletinsSelect;
    var bulletinPeriods;
    var periodNumber;

    function init()
    {
        bulletinsSelect = u.Dom.get("BulletinPeriods");
        bulletinPeriods = u.Dom.getElementsByClassName("bulletin-items", "ul");
        periodNumber = u.Dom.getElementsByClassName("period-number", "div")[0];
    
        if(!bulletinsSelect || bulletinPeriods.length < 1 || !periodNumber)
        {
            return false;
        }

        u.Event.addListener(bulletinsSelect, "change", changePeriod);
        changePeriod();
    }

	function changePeriod(e)
	{
	    for(var i = 0; i < bulletinPeriods.length; i++)
	    {
	        var period = bulletinPeriods[i];
	        u.Dom.setStyle(period, "display", "none");
	    }	    
	    var validPeriod = u.Dom.get(bulletinsSelect.value);
	    periodNumber.innerHTML = bulletinsSelect.options[bulletinsSelect.selectedIndex].getAttribute("week");
	    u.Dom.setStyle(validPeriod, "display", "block");
	}

})();