/**
*  @author: chad wagner, madebychad.com
*  @description: because the CMS lays out elements without containers having ids, the dom must be parsed
*                in part and have specific elements assigned various className's for theme
*  @created: 11/25/09
*/
var currentDiv = 0;
var numTabs = 0;
var numBoxes = 0;

var foundMainContent = false;
var setupTheme =function(){
   //return true;
   //alert("Dom loaded");

  //var extraContent = get('dnn_ContentPane').firstChild;//.nextSibling.nextSibling;
  //alert(extraContent);

  var right = get('dnn_Col3Pane');
  var middle = get('dnn_ContentPane');


  var rightElements = right.childNodes;
  var rightTop = get('brighton_sub-menu');
  var rTopElem = typeof(rightTop) != 'undefined' ? rightTop.childNodes : [];
  
  var middleElements = middle.childNodes;
    

  var tabHeader = document.createElement('div');
         tabHeader.setAttribute("id","rightTabHeader");

//1a. set class names on divs
  for(var i=0; i < rightElements.length; i++){
    if(i<0 || rightElements[i].tagName == 'DIV'){//one of our content boxes, apply an id and style to it
        var div = i==-1 ? rightTop : rightElements[i]; 
      //div's to end up in a "tab"
        if(currentDiv <= 1){
            div.className = div.className + " rightcolumntab tabbox"+currentDiv + (currentDiv == 0 ? " tabshow" : " tabhide");
            var origTitle = div.getElementsByTagName('h3')[0];
            var title = document.createElement("a");
                   title.innerHTML = origTitle.innerHTML;
                   title.setAttribute("id","tabHeader"+currentDiv);
                   title.className = "tabHeader" + (currentDiv == 0 ? " activeHeader" : " inactiveHeader");
                   title.setAttribute("href","javascript: showRightTab('"+currentDiv+"', this);");

            //alert(title.innerHTML);
            tabHeader.appendChild(title);
            origTitle.parentNode.removeChild(origTitle);
            numTabs++;

     //Div's to end up with a rounded shell
        }else{
            //initial task, get all divs in this container and apply the class "rightBoxMiddle" to them so they are padded only at level 0
            var innerDivs = div.getElementsByTagName('div');
            if(innerDivs && innerDivs.length > 0)
            for(var j=0; j<innerDivs.length; j++){
               var midDiv = innerDivs[j];
               if(midDiv.parentNode == div){
                   midDiv.className = (typeof(midDiv.className) == 'undefined' ? '' : midDiv.className) + ' rightBoxMiddle';
               }
            }
            //round out the borders only
            div.className = div.className + " rightBoxModule";
            var origTitle = div.getElementsByTagName('h3')[0];
            var titleHolder = document.createElement('div');
            var title = document.createElement("h1");
                title.innerHTML = origTitle.innerHTML;
                titleHolder.setAttribute("id","rightBox"+currentDiv);
                titleHolder.className = "rightBoxTop";
            titleHolder.appendChild(title);
            div.insertBefore(titleHolder,div.firstChild);
            origTitle.parentNode.removeChild(origTitle);

            
            
        }
     
         div.setAttribute('id','rightcol'+currentDiv);
      
         currentDiv++;
   }
     //alert(rightElements[i].tagName );
     
  }

//1b. insert a header for the tabbed interface
  if(currentDiv  > 0) right.insertBefore(tabHeader,right.firstChild);

//2. set class names on divs that are in the middle column
  var titleText = '';
  var toRemove = [];
  for(var i=0; i < middleElements.length; i++){
    //grab the title
    if(middleElements[i].tagName == 'DIV'){//one of our content boxes, apply an id and style to it
       if(!foundMainContent){ foundMainContent = true; middleElements[i].className = 'mainContentModule'; continue;}

       //initial task, get all divs in this container and apply the class "smallBoxMiddle" to them so they are padded only at level 0
       var innerDivs = middleElements[i].getElementsByTagName('div');
       if(innerDivs && innerDivs.length > 0)
       for(var j=0; j<innerDivs.length; j++){
          var midDiv = innerDivs[j];
          if(midDiv.parentNode == middleElements[i]){
              midDiv.className = (typeof(midDiv.className) == 'undefined' ? '' : midDiv.className) + ' smallBoxMiddle';
          }
       }

       //a. create the header
       var title = document.createElement('h1');
       title.innerHTML = titleText;
       var div = document.createElement('div');
       div.className = 'smallBoxTop';
       div.appendChild(title);

       //b. insert it before the current content
       //alert(middleElements[i].childNodes[0].innerHTML);

       middleElements[i].firstChild.className = 'smallBoxMiddle';
       middleElements[i].insertBefore(div,middleElements[i].childNodes[0]);
       middleElements[i].className = 'smallBoxModule middleModule' + numBoxes + ' middleTitleColor' + (numBoxes % 2);

       //c. now insert a footer div
       /* removed and put the bottom's background into the parentNode
       var footerText = document.createElement('p');
       footerText.innerHTML = '&nbsp';
       var divF = document.createElement('div');
       divF.className = 'smallBoxBottom';
       divF.appendChild(footerText);

       //c. insert the footer div after the content div
       middleElements[i].appendChild(divF);
       */
       
       numBoxes++;
     
    }else if(middleElements[i].tagName == 'H1'){
        titleText = middleElements[i].innerHTML;
        toRemove[toRemove.length] = middleElements[i];
        
    }
    //alert(middleElements[i].tagName ); 
  }
  for(var i=0; i<toRemove.length;i++) toRemove[i].parentNode.removeChild(toRemove[i]);


}

var showRightTab = function(index,elem){
    for(var i=0; i<numTabs; i++){
         get('tabHeader'+i).className = "tabHeader " + (i == index ? 'activeHeader' : 'inactiveHeader' );
         get('rightcol'+i).className = "block rightcolumntab tabbox"+i+" "+(i == index ? 'tabshow' : 'tabhide' );
    }
   var firstLink = get('rightcol'+index).getElementsByTagName('a')[0];
   if(firstLink){
      firstLink.focus();
      firstLink.blur();  
   }
}

// domReady.js
//
// DOMContentLoaded event handler. Works for browsers that don't support the DOMContentLoaded event.
//
// Modification Log:
// Date 	Initial Description
// 26 May 2008	TKO	Created by Tanny O'Haley

/*global addEvent, escape, unescape */

var domReadyEvent = {
	name: "domReadyEvent",
	// Array of DOMContentLoaded event handlers.
	events: {},
	domReadyID: 1,
	bDone: false,
	DOMContentLoadedCustom: null,

	// Function that adds DOMContentLoaded listeners to the array.
	add: function(handler) {
		// Assign each event handler a unique ID. If the handler has an ID, it
		// has already been added to the events object or been run.
		if (!handler.$$domReadyID) {
			handler.$$domReadyID = this.domReadyID++;

			// If the DOMContentLoaded event has happened, run the function.
			if(this.bDone){
				handler();
			}

			// store the event handler in the hash table
			this.events[handler.$$domReadyID] = handler;
		}
	},

	remove: function(handler) {
		// Delete the event handler from the hash table
		if (handler.$$domReadyID) {
			delete this.events[handler.$$domReadyID];
		}
	},

	// Function to process the DOMContentLoaded events array.
	run: function() {
		// quit if this function has already been called
		if (this.bDone) {
			return;
		}

		// Flag this function so we don't do the same thing twice
		this.bDone = true;

		// iterates through array of registered functions 
		for (var i in this.events) {
			this.events[i]();
		}
	},

	schedule: function() {
		// Quit if the init function has already been called
		if (this.bDone) {
			return;
		}
	
		// First, check for Safari or KHTML.
		if(/KHTML|WebKit/i.test(navigator.userAgent)) {
			if(/loaded|complete/.test(document.readyState)) {
				this.run();
			} else {
				// Not ready yet, wait a little more.
				setTimeout(this.name + ".schedule()", 100);
			}
		} else if(document.getElementById("__ie_onload")) {
			// Second, check for IE.
			return true;
		}

		// Check for custom developer provided function.
		if(typeof this.DOMContentLoadedCustom === "function") {
			//if DOM methods are supported, and the body element exists
			//(using a double-check including document.body, for the benefit of older moz builds [eg ns7.1] 
			//in which getElementsByTagName('body')[0] is undefined, unless this script is in the body section)
			if(typeof document.getElementsByTagName !== 'undefined' && (document.getElementsByTagName('body')[0] !== null || document.body !== null)) {
				// Call custom function.
				if(this.DOMContentLoadedCustom()) {
					this.run();
				} else {
					// Not ready yet, wait a little more.
					setTimeout(this.name + ".schedule()", 250);
				}
			}
		}

		return true;
	},

	init: function() {
		// If addEventListener supports the DOMContentLoaded event.
		if(document.addEventListener) {
			document.addEventListener("DOMContentLoaded", function() { domReadyEvent.run(); }, false);
		}

		// Schedule to run the init function.
		setTimeout("domReadyEvent.schedule()", 100);

		function run() {
			domReadyEvent.run();
		}
		
		// Just in case window.onload happens first, add it to onload using an available method.
		if(typeof addEvent !== "undefined") {
			addEvent(window, "load", run);
		} else if(document.addEventListener) {
			document.addEventListener("load", run, false);
		} else if(typeof window.onload === "function") {
			var oldonload = window.onload;
			window.onload = function() {
				domReadyEvent.run();
				oldonload();
			};
		} else {
			window.onload = run;
		}


		/* for Internet Explorer */
		/*@cc_on
			@if (@_win32 || @_win64)
			document.write("<script id=__ie_onload defer src=\"//:\"><\/script>");
			var script = document.getElementById("__ie_onload");
			script.onreadystatechange = function() {
				if (this.readyState == "complete") {
					domReadyEvent.run(); // call the onload handler
				}
			};
			@end
		@*/
	}
};

var domReady = function(handler) { domReadyEvent.add(handler); };
domReadyEvent.init();


domReady(setupTheme);
