﻿/**
 * @author	 		Marc Eley
 * Date created: 	25-04-2006 21:00 
 * Date revised: 	27-10-2006 10:38
*/

/**
 * The Utils object
 * @
*/
var Utils = {
	
	/**
	 * This method returns a reference to an HTML element
	 * @param	{String} sId The id-attribute of the HTML element you want to find
	 * @returns 	A reference to the node
	*/
	$:function (sId){
		return document.getElementById(sId)!=null?document.getElementById(sId):false;
	},
	
	/**
	 * This method returns the value of an HTML form element
	 * @param	{String} sId The id-attribute of the HTML form element which value you want to find
	 * @returns 	A string representing the value of the field
	*/
	$F:function(sId){
		return Utils.$(sId).value;
	},
	
	extend:function(o,parentNode){
		var p = parentNode?parentNode:this;
		for(var i in o) p[i] = o[i];
	},

	/**
	 *
	*/
	addClassName:function(elem,sClassName){
	    Utils.removeClassName(elem,sClassName);
	    elem.className = (elem.className + " " + sClassName).trim();
	},
	
	/**
	 *
	*/
	removeClassName:function(elem,sClassName){
		if(elem){
		    elem.className = elem.className.replace(sClassName,"").trim();
		}
	},
	
	/**
	 * This method will return a absolute pixel value of an element left edge to the edge of the browserwindow
	 * @param	{Node} o The HTML element which offset you want to find
	 * @returns 	A number
	*/
	getAbsLeft:function (o){
		var iY = 0;
		while(o.offsetParent){
			iY += o.offsetLeft;
			o = o.offsetParent;
		}
		return iY;
	},

	/**
	 * This method will return a absolute pixel value of an element top edge to the edge of the browserwindow
	 * @param	{Node} o The HTML element which offset you want to find
	 * @returns 	A number
	*/
	getAbsTop:function (o){
		var iX = 0;
		while(o.offsetParent){
			iX += o.offsetTop;
			o = o.offsetParent;
		}
		return iX;
	},
    getPageSize: function (){
    	
	    var xScroll,yScroll,scrollLeft;
    	
	    if (window.innerHeight && window.scrollMaxY) {	
		    xScroll = document.body.scrollWidth;
		    yScroll = window.innerHeight + window.scrollMaxY;
	    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		    xScroll = document.body.scrollWidth;
		    yScroll = document.body.scrollHeight;
	    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		    xScroll = document.body.offsetWidth;
		    yScroll = document.body.offsetHeight;
	    }
    	
	    var windowWidth, windowHeight;
	    if (self.innerHeight) {	// all except Explorer
		    windowWidth = self.innerWidth;
		    windowHeight = self.innerHeight;
		    scrollLeft = document.body.scrollLeft;
	    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		    windowWidth = document.documentElement.clientWidth;
		    windowHeight = document.documentElement.clientHeight;
		    scrollLeft = document.documentElement.scrollLeft;
	    } else if (document.body) { // other Explorers
		    windowWidth = document.body.clientWidth;
		    windowHeight = document.body.clientHeight;
		    scrollLeft = document.body.scrollLeft;
	    }	
    	
	    // for small pages with total height less then height of the viewport
	    if(yScroll < windowHeight){
		    pageHeight = windowHeight;
	    } else { 
		    pageHeight = yScroll;
	    }

	    // for small pages with total width less then width of the viewport
	    if(xScroll < windowWidth){	
		    pageWidth = windowWidth;
	    } else {
		    pageWidth = xScroll;
	    }
	    return [pageWidth,pageHeight,windowWidth,windowHeight,scrollLeft];
    },

	/**
	 * A method to easily create new DOM objects and populate them with attributes
	 * @param	{String} sType The type of HTML element to create
	 * @param	{Object} oConfig An object with attributes to attach to the created element
	 * @returns 	The newly created element
	*/
	createElement:function (sType,oConfig){
		var elm = document.createElement(sType);
		for(p in oConfig){
			if(p == "CSSClass"){
				elm.className = oConfig[p];
			} else if(p == "content"){
				try {
					elm.innerHTML = oConfig[p];
				} catch(e){}
			} else if(p == "parent"){
				if(Utils.$(oConfig[p])){
					Utils.$(oConfig[p]).appendChild(elm)
				} else {
					document.body.appendChild(elm);
				}
			} else {
				elm.setAttribute(p,oConfig[p]);
			}
		}
		return elm;
	},

	/**
	 * A method to add an event to the onload handler without overwriting prevoiusly set functions
	 * @param	{Function} f The function that is to be attached to the onload queue
	*/
	addLoadEvent:function (f){
		var exi = window.onload;
		if(typeof window.onload != "function"){
			window.onload = f;
		} else {
			window.onload = function() {
				exi();
				f();
			};
		}
	},
	
	zebratize:function (sId){
		var oTable = Utils.$(sId);
		if(oTable != null){
			for(var j=0; tr=oTable.getElementsByTagName("TR")[j]; j++){
				tr.className = j%2==0?"even":"odd";
			}
		}
	},
	
	/**	
	 * Lists all the properties in an object for debug purposes
	 * @param {Node} o The object to inspect
	 * @return A string listing all the properties
	*/
	list:function(o,bWriteToPage){
		var s=[],t;
		for(p in o){
			//if(typeof o[p] == "string" || typeof o[p] == "number" || typeof o[p] == "boolean" || p == "style"){ // dont show the applied functions but parse the style-attribute which is of type "object"
				t = p=="style"?p+": "+o[p].cssText:p+": "+o[p];
				s.push(t);
			//}
		}
		if(bWriteToPage){
			var content = [];
			var tmp = s.sort();
			for(var i=0; i<tmp.length; i++){
				content[i] = tmp[i].replace(/: ([\w\s\:\;\/\%\.\-]+)/gi,": <span style='color:red'>$1</span>");
			}
			Utils.createElement("div",{id:"Utils-debug",style:"border:1px solid red; font:11px Courier New",content:content.join("<br>")});
		} else {
			return r = s.sort().join("\n");
		}
	},
	
	/**
	 * Works like getElementsByTagName
	 * Would have been nice to do a Object.prototype.getElementsByClassName instead, but then we have no IE-support. Looks for the passed string in the nodes class="" attribute, so the function will also return the element if it has multible selectors like: class="section info"
	 * @param {Node} oParent The object in which you wish to find the elments
	 * @param {String} sClassName The name of the class attribute you wish to find
	 * @returns An array of elements
	*/
	getElementsByClassName:function(oParent,sClassName){
		var aNodes = oParent.getElementsByTagName("*");
		var aRet = [];
		if(aNodes.length > 0){
			for(var i=0; i<aNodes.length; i++){
				var sTmp = "#" + aNodes[i].className + "#";
				var sRegEx = "[ |#]" + sClassName + "[ |#]";
				if(sTmp.match(new RegExp(sRegEx))){ 
					aRet.push(aNodes[i]);
				}
			}
			return aRet;
		} else {
			return false;
		}
	},
	
	/**
	 * 
	*/
	Page: {
		
		resizeLeftMenu:function (){
			if(Utils.$("col-left-nav")){
				try { Utils.$("col-left-nav").style.height = "auto"; Utils.$("col-left-nav").style.height = (Utils.$("grid").offsetHeight) + "px"; } catch(e) {}
			}
		}, // @Utils.Page.resizeLeftMenu
		
		emulateCSSMinHeight:function (){
			var aDivs = document.getElementsByTagName("DIV");
			var s = "";
			for(var i=0; i<aDivs.length; i++){
				var o=aDivs[i];
				if(o.currentStyle){
					if(o.currentStyle.minHeight && o.currentStyle.minHeight != "auto"){
						o.style.height = o.currentStyle.minHeight;
					}
				}
			}
		}, // @Utils.Page.emulateCSSMinHeight
		
		setCampaignLinks:function (){
			Utils.Page.Logger.add("setCampaignLinks");
			
			/**
			 * 
			*/
			var aCamps = Utils.getElementsByClassName(document,"add-link");
			for(var i=0; i<aCamps.length; i++){
				var o = aCamps[i];
					
				/**
				 * Get the first link in the webpart
				*/
				var aLinks = o.getElementsByTagName("A");
		
				if(aLinks[1]){
					Utils.addClassName(o,"link-cursor");
					
					o.setAttribute("href",aLinks[1].getAttribute("href"));
	
					o.onmouseover = function (e){ // event mouseover
						// show the link address in the browsers status bar, so it looks like a regular HTML link
						window.status = this.getAttribute("href");
					}
	
					o.onmouseout = function (){ // event mouseout
						window.status = window.defaultStatus; 
					}
	
					o.onclick = function (){ // event click
						document.location.href = this.getAttribute("href"); 
					}
						
					/**
					 * Nuke all links in the campaign
					*/
					var aLinks = o.getElementsByTagName("A");
					if(aLinks.length > 0){
						for(var p=0; p<aLinks.length; p++){
							aLinks[p].removeAttribute("href");
							Utils.addClassName(aLinks[p],"clean");  /** some browsers still underlines the link when mousing over, so add a class that removes the underline */
						}
					}
				}
			}
		}, // @Utils.Page.setCampaignLinks
		
		createAccessiblePopupLinks:function (){
			var aElms = Utils.getElementsByClassName(document,"popup");
			var dims = {
			    popup:{w:710,h:560},
			    readmore:{w:300,h:300},
			    def:{w:100,h:100},
			    conditions:{w:800,h:800}
			};
			var currentDims;
			for(var i=0; i<aElms.length; i++){
				var o=aElms[i];
				var sHref = o.getAttribute("href");
				o.setAttribute("savedHrefAtt",sHref); // save the href attribute so we can use it in the window.open()
				o.onclick = function (){
					if(sHref != "#" && sHref != ""){
						if(!win){
						    if(o.className.indexOf("popup") != -1){
						        currentDims = "popup";
						    } else if(o.className.indexOf("readmore") != -1){
						        currentDims = "readmore";
						    } else if(o.className.indexOf("conditions") != -1) {
						        currentDims = "conditions";
						    } else {
						        currentDims = "def";
						    }
							var win = window.open(this.getAttribute("savedHrefAtt"),"Region H","width="+dims[currentDims].w+",height="+dims[currentDims].h);
						} else {
							win.focus();
						}
						return false; 
					}
				};
			}
		}, // @Utils.Page.createAccessiblePopupLinks
		
		Stylesheet:{
			o:function (){ return Utils.$("ss-fonts-large"); },
			oPrintPreview:function (){ return Utils.$("ss-print-preview"); },
			btn:function (){ return Utils.getElementsByClassName(Utils.$("top-nav"),"btn-fontchange")[0]; },
			btnText:[2],
			initialize:function (){
				if(this.o() && Utils.Page.Stylesheet.btn()){
					this.btnText[0] = Utils.Page.Stylesheet.btn().innerHTML;
					this.btnText[1] = Utils.Page.Stylesheet.btn().getAttribute("rel");
					this.o().disabled = true;
					this.buttons();
					if(Utils.Page.Cookie.read("FRKstyle") == "large"){
						this.enable();
					} else {
						this.disable();
					}
				}
				if(this.oPrintPreview()){
					this.oPrintPreview().disabled = true;
				}
			},
			buttons:function (){
				if(this.btn()) this.btn().onclick = this.toggle;
			},
			toggle:function (){
				if(Utils.Page.Stylesheet.btn().getAttribute("isenabled") == "true"){
					Utils.Page.Stylesheet.disable();
				} else if(Utils.Page.Stylesheet.btn().getAttribute("isenabled") == "false"){
					Utils.Page.Stylesheet.enable();
				}
				return false;
			},
			disable:function (){
				this.o().disabled = true;
				Utils.Page.Stylesheet.btn().setAttribute("isenabled","false");
				Utils.Page.Stylesheet.btn().setAttribute("rel",this.btnText[1]);
				Utils.Page.Cookie.create("FRKstyle","small",365);
				Utils.Page.Stylesheet.btn().innerHTML = this.btnText[0];
				Utils.Page.resizeLeftMenu();
			},
			enable:function (){
				this.o().disabled = false;
				Utils.Page.Stylesheet.btn().setAttribute("isenabled","true");
				Utils.Page.Stylesheet.btn().setAttribute("rel",this.btnText[0]);
				Utils.Page.Cookie.create("FRKstyle","large",365);
				Utils.Page.Stylesheet.btn().innerHTML = this.btnText[1];
				Utils.Page.resizeLeftMenu();
			},
			enablePrintPreview:function (){
				Utils.Page.Stylesheet.oPrintPreview().disabled = false;
				Utils.$("cancel-print-preview").onclick = Utils.Page.Stylesheet.disablePrintPreview;
                // set the possibility to cancel the printpreview by pressing <ESC>
                function enableEscPress(e){
                        var code;
                        if (!e) var e = window.event;
                        if(e.keyCode){
                                code = e.keyCode;
                        } else if(e.which){
                                code = e.which;
                        }
                        if(code == 27){
                                Utils.Page.Stylesheet.disablePrintPreview();
                        }
                };
                if(typeof document.onkeyup == "function"){
                    document.onkeyup = function (e){
                        //document.onkeyup();
                        enableEscPress(e);
                    }
                } else {
                    document.onkeyup = function (e){ enableEscPress(e); }
                }
			},
			disablePrintPreview:function (){
				Utils.Page.Stylesheet.oPrintPreview().disabled = true;
				return false;
			}
		}, // @Utils.Page.Stylesheet

		Cookie:{
			create:function(name,value,days){
				if(days){
					var date = new Date();
					date.setTime(date.getTime()+(days*24*60*60*1000));
					var expires = "; expires="+date.toGMTString();
				} else {
					expires = "";
				}
				document.cookie = name+"="+value+expires+"; path=/";
			},
			read:function(name){
				var nameEQ = name + "=";
				var ca = document.cookie.split(';');
				for(var i=0; i<ca.length; i++){
					var c = ca[i];
					while (c.charAt(0)==' ') c = c.substring(1,c.length);
					if(c.indexOf(nameEQ)==0) return c.substring(nameEQ.length,c.length);
				}
				return null;
			}
		}, // @Utils.Page.Cookie
		Print:{
			button:function (){
				if(Utils.$("top-nav")){ 
					var btn = Utils.getElementsByClassName(Utils.$("top-nav"),"btn-print")[0];
					if(btn) btn.onclick = this.preview;
				}
			},
			preview:function(){
				//Utils.Page.Stylesheet.enablePrintPreview();
				try { window.print(); } catch(e){} // mac ie dont support window.print(), the user must press the print button in the browser, so just die gracefully
				return false;
			}
		}, // @Utils.Page.Print
		
		Logger:{
			initialized:false,
			init:function (){
				var o = Utils.createElement("DIV",{id:"Utils-logger",style:"border:3px solid red; background-color:#fff; position:fixed; right:0; top:0"});
				var oList = Utils.createElement("UL",{id:"Utils-logger-list"});
				o.appendChild(oList);
				this.initialized = true;
			},
			add:function (sMessage){
				if(this.initialized){
					var o = Utils.createElement("LI");
					var oText = document.createTextNode(sMessage);
					o.appendChild(oText);
					document.getElementById("Utils-logger-list").appendChild(o);
				}
			}
		}, // @Utils.Page.Logger
		
		start:function (){
            
			/**
			 * 
			*/
			Utils.extend(Columns);
			Utils.Columns.init();

			/**
			 * 
			*/
			if(document.location.href.indexOf("debug") != -1){
				Utils.Page.Logger.init();
			}
			
			/**
			 * Initializes the print button.
			*/
			Utils.Page.Print.button();
			
			/**
			 * Sets the preferred stylesheet based on user cookie and 
			 * sets onclick handlers on the buttons for changing stylesheets.
			*/
			Utils.Page.Stylesheet.initialize();
			
			/**
			 * Add links to all relevant campaigns
			*/
			Utils.Page.setCampaignLinks();
			
			/**
			 * Resize the height of the left menu to stretch to 100%
			*/
			Utils.Page.resizeLeftMenu();
			
			/**
			 * Creates accessible popup links
			*/
			Utils.Page.createAccessiblePopupLinks();
			
			//Utils.Page.emulateCSSMinHeight();
		} // @Utils.Page.start
				
	} // @Utils.Page
} // @Utils

Utils.addLoadEvent(Utils.Page.start);

String.prototype.trim = function() {
    return this.replace( /^\s+|\s+$/, "" ); 
}
if(!Array.push){
	Array.prototype.push = function (k){
		this[this.length] = k;
		return this;
	};
}

/*
 * example of usage of Utils.extend()
var CustomObj = {
	Cat:{
		init:function(){
			alert("this is a function from my NESTED custom object")
		}
	}
};
Utils.extend(CustomObj,Utils.Page);
Utils.Page.Cat.init()
*/


var Columns = {
	Columns:{
		init:function (){
			var oUL = Utils.$("subscribe-list");
			if(oUL){ // only continue if the subscriptions list is present in the document
				var oMother = Utils.$("col-list");
				var aChannels = [];
				var activeArrayKey = -1;
				for(var i=0; i<oUL.childNodes.length; i++){
					if(oUL.childNodes[i].nodeName == "LI"){
						if(oUL.childNodes[i].className.indexOf("channeltop") != -1){
							aChannels.push([]); // create new array for every topchannel we get
							activeArrayKey++;
						}
						aChannels[activeArrayKey].push(oUL.childNodes[i]); // push nodes belonging to the current channel into the array
					}
				}
				oMother.removeChild(oUL); // delete the original node from the document
				for(var i=0; i<aChannels.length; i++){ // for every channel create a wrapper div and a new <ul> and put all the <li>'s into it
					var oCol = Utils.createElement("DIV",{id:"main-channel-"+i,CSSClass:"dyncol",parent:"col-list"});
					var oULNew = Utils.createElement("UL",{parent:"main-channel-"+i});
					for(var j=0; j<aChannels[i].length; j++){
						oULNew.appendChild(aChannels[i][j]);
					}
				}
				var oFF = Utils.createElement("DIV",{CSSClass:"float-fix"});
				oMother.appendChild(oFF);
				oMother.style.height = oMother.offsetHeight+20+"px";
			}
		}
	}
};





