// AAMAS 2010 namespace
YAHOO.namespace("aamas2010");

/*
 * Implementation of the left-hand side navigation tree menu
 */
YAHOO.aamas2010.navtree = {

    // the init function hooks up the toggle listener, and collapses the tree menu
    init:function(){
        // hook up the click listener, note "this" is whoever cal init (here only "navigation-left")
        YAHOO.util.Event.addListener(this, "click", YAHOO.aamas2010.navtree.click);
        YAHOO.util.Event.addListener(this,"dblclick", YAHOO.aamas2010.navtree.toggleCollapseAll); //HG
        // make everything collapsed, and disable selection
        var children = YAHOO.util.Dom.getChildren(this);  //"this" is navigation-left and children are h3 or dl (not dt)
        for (var i = 0; i < children.length; i++) {
            children[i].className = "collapsed";
            if (children[i].tagName.toLowerCase() == "h3") {
                YAHOO.aamas2010.util.disableSelection(children[i]);
                // if last, or no submenus, make it unexpandable
                if ((i == children.length - 1) || (children[i+1].tagName.toLowerCase() == "h3"))
                    children[i].className = "unexpandable";
            } else if (children[i].tagName.toLowerCase() == "dl") { //added by HG: make submenus text not selectable
               var items = YAHOO.util.Dom.getChildren(children[i]);   //items in submenu
               for (var j = 0; j < items.length; j++) 
                   YAHOO.aamas2010.util.disableSelection(items[j]); //Added by HG
	    }
        }
    },
    
    // called when someone clicks inside the navigation div element; this function
    // acts as a dispatcher for the rest
    click:function(e) {
        // figure out who was clicked 
        var t = YAHOO.util.Event.getTarget(e);
        // if it's not h3, get out, because we have only one nested level so we won't hander click on submenu here
        if (t.tagName.toLowerCase() != "h3")
            return;
        // otherwise, get the dl sibling, and if there, toggle its display
        var dl = YAHOO.util.Dom.getNextSibling(t);
        if (dl!=null && dl.tagName.toLowerCase() == "dl") { //if it's not dl means it's h3 without childern: unexpandable!
            t.className = (t.className == "collapsed") ? "expanded" : "collapsed";  //so the icon for h3 will be changed
            dl.className = (dl.className == "collapsed") ? "expanded" : "collapsed"; //so  the display of items in dl will become none
        }
    },

    collapseall:function(){
        // make everything collapsed
        var nav = document.getElementById("navigation-left");
        var children = YAHOO.util.Dom.getChildren(nav);  //"this" is navigation-left and children are h3/dl
        for (var i = 0; i < children.length; i++) {
            if (children[i].className == "expanded")
	            children[i].className = "collapsed";
        }
    },


    expandall:function(){
        // make everything expanded
        var nav = document.getElementById("navigation-left");
        var children = YAHOO.util.Dom.getChildren(nav);  //"this" is navigation-left and children are h3/dl
        for (var i = 0; i < children.length; i++) {
            if (children[i].className == "collapsed")
	            children[i].className = "expanded";
        }
    },

    toggleCollapseAll:function(e){
        if (allExpanded)
		YAHOO.aamas2010.navtree.collapseall();
	else
		YAHOO.aamas2010.navtree.expandall();
	allExpanded = ! allExpanded;
        YAHOO.util.Event.preventDefault(e);
        
    },

    //given an href, search the left-submenu (only inside <dt>, not <dl>) for a maching anchor
    //if found returns the element (i.e. the anchor) otherwise return null
    findNavigationItem:function(href){
      var navRoot = "navigation-left"; //id of navigation div, we use to find it's descendants
      var isaDTandSameHRef = function(anchor) {
            var p = anchor.parentNode;
            return (p && p.tagName.toLowerCase()=="dt" && anchor.href==href);
        };
      var navLinks = YAHOO.util.Dom.getElementsBy(isaDTandSameHRef, "a", navRoot ); //find all anchor "a" that are child of "dt" 
      if (navLinks.length ==0) 
      	return null;
      else
      	return navLinks[0];
    },

    //given an anchor element in the left-submenu, hightlight it, also if its h3&dl is collapsed 
    // expand them, and finally deselect any previous selection
    //if elm is null nothing get's highlighted but past selection gets deselected
    highlightNavigationItem:function(elm){ //elm is a "<a  >" anchor, either in h3 or dt
       var sels = YAHOO.util.Dom.getElementsByClassName('selected');
        YAHOO.util.Dom.removeClass(sels, 'selected'); //remove the "selected" classname from previosly slected items
	if (elm){
          var dt = elm.parentNode;
          var dl = dt.parentNode;
          YAHOO.util.Dom.addClass(elm, "selected");  //add "selected" class to this link
         if (dl.className ==  "collapsed"){ //if dl is collapsed, expand both h3 and dl
             var h3 =  YAHOO.util.Dom.getPreviousSibling(dl)// dl.previousSibling;
             dl.className = "expanded";
             h3.className = "expanded";
	  }
	}
    }
}


YAHOO.aamas2010.infoSectionLayout = {
    // shrink the infosection
    shrinkInfoSection:function(e) {
   	  document.getElementById("info-section").style.display = "none";
   	  document.getElementById("content").style.width = "755px"; //582+192-18-1 (have same pading!)
   	  document.getElementById("shrinked-info-section").style.display = "inline";
   	  document.getElementById("bgframe").style.backgroundImage = "url(images/conference_logo_background_expanded.jpg)"; //expanded bg for content

    },
    // expand the infosection
    expandInfoSection:function(e) {
   	  document.getElementById("content").style.width = "582px";
   	  document.getElementById("shrinked-info-section").style.display = "none";
   	  document.getElementById("info-section").style.display = "inline";
   	  document.getElementById("bgframe").style.backgroundImage = "url(images/images/conference_logo_background_normal.jpg)"; //origbackground for content

    }

}
/*
 * Implementation of AJAX-based links and other interesting actions; this 
 * is basically, a dispatcher for all interesting clicks, except the clicks
 * that take care of navigation menu (TBD: combine these)
 */
YAHOO.aamas2010.links = {

    // the init function hooks up the listener
    init:function(){
        // hook up the click listener
        YAHOO.util.Event.addListener(document.getElementById("container"),"click", YAHOO.aamas2010.links.click);
        YAHOO.util.Event.addListener(document.getElementById("shrinked-info-section"),"click", YAHOO.aamas2010.infoSectionLayout.expandInfoSection);
        YAHOO.util.Event.addListener(document.getElementById("button-shrink-info"),"click", YAHOO.aamas2010.infoSectionLayout.shrinkInfoSection);
	document.getElementById("button-shrink-info").style.display = "inline";
    },


    // return current mouse position of click
    getMousePos:function(e){
        var p={posx:0,  posy:0};
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		p.posx = e.pageX;
		p.posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		p.posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		p.posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
        return p;
    },

    //check the given href to see if it's from website or an external website
    internalUrl:function(href){
        var otherurl = parseUri(href);    //parseUri is our function in parseuri.js
        var oururl   = document.location; //document.location has comptlete URI
        return (otherurl.host == oururl.hostname && 
		 (otherurl.path == oururl.pathname || otherurl.path == oururl.pathname+"index.php")   );
    },
  
    // called when someone clicks in the document; if the source is the anchor with 
    // no class set this function loads the requested document via AJAX, i.e. 
    // every anchor is by default loaded into the content page via AJAX; external
    // anchors should have class "external"; if the source is INPUT tag with class
    // submit, we call appropriate form handler
    click:function(e) {
        // figure out who was clicked, if not "a" (or for images its parent is not "a")
        // get out right away
        var t = YAHOO.util.Event.getTarget(e);
        switch(t.tagName.toLowerCase()) {
        case "img":
            t = t.parentNode;  //finding it's "a" tag
            // fall through 
        case "a":
            if (!t.href) //it's not a real link to somewhere!
		break;
            if (t.id == "gototop"){  //it's a go to top icon
        	window.scrollTo(0,0);
                YAHOO.util.Event.preventDefault(e);
		break;
            }
            if ((YAHOO.aamas2010.links.internalUrl(t.href))){//it's an internal link. OlD: if (t.className != "external")
                if (t.id == "navt-gohome")  //if clicked on home then collapse the tree menu
	    	   YAHOO.aamas2010.navtree.collapseall();
               // extract content string from URL. content is everything after "content=" or "" if its home
               var content = "";
               var mousepos = YAHOO.aamas2010.links.getMousePos(e); //get positoin of mouse click, mayneed to scroll
               var idx = t.href.indexOf("?content=");         
               if (idx >= 0) //it's not home page, it has content param
                   content = t.href.substring(idx + 9);  // 9 = length("?content=")
               else //it's homepage, get out and do the default (reload the whole page)
		   break;
               try {
                   // try the history navigation - this will end up calling 
                   // YAHOO.aamas2010.ajax.stateChangeHanlder because I've registered it as a history handler
                   YAHOO.util.History.navigate("content", content);
               } catch ( e ) {
                   // this will happen if its not an A-grade browser, just go via the regular AJAX route
                   YAHOO.aamas2010.ajax.loadContent(content);
               }
               if (mousepos.posy>850) //if too down the page, scroll up so the content is visible!
        	  window.scrollTo(0,230);
               YAHOO.util.Event.preventDefault(e);  // prevent default behaviour, since we processed the click
               break;
             } else{ //it's an external link. 
                var newWindow = window.open(t.href, '_blank');  //open in a new window!
                newWindow.focus();
                YAHOO.util.Event.preventDefault(e);
                break;
             }
           case "input": //disable, we don't use this feature
            if (t.className != "submit")
                break;
            var form = YAHOO.util.Dom.getAncestorByTagName(t, "form");
            if (form.id == "contact-form") {
                YAHOO.aamas2010.contactForm.handle();
                YAHOO.util.Event.preventDefault(e);
            }        
            break;
        }
        return;
    }
}

/*
 * AJAX-based local navigation and history management 
 */
YAHOO.aamas2010.ajax = {

    // this function is used to load the content and the info section
    // whenever the connection manager has processed the connection request
    // successfully; obj is YAHOO.util.connection
    requestSuccess:function(obj) {
        var response = obj.responseText; // get the response
        // extract the pieces that we need
        var content_start = response.indexOf("<div id=\"content\"");
        content_start = response.indexOf(">", content_start) + 1;
        var content_end = response.indexOf("<\/div>", content_start);
//HG        var info_start = response.indexOf("<div id=\"info-section\"");
//HG        info_start = response.indexOf(">", info_start) + 1;
//HG        var info_end = response.indexOf("<\/div>", info_start);
        // and now, plug in in where it belongs
        document.getElementById("content").innerHTML = response.substring(content_start, content_end);
//HG        document.getElementById("info-section").innerHTML = response.substring(info_start, info_end);
        document.body.style.cursor = "default";
    },

    // this function is used to load the content and the info section
    // whenever the connection manager has failed to process the connection 
    // request; obj is YAHOO.util.connection
    requestFailure:function(obj) {
        var error = "<h1>Sorry</h1>";
        error += "<p>An error occured trying to fetch the document: </p>"; 
        error += '<p class="error">'
      
        if (obj.status == -1) {    
            error += "The connection has timed out.";
        } else if (obj.status == 404) {
            error += "The document was not found.";
        } else {
            error += obj.statusText;
        }
        error += "</p>" +
                  "<p>Please refresh your browser and try again later.  If the problem persists, please let us know " +
                  "by sending an email to skhan" + 
                  "@" + "cse.yorku.ca</p><p>Thank you very much in advance !</p>";
        // plug in the error text where it belongs
        document.getElementById("content").innerHTML = error;
        document.body.style.cursor = "default";
    },

    // This function is responsible for making an asynch request to 
    // the server and fetching the appropriate content via AJAX. The
    // content is the name of the content, which is everything after
    // the "content=" string, or "" if we need to go home
    loadContent:function(content) {
        // hookup the handlers
        var handlers = {
            success: YAHOO.aamas2010.ajax.requestSuccess,  // handler for success
            failure: YAHOO.aamas2010.ajax.requestFailure,  // handler for error
            timeout: 10000     // timeout in ms before declaring failure
        }

        // make up the URL
        var url = "index.php?";
        if (content != "")
            url += "content=" + content + "&";
        url += "xml"; 
        document.body.style.cursor = "wait"; // indicate that we're waiting
        // define a new asych connector request to load the URL
        var conn = YAHOO.util.Connect.asyncRequest("GET", url, handlers);

        var ourAddress = document.location.href.substring(0,document.location.href.lastIndexOf("/")+1)+"index.php";
        if (content != "")
             ourAddress += "?content=" + content; 
	var navLink = YAHOO.aamas2010.navtree.findNavigationItem(ourAddress);
	//debugging alert(ourAddress);
	YAHOO.aamas2010.navtree.highlightNavigationItem(navLink);  //hightlights the appropriate navtiation subitem if user clicked on it 

    },
    
    // This is the handler called by the history manager whenever it thinks
    // that the app state has changed. I've registered this function with the
    // history manager, and so it will be called whenever someone calls 
    // YAHOO.util.History.navigate (which for us happends inside YAHOO.aamas2010.links.click)
    // or when the user walks around using back/forward buttons
    // All we need to do is to load the appropriate content
    stateChangeHanlder:function(state) {
       YAHOO.aamas2010.ajax.loadContent(state);
   },
    
    initializeNavigationBar:function() {
        // This is the tricky part... The window's onload handler is called when the
          // user comes back to your page using the back button. In this case, the
          // actual section that needs to be loaded corresponds to the last section
          // visited before leaving the page, and not the initial section. This can
          // be retrieved using getCurrentState:
          var currentContent = YAHOO.util.History.getCurrentState("content");
          if ( location.hash.substr(1).length > 0 ) {
               // If the section requested in the URL fragment is different from
               // the section loaded in index.php, we have an unpleasant refresh
               // effect because we do an asynchronous XHR call. Instead of doing
               // a synchronous XHR call, we can fix this by erasing the initial
               // content of bd:
               if (currentContent != queryContent)
                   YAHOO.util.Dom.get("content").innerHTML = "";
               YAHOO.aamas2010.ajax.loadContent(currentContent);
          }
    }
}

/*
 * AJAX-based contact form implementation
 */
YAHOO.aamas2010.contactForm = {

    // handles the validation and submission of the contact form;
    handle:function() {
        // extract and validate parameters
        var to = document.getElementById("to").value;
        var from_email = document.getElementById("from-email").value;
        var from_name = document.getElementById("from-name").value;
        var subject = document.getElementById("subject").value;
        var message = document.getElementById("message").value;
        var error = 0;
        var error_text;
        if (from_email == "") {
            error_text = "required";
            error = 1;
        } else if ((from_email.indexOf("@") <= 0) || 
                  (from_email.indexOf("@") >= from_email.lastIndexOf("."))) {
            error_text = "misformatted email";
            error = 1;
        } else {
            error_text = "";
        }
        document.getElementById("from-email-error").innerHTML = error_text;
        if (from_name == "") {
            error_text = "required";
            error = 1;
        } else {
            error_text = "";
        }
        document.getElementById("from-name-error").innerHTML = error_text;        
        if (message == "") {
            error_text = "required";
            error = 1;
        } else {
            error_text = "";
        }
        document.getElementById("message-error").innerHTML = error_text;
        if (error)
            return;
        // form validated, submit
        poststr = "to=" + escape(encodeURI(to)) +
                  "&from_email=" + escape(encodeURI(from_email)) +
                  "&from_name=" + escape(encodeURI(from_name)) +
                  "&subject=" + escape(encodeURI(subject)) +
                  "&message=" + escape(encodeURI(message)) +
                  "&xml";
        // hookup the handlers
        var handlers = {
            success: YAHOO.aamas2010.ajax.requestSuccess,  // handler for success
            failure: YAHOO.aamas2010.ajax.requestFailure,  // handler for error
            timeout: 10000     // timeout in ms before declaring failure
        }
        // make up the URL
        var url = document.getElementById("contact-form").getAttribute("action");
        // define a new asych connector request to load the URL
        url += "&xml";
        var conn = YAHOO.util.Connect.asyncRequest("POST", url, handlers, poststr);
        // indicate that we're waiting
                document.getElementById("content").innerHTML = "<h1>Sending ...</h1>";
        document.body.style.cursor = "wait";
    }
}
 
/*
 * Various extremely useful utility functions
 */
YAHOO.aamas2010.util = {

    // Disables text selection on the specified element
    disableSelection:function (e) {
        e.onselectstart = function() { return (false); };
        //e.onselect = function() { return (false); };
 	e.unselectable = "on";
        e.style.MozUserSelect = "none";
        // uncomment this to make sure that the cursor doesn't change over text
        // e.style.cursor = "default";
    }
}

/* Hook up all the listeners ...
 */

// as soon as the element with ID "navigation-left" is available, initialize 
// the navigation tree
YAHOO.util.Event.onAvailable("navigation-left", YAHOO.aamas2010.navtree.init);

// as soon as the document's DOM is ready, initialize the link handler
YAHOO.util.Event.on(window, "load", YAHOO.aamas2010.links.init);


// decide which content do we start from, the options are:
// 1. URL fragment identifier (it will be there if the user previously
// bookmarked the application in a specific state)
// 2. "content" URL parameter (it will be there if the user accessed
// the site from a search engine result, or did not have scripting
// enabled when the application was bookmarked in a specific state)
// 3. or "" (home page, this is the default)
var bookmarkedContent = YAHOO.util.History.getBookmarkedState("content");
var queryContent = YAHOO.util.History.getQueryStringParameter("content");
var initContent = bookmarkedContent || queryContent || "";
var curNavSelected=false; //this will be the item on the leftnavigtion that user has clicked 
var allExpanded=false;

if (queryContent){ //if the user what to access a directy query index.php?... we replace it with hash!
     var st= new String(location);
     location = st.replace(/\?/,"#");
     //alert(' LOC is '+ location+'\n\n\n ST is '+st);
}

// register our module with the history manager; note that module registration 
// MUST take place before calling YAHOO.util.History.initialize.
YAHOO.util.History.register("content", initContent, YAHOO.aamas2010.ajax.stateChangeHanlder);
YAHOO.util.History.onLoadEvent.subscribe(YAHOO.aamas2010.ajax.initializeNavigationBar);
// The call to YAHOO.util.History.initialize should ALWAYS be from within
// a script block located RIGHT AFTER the opening body tag (this seems to prevent
// an edge case bug on IE - IE seems to sometimes forget the history when
// coming back to a page, and the back - or forward button depending on the
// situation - is disabled...)
try {
    YAHOO.util.History.initialize();
} catch ( e ) {
    // The only exception that gets thrown here is when the browser is not A-grade.
    // Since scripting is enabled, we still try to provide the user with a better
    // experience using AJAX. The only caveat is that the browser history will not work.
    YAHOO.aamas2010.ajax.initializeNavigationBar();
}
//alert(initContent);

