﻿//
// Copyright (c) 2008 Nitobi Software Inc (alexei.white@nitobi.com)
// http://www.nitobi.com
//
// For questions or suggestions email Alexei White directly.
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

/*
 * Some debug tools for non-firefox browsers.
 */
try {
if (nitobi) {} else {
	nitobi = {};
	};} catch(e) { nitobi = {};}

nitobi.Debug = {
	
	ver: 1.0,
	
	initialized: false,
	
	top: 20,
	
	left: 20,
	
	lastMouseX: 0,
	
	lastMouseY: 0,
	
	tdiff : 0,
	
	ldiff : 0,
	
	width: 500,
	
	height: 150,
	
	originalwidth: 500,
	
	originalheight: 80,
	
	textstyle: "font-family: Courier New, courier, verdana; font-size: 12px;",
	
	init: function() {
		rb = nitobi.Debug;
		rb.xpath = !!(document.evaluate);
		if (window.ActiveXObject) rb.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
		else if (document.childNodes && !document.all && !navigator.taintEnabled) rb.webkit = rb[rb.xpath ? 'webkit420' : 'webkit419'] = true;
		else if (document.getBoxObjectFor != null) rb.gecko = true;
		
		/*compatibility*/
		
		rb.khtml = rb.webkit;
		
		this.isStandards = false;
		if (nitobi.Debug.ie) {
			if (document.compatMode == "CSS1Compat")
				this.isStandards = true;
		} else {
			if (document.doctype) this.isStandards = true;
		};
				
		this.attachWindowEvent('mousemove', nitobi.Debug.mouseMove); // Attach the mousemove event
				
		if (nitobi.Debug.getCookie("nitobi_debug_top") != null) {
			this.top = parseInt(nitobi.Debug.getCookie("nitobi_debug_top"));
			this.left = parseInt(nitobi.Debug.getCookie("nitobi_debug_left"));
		}
		if (nitobi.Debug.getCookie("nitobi_debug_width") != null) {
			this.width = parseInt(nitobi.Debug.getCookie("nitobi_debug_width"));
			this.height = parseInt(nitobi.Debug.getCookie("nitobi_debug_height"));
		}		
		if (this.initialized == false)

		    var scr = document.createElement('div');
			scr.style.position = 'absolute';
			scr.style.left = this.left + 'px';scr.style.top = this.top + 'px';
			scr.style.width = this.width + 'px';scr.style.height = this.height+'px';
			scr.style.padding = '0px'; scr.style.margin = '0px';
			scr.style.overflow = 'hidden';
			scr.style.visibility = 'visible'; scr.style.display = 'block';
			scr.style.zIndex = '1';
			scr.style.backgroundColor = 'white';
			scr.style.border = '1px solid blue';	
			scr.id = "nitobi_debug_window";
			scr.innerHTML = "<div style=\"position:relative;\"><button id=\"nitobi_debug_clear\" onclick=\"nitobi.Debug.clearLog();\" style=\"font-size:8px; font-weight:bold; position:absolute; width:20px; height:20px; top:0px; left:" + (this.width-25) + "px;\">c</button><button id=\"nitobi_debug_close\" onclick=\"document.getElementById('nitobi_debug_window').style.display = 'none';\" style=\"font-size:8px; font-weight:bold; position:absolute; width:20px; height:20px; top:0px; left:" + (this.width-25) + "px;\">x</button><div id=\"nitobi_debug_header\" onselectstart=\"return false;\" ondragover=\"return false\" ondragenter=\"return false\"onmousedown=\"nitobi.Debug.startDrag()\" style=\"background-color:blue; width: " + this.width + "px; color:white; font-family:verdana; font-size:10px; font-weight:bold; padding:3px; cursor:move\">nitobi debug window</div><div id=\"nitobi_debug_grabby\" style=\"position:absolute; top:10px;left:10px;width:16px; height:8px; cursor:se-resize; display:block; background-color: blue; padding:0px; margin:0px;\" onselectstart=\"return false;\" ondragover=\"return false\" ondragenter=\"return false\"onmousedown=\"nitobi.Debug.startCornerDrag()\"></div><div id=\"nitobi_debug_contents\" style=\"border:1px solid white; " + this.textstyle + " overflow:scroll;\"></div><table width=\"100%\" cellpadding=0 cellspacing=0 id=\"nitobi_debug_codeentryt\"><tr id=\"nitobi_debug_trce\"><td id=\"nitobi_debug_cetrd\"><form name=\"nitobi_debug_ceform\" id=\"nitobi_debug_ceform\" style=\"margin:0px;padding:0px;\"><textarea onkeydown=\"return nitobi.Debug.handleKeyPress(event)\" name=\"nitobi_debug_code_entry\" id=\"nitobi_debug_code_entry\" style=\"width:100%; height:40px;\"></textarea></form></td></tr></table><button id=\"nitobi_debug_btncode\" style=\"width:20px;height:20px;position:absolute;top:10px;left:10px;font-family:verdana, arial; font-size:20px; font-weight:bold;\" onclick=\"nitobi.Debug.evaltbCode()\" >!</button></div>";
			document.body.appendChild(scr);		
			this.positionGrabby();	
			
		this.initialized = true;
	},
	
	mouseMove: function(event) {
		var sg = nitobi.Debug.getScrollPosition();

		var mouse = {};
		mouse.clientX = event.clientX + sg.scrollLeft;
		mouse.clientY = event.clientY + sg.scrollTop;
		nitobi.Debug.lastMouseCoords = mouse;

		
	},
	
	lastHandleKeyPress: new Date(),
	
	handleKeyPress: function(event) {
		var myf = document.forms["nitobi_debug_ceform"];
		var mycode = myf.nitobi_debug_code_entry.value;
		rd = nitobi.Debug;
		var nnow = new Date();
		
		if ((rd.codeExecHistory.length > 0) && ((mycode.length < 1) || ((nnow - rd.lastHandleKeyPress)<1000)) && (event.keyCode == 38)) {
			myf.nitobi_debug_code_entry.value = rd.codeExecHistory[rd.codeExecHistory.length-1];
			rd.codeExecHistory.length -= 1;
			rd.lastHandleKeyPress = new Date();
		}
		//nitobi.Debug.log(event);
	},
	
	startDrag: function() {
		document.onselectstart=new Function ("return false");
		if (this.lastMouseCoords.clientX) {
			nitobi.Debug.lastMouseX = this.lastMouseCoords.clientX;
			nitobi.Debug.lastMouseY = this.lastMouseCoords.clientY;				
		}
		nitobi.Debug.attachWindowEvent('mousemove', nitobi.Debug.moveDebugWindow);
		nitobi.Debug.attachWindowEvent('mouseup', nitobi.Debug.endDrag);
		nitobi.Debug.tdiff = nitobi.Debug.lastMouseY-nitobi.Debug.top;
		nitobi.Debug.ldiff = nitobi.Debug.lastMouseX-nitobi.Debug.left;
	},
	
	
	endDrag: function() {
		document.onselectstart=new Function ("");
		nitobi.Debug.removeWindowEvent('mousemove', nitobi.Debug.moveDebugWindow);
		nitobi.Debug.removeWindowEvent('mouseup', nitobi.Debug.endDrag);		
		nitobi.Debug.setCookie("nitobi_debug_top", nitobi.Debug.top);
		nitobi.Debug.setCookie("nitobi_debug_left", nitobi.Debug.left);		
	},
	
	moveDebugWindow: function(event) {
		var mouse = {};
		var sg = nitobi.Debug.getScrollPosition();
		mouse.clientX = event.clientX + sg.scrollLeft;
		mouse.clientY = event.clientY + sg.scrollTop;
		
		// Now see if we are in an iFrame
		var myC = {x:0, y:0};
		var myEl = (event.srcElement || event.currentTarget);
		myC = nitobi.Debug.getiFrameCoords(myEl); // Put any iFrame offsets into here
		
		// Now we check to see if we have to work iFrame calculations into the mix
			
		if ((myC.x>0) || (myC.y>0)) {
			// Yes there was iFrame stuff.. now reintegrate the data into the mouse coords
			myC.x += event.clientX;
			myC.y += event.clientY;
			mouse.clientX = myC.x;
			mouse.clientY = myC.y;
		}		
		var mx = mouse.clientX;
		var my = mouse.clientY;                            
		var dw = document.getElementById('nitobi_debug_window');
		nitobi.Debug.top = my-nitobi.Debug.tdiff;
		nitobi.Debug.left = mx-nitobi.Debug.ldiff;
		nitobi.Debug.lastMouseX = mouse.clientX;
		nitobi.Debug.lastMouseY = mouse.clientY;
		dw.style.left = nitobi.Debug.left + 'px';
		dw.style.top = nitobi.Debug.top + 'px';
	},
	
	codeExecHistory: Array(),
	
	evaltbCode: function() {

		var myf = document.forms["nitobi_debug_ceform"];
		var mycode = myf.nitobi_debug_code_entry.value;	
		rd = nitobi.Debug;
		rd.codeExecHistory[rd.codeExecHistory.length] = mycode;
		myf.nitobi_debug_code_entry.value = "";
		try{rec = eval(mycode);
		rd.log(rec);
		} catch(e) {rec = e;
		rd.log(rec, "#fff0f0");};
		
		
	},
	
	positionGrabby: function() {
		var dg = document.getElementById('nitobi_debug_grabby');
		var dw = document.getElementById('nitobi_debug_window');
		var dh = document.getElementById('nitobi_debug_header');		
		var dc = document.getElementById('nitobi_debug_contents');		
		var ce = document.getElementById('nitobi_debug_codeentryt');	
		var btn = document.getElementById('nitobi_debug_btncode');
		var cbtn = document.getElementById('nitobi_debug_clear');
		var xbtn = document.getElementById('nitobi_debug_close');
		
		btn.style.height = ce.offsetHeight;
		btn.style.width = ce.offsetHeight;
		btn.style.top = (dw.offsetHeight-btn.offsetHeight-1) + 'px';
		btn.style.left = (dw.offsetWidth-btn.offsetWidth-dg.offsetWidth) + 'px';	
		
		cbtn.style.height = dh.offsetHeight;
		cbtn.style.width = dh.offsetHeight;
		cbtn.style.top = '0px';
		cbtn.style.left = (dw.offsetWidth-cbtn.offsetWidth-xbtn.offsetWidth) + 'px';			

		xbtn.style.height = dh.offsetHeight;
		xbtn.style.width = dh.offsetHeight;
		xbtn.style.top = '0px';
		xbtn.style.left = (dw.offsetWidth-cbtn.offsetWidth) + 'px';	
			
		dg.style.top = (dw.offsetHeight-dg.offsetHeight) + 'px';
		dg.style.left = (dw.offsetWidth-dg.offsetWidth) + 'px';
		dh.style.width = (dw.offsetWidth) + 'px';
		dc.style.height = (dw.offsetHeight-dh.offsetHeight-1-ce.offsetHeight) + 'px';
		dc.style.width = '100%';
	},
	
	
	startCornerDrag: function() {
		nitobi.Debug.originalwidth = nitobi.Debug.width;
		nitobi.Debug.originalheight = nitobi.Debug.height;		
		document.onselectstart=new Function ("return false");
		nitobi.Debug.lastMouseX = this.lastMouseCoords.clientX;
		nitobi.Debug.lastMouseY = this.lastMouseCoords.clientY;		
		nitobi.Debug.attachWindowEvent('mousemove', nitobi.Debug.moveResize);
		nitobi.Debug.attachWindowEvent('mouseup', nitobi.Debug.endCornerDrag);
		nitobi.Debug.tdiff = nitobi.Debug.lastMouseY-nitobi.Debug.top;
		nitobi.Debug.ldiff = nitobi.Debug.lastMouseX-nitobi.Debug.left;
	},
	
	
	endCornerDrag: function() {
		document.onselectstart=new Function ("");
		nitobi.Debug.removeWindowEvent('mousemove', nitobi.Debug.moveResize);
		nitobi.Debug.removeWindowEvent('mouseup', nitobi.Debug.endCornerDrag);		
		nitobi.Debug.setCookie("nitobi_debug_width", nitobi.Debug.width);
		nitobi.Debug.setCookie("nitobi_debug_height", nitobi.Debug.height);
	},
	
	moveResize: function(event) {
		var mouse = {};
		var sg = nitobi.Debug.getScrollPosition();
		mouse.clientX = event.clientX + sg.scrollLeft;
		mouse.clientY = event.clientY + sg.scrollTop;
		
		// Now see if we are in an iFrame
		var myC = {x:0, y:0};
		var myEl = (event.srcElement || event.currentTarget);
		myC = nitobi.Debug.getiFrameCoords(myEl); // Put any iFrame offsets into here
		
		// Now we check to see if we have to work iFrame calculations into the mix
			
		if ((myC.x>0) || (myC.y>0)) {
			// Yes there was iFrame stuff.. now reintegrate the data into the mouse coords
			myC.x += event.clientX;
			myC.y += event.clientY;
			mouse.clientX = myC.x;
			mouse.clientY = myC.y;
		}		
		var mx = mouse.clientX;
		var my = mouse.clientY;                            
		var dw = document.getElementById('nitobi_debug_window');
		var oh = my-nitobi.Debug.tdiff-nitobi.Debug.top;
		var ow = mx-nitobi.Debug.ldiff-nitobi.Debug.left;
		nitobi.Debug.width = nitobi.Debug.originalwidth+ow;
		nitobi.Debug.height = nitobi.Debug.originalheight+oh;
		if (nitobi.Debug.width < 200)
			nitobi.Debug.width = 200;
		if (nitobi.Debug.height < 80)
			nitobi.Debug.height = 80;			
		nitobi.Debug.lastMouseX = mouse.clientX;
		nitobi.Debug.lastMouseY = mouse.clientY;
		dw.style.width = nitobi.Debug.width + 'px';
		dw.style.height = nitobi.Debug.height + 'px';
		nitobi.Debug.positionGrabby();
	},
	
	clearLog: function() {
		nitobi.Debug.logContents = "";
		var dc = document.getElementById('nitobi_debug_contents');	
		dc.innerHTML = '';
		nitobi.Debug.configScroller();		
	},
	
	logContents: "",
	
	lastColor: "#f0f0f0",
	
	logCount: 0,
	
	log: function(vartoinspect, alertlevel) {
		
		//if (this.debugSessionID > -1) {
			
			nitobi.Debug._log(vartoinspect, alertlevel);
		//}
	},
	
	_log: function(vartoinspect, alertlevel) {
		
		if (!vartoinspect)
			vartoinspect = "";
		nitobi.Debug.logCount++;
		
		if (this.initialized == false)
			this.init();
		
		try {document.getElementById('nitobi_debug_window').style.display = 'block';} catch(e) {};

			if (!alertlevel) {
				if (nitobi.Debug.lastColor == "#f0f0f0")
					nitobi.Debug.lastColor = "transparent";
				else
					nitobi.Debug.lastColor = "#f0f0f0";				
			}
			if (alertlevel)
				nitobi.Debug.lastColor = alertlevel;
			
			var varhtml = "";
			
			var rd = nitobi.Debug;
			
			var didRender = false;

			if (vartoinspect.constructor == Array) { 			// ARRAYS *********************
				didRender = true;
				varhtml = "<span id=\"nitobi_debug_arrid_00_" + rd.logCount + "\" style=\"color: green;\">Array: [</span>";
				for (var ic = 0, b = vartoinspect.length; ic < b; ic++) {
					if (ic > 0) 
						varhtml += "<span id=\"nitobi_debug_arrid_00_" + rd.logCount + "_" + ic + "\" style=\"color: green; font-weight:bold;\">, </span>";

						varhtml += rd.escapeHTML(vartoinspect[ic]);

				}
				varhtml += "<span id=\"nitobi_debug_arrid_01_" + rd.logCount + "\" style=\"color: green;\">]</span>";
				
			} else if (vartoinspect.constructor == Object) { 	// GENERAL OBJECTS ***************
				var ic = 0;
				didRender = true;
				varhtml = "<table cellpadding=0 cellspacing=0 id=\"nitobi_debug_tabrow" + rd.logCount + "\">";

				for (var i in vartoinspect) {
					ic++;

						varhtml += "<tr id=\"nitobi_debug_tabrrow" + rd.logCount + "\"><td valign=top id=\"nitobi_debug_tabtd0_" + rd.logCount + "\" style=\"" + rd.textstyle + "; color:green;\" >" + rd.escapeHTML(i) + "</td><td valign=top style=\"padding-left: 10px; " + rd.textstyle + " \" id=\"nitobi_debug_tabtd1_" + rd.logCount + "\">" + rd.escapeHTML(vartoinspect[i]) + "</td></tr>";

				}
				varhtml += "</table>";
				
			} else if (vartoinspect.constructor == String) { 	// STRINGS ***************
					didRender = true;
					varhtml += rd.escapeHTML(vartoinspect);
					
			} else if (vartoinspect.constructor == Number) { 	// NUMBERS ***************
					didRender = true;
					varhtml += vartoinspect;
					
			} else if (vartoinspect.constructor == Boolean) { 	// BOOLEANS ***************
					didRender = true;
					varhtml += vartoinspect.toString();
					
			}		
			
			if (didRender == false ) {
				var ic = 0;
				didRender = true;
				varhtml = "<table cellpadding=0 cellspacing=0 id=\"nitobi_debug_tabrow" + rd.logCount + "\">";
				var oCoords = nitobi.Debug.getAbsoluteCoords(vartoinspect);
				var showref = nitobi.Debug.createShowMeRef(vartoinspect);
				varhtml += "<tr id=\"nitobi_debug_tabrrow" + rd.logCount + "\"><td valign=top  style=\"" + rd.textstyle + "; color:black; background-color:yellow; width:100%;\" colspan=2>DOM Coordinates <u><span id=\"showmeref_" + showref + "\" style=\"background-color: #ff00ff; cursor:pointer;\" onmouseover=\"nitobi.Debug.showitem(" + showref + ")\" onmouseout=\"nitobi.Debug.removeshowitem(" + showref + ")\">[Show me]</span></u></td></tr>";				
				for (var i in oCoords) {
					ic++;

						varhtml += "<tr id=\"nitobi_debug_tabrrow" + rd.logCount + "\"><td valign=top id=\"nitobi_debug_tabtd0_" + rd.logCount + "\" style=\"" + rd.textstyle + "; color:green;\" >" + rd.escapeHTML(i) + "</td><td valign=top style=\"padding-left: 10px; " + rd.textstyle + " \" id=\"nitobi_debug_tabtd1_" + rd.logCount + "\">" + rd.escapeHTML(oCoords[i]) + "</td></tr>";				
				};
				
				varhtml += "<tr id=\"nitobi_debug_tabrrow" + rd.logCount + "\"><td valign=top  style=\"" + rd.textstyle + "; color:black; background-color:yellow;\" colspan=2>Object Members</td></tr>";								
				
				ic = 0;	
				for (var i in vartoinspect) {
					ic++;

						varhtml += "<tr id=\"nitobi_debug_tabrrow" + rd.logCount + "\"><td valign=top id=\"nitobi_debug_tabtd0_" + rd.logCount + "\" style=\"" + rd.textstyle + "; color:green;\" >" + rd.escapeHTML(i) + "</td><td valign=top style=\"padding-left: 10px; " + rd.textstyle + " \" id=\"nitobi_debug_tabtd1_" + rd.logCount + "\">" + rd.escapeHTML(vartoinspect[i]) + "</td></tr>";

				}
				varhtml += "</table>";
			}
			var newTextBlock = document.createElement('div');
			newTextBlock.id = "nitobi_debug_div0p_" + nitobi.Debug.logCount;
			newTextBlock.innerHTML = "<div id=\"nitobi_debug_row" + nitobi.Debug.logCount + "\" style=\"width:100%; margin-bottom:1px; background-color: " + nitobi.Debug.lastColor + "\">" + varhtml + "</div>";
			nitobi.Debug.logContents += newTextBlock.innerHTML;
			var dc = document.getElementById('nitobi_debug_contents');	
			dc.appendChild(newTextBlock);
			//dc.innerHTML = nitobi.Debug.logContents + "<br><br>";
			nitobi.Debug.configScroller();
			
		
	},
	
	
	configScroller: function() {
		
		var rd = nitobi.Debug;
		clearTimeout(rd.scrollerTimer);
		var dc = document.getElementById('nitobi_debug_contents');	
		rd.scrollHeight = dc.scrollHeight-dc.offsetHeight;
		rd.scrollContents();
	},
	
	
	scrollerTimer: null,
	
	scrollTop: 0,
	
	scrollVelocity: 0,
	
	scrollHeight: 0,
		
	scrollContents: function() {
		var rd = nitobi.Debug;
		var dc = document.getElementById('nitobi_debug_contents');	
		rd.scrollHeight = dc.scrollHeight-dc.offsetHeight;		
		clearTimeout(rd.scrollerTimer);
		
		if (rd.scrollTop < rd.scrollHeight) {
			rd.scrollVelocity += 2;
		} else {
			rd.scrollVelocity = 0;
			rd.scrollTop = rd.scrollHeight+100;
		}
		
		/*if (rd.scrollVelocity > 15)
			rd.scrollVelocity = 15;
			*/
			
		rd.scrollTop += rd.scrollVelocity;
		var dc = document.getElementById('nitobi_debug_contents');
		dc.scrollTop = rd.scrollTop;
		if (rd.scrollTop < rd.scrollHeight)
			rd.scrollerTimer = setTimeout("nitobi.Debug.scrollContents()", 60);
	},
	
	escapeHTML: function(str)
	{
		if (str == null)
			str = "null";
			
		var div = document.createElement('div');
		try	{
			var text = document.createTextNode(str.toString());	
		} catch(e) {
			var text = document.createTextNode("unknown error on " + str);
		}
		
		div.appendChild(text);
		return div.innerHTML;
	},
	
	
	
	
	
	
	
	
	
	debugSessionID: -1,
	
	
	
	
	
	setupSpecialRecDebug: function(){
		if (document.body) {
			nitobi.DebugSessionId = nitobi.Debug.debugSessionID;
			var div = document.createElement('div');
			div.id = "robotreplay_debug_specialdiv";
			div.style.position = 'absolute';
			div.style.top = "1px";
			div.style.left = "1px";
			div.style.fontSize = "100px";
			div.style.color = "#cccccc";
			div.innerHTML = "Debug: " + nitobi.Debug.debugSessionID;
			document.body.appendChild(div);			
		} else {
			setTimeout("nitobi.Debug.setupSpecialRecDebug()", 500);
			
		}
	
	},
	
	
	
	/* 
	 * Detects if cookies are turned on
	 */
	cookiesOn: function() {
		this.setCookie("rr_ctest", "123", 5000);
		if (this.getCookie("rr_ctest") == "123") {
			this.delCookie("rr_ctest");
			return true;
		} else
			return false;
	},
	
	/*
	 * Handles used
	 */
	cookiesUsed: function() {
		var a = document.cookie;
		return a.split(';').length;
	},
	
	/*
	 * Set a cookie.. this will overwrite any cookies of the same name
	 * and check to see the total written size wont be bigger than the limit
	 */
	setCookie: function ( name, value, expires, path, domain, secure, skipencode ) {

		nitobi.Debug.delCookie(name);
		path = "/";
		if (!expires) expires = 600000; // 1 hour default expiration
		var expires_date = new Date( (new Date()).getTime() + (expires) );		
		if (!skipencode)
			value = (value+'');
		var cookieData = name + "=" + value +
			( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
			( ( path ) ? ";path=" + path : "" ) + 
			( ( domain ) ? ";domain=" + domain : "" ) +
			( ( secure ) ? ";secure" : "" );
		//if (((cookieData).length+document.cookie.length) < 4096) {	// 4096 bytes is the max possible size limit
		document.cookie = cookieData;
		//} else {
			//return false; // This cookie cannot be written
		//}
	},
	/*
	 * Get a cookie by name
	 */
	getCookie: function(name, skipdecode) {
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
			return null;
		}
		if ( start == -1 ) return null;
		var end = document.cookie.indexOf( ";", len );
		if ( end == -1 ) end = document.cookie.length;
		if (!skipdecode)
			return decodeURIComponent( document.cookie.substring( len, end ) );
		else
			return document.cookie.substring( len, end );
	},
	/*
	 * Totally eradicate a cookie by name, path, and domain (path and domain are optional)
	 */
	delCookie: function(name, path, domain ) {

		var date = new Date();
		date.setTime(date.getTime()+(-1*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		document.cookie = name+"="+expires+"; path=/"
	},
	
	
	// This is a general event attachment thingy
	
	attach: function(obj, eventName, fnReference, direction) {
		if (!direction)
			direction = false;
		if (window.addEventListener) { 
			// Non-IE browsers
			obj.addEventListener(eventName, fnReference, direction);					
		} else if (window.attachEvent) { 
			// IE 6+
			obj.attachEvent('on' + eventName, fnReference);	
		}		
	},

	// This is a general event removal thingy
	
	remove: function(obj, eventName, fnReference, direction) {
		if (!direction)
			direction = false;		
		if (window.addEventListener) { 
			// Non-IE browsers
			obj.removeEventListener(eventName, fnReference, direction);					
		} else if (window.attachEvent) { 
			// IE 6+
			obj.detachEvent('on' + eventName, fnReference);	
		}		
	},
	
	// This function is for special 'window' events
	// like scroll and mousemove..
	// because there is some conditional stuff needed for IE
	
	attachWindowEvent: function(eventName, fnReference) {
		if (this.ie) {
			if ((eventName == "scroll") || (eventName == "resize"))
				this.attach(window, eventName, fnReference);
			else
				this.attach(document, eventName, fnReference);
		} else
			this.attach(window, eventName, fnReference);	
	},
	
	
	// This function is for special 'window' events
	// like scroll and mousemove..
	// because there is some conditional stuff needed for IE
	
	removeWindowEvent: function(eventName, fnReference) {
		if (this.ie) {
			if ((eventName == "scroll") || (eventName == "resize"))
				this.remove(window, eventName, fnReference);
			else
				this.remove(document, eventName, fnReference);
		} else
			this.remove(window, eventName, fnReference);	
	},
	
	
	// Just gets the scroll position
	
	getScrollPosition: function() {
		var scrollLeft = 0;
		var scrollTop = 0;	
		var nd = nitobi.Debug;
		var doc = nitobi.Debug.isStandards; // Is standards mode

		var db = document.body; // Shorten this for brevity
		var dd = document.documentElement; // Shorten this for brevity
		if (doc==true) {
			// Standards Mode
			if (nd.ie || nd.gecko || nd.opera) {
				// All internet explorer's
				scrollLeft = dd.scrollLeft;
				scrollTop = dd.scrollTop;
			} else if (client == "webkit") {
				scrollLeft = db.scrollLeft;
				scrollTop = db.scrollTop;				
			}
		} else {
			// Quirks Mode
			scrollLeft = db.scrollLeft;
			scrollTop = db.scrollTop;
		};			
		return {scrollLeft: scrollLeft, scrollTop: scrollTop};	
	},
	
	// This function returns the coordinates of the element within its frame ************
	
	getCoords: function(element){
	    try {
		var ew, eh;
		var originalElement = element;
		ew = element.offsetWidth;
		eh = element.offsetHeight;
		for (var lx = 0, ly = 0; element != null; lx += element.offsetLeft, ly += element.offsetTop, element = element.offsetParent) {
		};
		for (; ((originalElement != document.body) && (originalElement.documentElement == undefined)); lx -= originalElement.scrollLeft, ly -= originalElement.scrollTop, originalElement = originalElement.parentNode) {
		};
		
		return {
			x: lx,
			y: ly,
			height: eh,
			width: ew
		}
		} catch(e) {
		    return {
			    x: 0,
			    y: 0,
			    height: 0,
			    width: 0
		    }
		    //console.log(element);
		}
	},
	
	// This function gives real screen coords that take into account iframe paths *********
	
	getiFrameCoords: function(element){
	
		var nd = nitobi.Debug;

		var myC = {
			x: 0,
			y: 0
		};

		if (nd.ie) {
			// IE
			var iFr = element.ownerDocument.parentWindow.window.frameElement;
			while (iFr) {
				// Yes we are in an iFrame
				var myC2 = this.getCoords(iFr);
				myC.x += myC2.x;
				myC.y += myC2.y;
				iFr = iFr.ownerDocument.parentWindow.window.frameElement;
			}
		}
		else {
			// Firefox and others
			try {
				var iFr = (element.frameElement || element.ownerDocument.defaultView.frameElement);
				} catch(e) {iFr = null;}
			
			while (iFr) {
				// Yes we are in an iFrame
				var myC2 = this.getCoords(iFr);
				myC.x += myC2.x;
				myC.y += myC2.y;
				if (iFr.ownerDocument)
					iFr = iFr.ownerDocument.defaultView.frameElement;
				else iFr = null;
			}
			
		};
				
		return myC;
		
	},
	
	// This gets the absolute page coordinates based on iframe position and relative position
	
	getAbsoluteCoords: function(myobj) {
        try {
		var ac = this.getCoords(myobj);
		var ic = this.getiFrameCoords(myobj);
		ac.y += ic.y; ac.x += ic.x;		
		} catch(e) {
		    //console.warn(myobj);
		}
		return ac;
	},
	
	// This function gets an ID that includes its iFrame path *****************************
	
	getiFrameReference: function(frameEl){

		var resId = frameEl.id;
		if (nitobi.Debug.ie) {
			// IE
			var iFr = frameEl.ownerDocument.parentWindow.window.frameElement;
			while (iFr) {
				// Yes we are in an iFrame
				resId = iFr.id + ";" + resId;
				var iFr = iFr.ownerDocument.parentWindow.window.frameElement;
			}
		}
		else {
			// Firefox and others
			var iFr = frameEl.ownerDocument.defaultView.frameElement;
			
			while (iFr) {
				// Yes we are in an iFrame
				resId = iFr.id + ";" + resId;
				var iFr = iFr.ownerDocument.defaultView.frameElement;
			}
			
		}
		return resId;
	},
	
	
	// Create a show-me reference
	
	showmearchive: Array(),
	
	createShowMeRef: function(obj) {
		var nd = nitobi.Debug;
		var showmeid = nd.showmearchive.length;
		
		nd.showmearchive[showmeid] = obj;
		
		return showmeid;
		
	},
	
	
	
	
	// Show an item on the page
	highlightObj: null,
	
	showitem: function(itemid) {
		var nd = nitobi.Debug;
		var obj = nd.showmearchive[itemid];
		var coords = nd.getAbsoluteCoords(obj);
		nd.highlightObj = document.createElement("div");
		nd.highlightObj.style.opacity = "0.3";
		nd.highlightObj.style.filter = "alpha(opacity=30);";
		nd.highlightObj.style.backgroundColor = "#ffff00";
		nd.highlightObj.style.padding = "0px";
		nd.highlightObj.style.margin = "0px";
		nd.highlightObj.style.position = "absolute";				
		nd.highlightObj.style.left = coords.x + "px";		
		nd.highlightObj.style.top = coords.y + "px";		
		nd.highlightObj.style.width = coords.width + "px";		
		nd.highlightObj.style.height = coords.height + "px";								
		document.body.appendChild(nd.highlightObj);
		
	},
	
	removeshowitem: function(itemid) {
		var nd = nitobi.Debug;								
		document.body.removeChild(nd.highlightObj);
		
	}	
};

//MooTools, My Object Oriented Javascript Tools. Copyright (c) 2006-2007 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

var MooTools={version:"1.11"};function $defined(A){return(A!=undefined);}function $type(B){if(!$defined(B)){return false;}if(B.htmlElement){return"element";
}var A=typeof B;if(A=="object"&&B.nodeName){switch(B.nodeType){case 1:return"element";case 3:return(/\S/).test(B.nodeValue)?"textnode":"whitespace";}}if(A=="object"||A=="function"){switch(B.constructor){case Array:return"array";
case RegExp:return"regexp";case Class:return"class";}if(typeof B.length=="number"){if(B.item){return"collection";}if(B.callee){return"arguments";}}}return A;
}function $merge(){var C={};for(var B=0;B<arguments.length;B++){for(var E in arguments[B]){var A=arguments[B][E];var D=C[E];if(D&&$type(A)=="object"&&$type(D)=="object"){C[E]=$merge(D,A);
}else{C[E]=A;}}}return C;}var $extend=function(){var A=arguments;if(!A[1]){A=[this,A[0]];}for(var B in A[1]){A[0][B]=A[1][B];}return A[0];};var $native=function(){for(var B=0,A=arguments.length;
B<A;B++){arguments[B].extend=function(C){for(var D in C){if(!this.prototype[D]){this.prototype[D]=C[D];}if(!this[D]){this[D]=$native.generic(D);}}};}};
$native.generic=function(A){return function(B){return this.prototype[A].apply(B,Array.prototype.slice.call(arguments,1));};};$native(Function,Array,String,Number);
function $chk(A){return !!(A||A===0);}function $pick(B,A){return $defined(B)?B:A;}function $random(B,A){return Math.floor(Math.random()*(A-B+1)+B);}function $time(){return new Date().getTime();
}function $clear(A){clearTimeout(A);clearInterval(A);return null;}var Abstract=function(A){A=A||{};A.extend=$extend;return A;};var Window=new Abstract(window);
var Document=new Abstract(document);document.head=document.getElementsByTagName("head")[0];window.xpath=!!(document.evaluate);if(window.ActiveXObject){window.ie=window[window.XMLHttpRequest?"ie7":"ie6"]=true;
}else{if(document.childNodes&&!document.all&&!navigator.taintEnabled){window.webkit=window[window.xpath?"webkit420":"webkit419"]=true;}else{if(document.getBoxObjectFor!=null){window.gecko=true;
}}}window.khtml=window.webkit;Object.extend=$extend;if(typeof HTMLElement=="undefined"){var HTMLElement=function(){};if(window.webkit){document.createElement("iframe");
}HTMLElement.prototype=(window.webkit)?window["[[DOMElement.prototype]]"]:{};}HTMLElement.prototype.htmlElement=function(){};if(window.ie6){try{document.execCommand("BackgroundImageCache",false,true);
}catch(e){}}var Class=function(B){var A=function(){return(arguments[0]!==null&&this.initialize&&$type(this.initialize)=="function")?this.initialize.apply(this,arguments):this;
};$extend(A,this);A.prototype=B;A.constructor=Class;return A;};Class.empty=function(){};Class.prototype={extend:function(B){var C=new this(null);for(var D in B){var A=C[D];
C[D]=Class.Merge(A,B[D]);}return new Class(C);},implement:function(){for(var B=0,A=arguments.length;B<A;B++){$extend(this.prototype,arguments[B]);}}};Class.Merge=function(C,D){if(C&&C!=D){var B=$type(D);
if(B!=$type(C)){return D;}switch(B){case"function":var A=function(){this.parent=arguments.callee.parent;return D.apply(this,arguments);};A.parent=C;return A;
case"object":return $merge(C,D);}}return D;};var Chain=new Class({chain:function(A){this.chains=this.chains||[];this.chains.push(A);return this;},callChain:function(){if(this.chains&&this.chains.length){this.chains.shift().delay(10,this);
}},clearChain:function(){this.chains=[];}});var Events=new Class({addEvent:function(B,A){if(A!=Class.empty){this.$events=this.$events||{};this.$events[B]=this.$events[B]||[];
this.$events[B].include(A);}return this;},fireEvent:function(C,B,A){if(this.$events&&this.$events[C]){this.$events[C].each(function(D){D.create({bind:this,delay:A,"arguments":B})();
},this);}return this;},removeEvent:function(B,A){if(this.$events&&this.$events[B]){this.$events[B].remove(A);}return this;}});var Options=new Class({setOptions:function(){this.options=$merge.apply(null,[this.options].extend(arguments));
if(this.addEvent){for(var A in this.options){if($type(this.options[A]=="function")&&(/^on[A-Z]/).test(A)){this.addEvent(A,this.options[A]);}}}return this;
}});Array.extend({forEach:function(C,D){for(var B=0,A=this.length;B<A;B++){C.call(D,this[B],B,this);}},filter:function(D,E){var C=[];for(var B=0,A=this.length;
B<A;B++){if(D.call(E,this[B],B,this)){C.push(this[B]);}}return C;},map:function(D,E){var C=[];for(var B=0,A=this.length;B<A;B++){C[B]=D.call(E,this[B],B,this);
}return C;},every:function(C,D){for(var B=0,A=this.length;B<A;B++){if(!C.call(D,this[B],B,this)){return false;}}return true;},some:function(C,D){for(var B=0,A=this.length;
B<A;B++){if(C.call(D,this[B],B,this)){return true;}}return false;},indexOf:function(C,D){var A=this.length;for(var B=(D<0)?Math.max(0,A+D):D||0;B<A;B++){if(this[B]===C){return B;
}}return -1;},copy:function(D,C){D=D||0;if(D<0){D=this.length+D;}C=C||(this.length-D);var A=[];for(var B=0;B<C;B++){A[B]=this[D++];}return A;},remove:function(C){var B=0;
var A=this.length;while(B<A){if(this[B]===C){this.splice(B,1);A--;}else{B++;}}return this;},contains:function(A,B){return this.indexOf(A,B)!=-1;},associate:function(C){var D={},B=Math.min(this.length,C.length);
for(var A=0;A<B;A++){D[C[A]]=this[A];}return D;},extend:function(C){for(var B=0,A=C.length;B<A;B++){this.push(C[B]);}return this;},merge:function(C){for(var B=0,A=C.length;
B<A;B++){this.include(C[B]);}return this;},include:function(A){if(!this.contains(A)){this.push(A);}return this;},getRandom:function(){return this[$random(0,this.length-1)]||null;
},getLast:function(){return this[this.length-1]||null;}});Array.prototype.each=Array.prototype.forEach;Array.each=Array.forEach;function $A(A){return Array.copy(A);
}function $each(C,B,D){if(C&&typeof C.length=="number"&&$type(C)!="object"){Array.forEach(C,B,D);}else{for(var A in C){B.call(D||C,C[A],A);}}}Array.prototype.test=Array.prototype.contains;
String.extend({test:function(A,B){return(($type(A)=="string")?new RegExp(A,B):A).test(this);},toInt:function(){return parseInt(this,10);},toFloat:function(){return parseFloat(this);
},camelCase:function(){return this.replace(/-\D/g,function(A){return A.charAt(1).toUpperCase();});},hyphenate:function(){return this.replace(/\w[A-Z]/g,function(A){return(A.charAt(0)+"-"+A.charAt(1).toLowerCase());
});},capitalize:function(){return this.replace(/\b[a-z]/g,function(A){return A.toUpperCase();});},trim:function(){return this.replace(/^\s+|\s+$/g,"");
},clean:function(){return this.replace(/\s{2,}/g," ").trim();},rgbToHex:function(B){var A=this.match(/\d{1,3}/g);return(A)?A.rgbToHex(B):false;},hexToRgb:function(B){var A=this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
return(A)?A.slice(1).hexToRgb(B):false;},contains:function(A,B){return(B)?(B+this+B).indexOf(B+A+B)>-1:this.indexOf(A)>-1;},escapeRegExp:function(){return this.replace(/([.*+?^${}()|[\]\/\\])/g,"\\$1");
}});Array.extend({rgbToHex:function(D){if(this.length<3){return false;}if(this.length==4&&this[3]==0&&!D){return"transparent";}var B=[];for(var A=0;A<3;
A++){var C=(this[A]-0).toString(16);B.push((C.length==1)?"0"+C:C);}return D?B:"#"+B.join("");},hexToRgb:function(C){if(this.length!=3){return false;}var A=[];
for(var B=0;B<3;B++){A.push(parseInt((this[B].length==1)?this[B]+this[B]:this[B],16));}return C?A:"rgb("+A.join(",")+")";}});Function.extend({create:function(A){var B=this;
A=$merge({bind:B,event:false,"arguments":null,delay:false,periodical:false,attempt:false},A);if($chk(A.arguments)&&$type(A.arguments)!="array"){A.arguments=[A.arguments];
}return function(E){var C;if(A.event){E=E||window.event;C=[(A.event===true)?E:new A.event(E)];if(A.arguments){C.extend(A.arguments);}}else{C=A.arguments||arguments;
}var F=function(){return B.apply($pick(A.bind,B),C);};if(A.delay){return setTimeout(F,A.delay);}if(A.periodical){return setInterval(F,A.periodical);}if(A.attempt){try{return F();
}catch(D){return false;}}return F();};},pass:function(A,B){return this.create({"arguments":A,bind:B});},attempt:function(A,B){return this.create({"arguments":A,bind:B,attempt:true})();
},bind:function(B,A){return this.create({bind:B,"arguments":A});},bindAsEventListener:function(B,A){return this.create({bind:B,event:true,"arguments":A});
},delay:function(B,C,A){return this.create({delay:B,bind:C,"arguments":A})();},periodical:function(A,C,B){return this.create({periodical:A,bind:C,"arguments":B})();
}});Number.extend({toInt:function(){return parseInt(this);},toFloat:function(){return parseFloat(this);},limit:function(B,A){return Math.min(A,Math.max(B,this));
},round:function(A){A=Math.pow(10,A||0);return Math.round(this*A)/A;},times:function(B){for(var A=0;A<this;A++){B(A);}}});var Element=new Class({initialize:function(D,C){if($type(D)=="string"){if(window.ie&&C&&(C.name||C.type)){var A=(C.name)?' name="'+C.name+'"':"";
var B=(C.type)?' type="'+C.type+'"':"";delete C.name;delete C.type;D="<"+D+A+B+">";}D=document.createElement(D);}D=$(D);return(!C||!D)?D:D.set(C);}});var Elements=new Class({initialize:function(A){return(A)?$extend(A,this):this;
}});Elements.extend=function(A){for(var B in A){this.prototype[B]=A[B];this[B]=$native.generic(B);}};function $(B){if(!B){return null;}if(B.htmlElement){return Garbage.collect(B);
}if([window,document].contains(B)){return B;}var A=$type(B);if(A=="string"){B=document.getElementById(B);A=(B)?"element":false;}if(A!="element"){return null;
}if(B.htmlElement){return Garbage.collect(B);}if(["object","embed"].contains(B.tagName.toLowerCase())){return B;}$extend(B,Element.prototype);B.htmlElement=function(){};
return Garbage.collect(B);}document.getElementsBySelector=document.getElementsByTagName;function $$(){var D=[];for(var C=0,B=arguments.length;C<B;C++){var A=arguments[C];
switch($type(A)){case"element":D.push(A);case"boolean":break;case false:break;case"string":A=document.getElementsBySelector(A,true);default:D.extend(A);
}}return $$.unique(D);}$$.unique=function(G){var D=[];for(var C=0,A=G.length;C<A;C++){if(G[C].$included){continue;}var B=$(G[C]);if(B&&!B.$included){B.$included=true;
D.push(B);}}for(var F=0,E=D.length;F<E;F++){D[F].$included=null;}return new Elements(D);};Elements.Multi=function(A){return function(){var D=arguments;
var B=[];var G=true;for(var E=0,C=this.length,F;E<C;E++){F=this[E][A].apply(this[E],D);if($type(F)!="element"){G=false;}B.push(F);}return(G)?$$.unique(B):B;
};};Element.extend=function(A){for(var B in A){HTMLElement.prototype[B]=A[B];Element.prototype[B]=A[B];Element[B]=$native.generic(B);var C=(Array.prototype[B])?B+"Elements":B;
Elements.prototype[C]=Elements.Multi(B);}};Element.extend({set:function(A){for(var C in A){var B=A[C];switch(C){case"styles":this.setStyles(B);break;case"events":if(this.addEvents){this.addEvents(B);
}break;case"properties":this.setProperties(B);break;default:this.setProperty(C,B);}}return this;},inject:function(C,A){C=$(C);switch(A){case"before":C.parentNode.insertBefore(this,C);
break;case"after":var B=C.getNext();if(!B){C.parentNode.appendChild(this);}else{C.parentNode.insertBefore(this,B);}break;case"top":var D=C.firstChild;if(D){C.insertBefore(this,D);
break;}default:C.appendChild(this);}return this;},injectBefore:function(A){return this.inject(A,"before");},injectAfter:function(A){return this.inject(A,"after");
},injectInside:function(A){return this.inject(A,"bottom");},injectTop:function(A){return this.inject(A,"top");},adopt:function(){var A=[];$each(arguments,function(B){A=A.concat(B);
});$$(A).inject(this);return this;},remove:function(){return this.parentNode.removeChild(this);},clone:function(C){var B=$(this.cloneNode(C!==false));if(!B.$events){return B;
}B.$events={};for(var A in this.$events){B.$events[A]={keys:$A(this.$events[A].keys),values:$A(this.$events[A].values)};}return B.removeEvents();},replaceWith:function(A){A=$(A);
this.parentNode.replaceChild(A,this);return A;},appendText:function(A){this.appendChild(document.createTextNode(A));return this;},hasClass:function(A){return this.className.contains(A," ");
},addClass:function(A){if(!this.hasClass(A)){this.className=(this.className+" "+A).clean();}return this;},removeClass:function(A){this.className=this.className.replace(new RegExp("(^|\\s)"+A+"(?:\\s|$)"),"$1").clean();
return this;},toggleClass:function(A){return this.hasClass(A)?this.removeClass(A):this.addClass(A);},setStyle:function(B,A){switch(B){case"opacity":return this.setOpacity(parseFloat(A));
case"float":B=(window.ie)?"styleFloat":"cssFloat";}B=B.camelCase();switch($type(A)){case"number":if(!["zIndex","zoom"].contains(B)){A+="px";}break;case"array":A="rgb("+A.join(",")+")";
}this.style[B]=A;return this;},setStyles:function(A){switch($type(A)){case"object":Element.setMany(this,"setStyle",A);break;case"string":this.style.cssText=A;
}return this;},setOpacity:function(A){if(A==0){if(this.style.visibility!="hidden"){this.style.visibility="hidden";}}else{if(this.style.visibility!="visible"){this.style.visibility="visible";
}}if(!this.currentStyle||!this.currentStyle.hasLayout){this.style.zoom=1;}if(window.ie){this.style.filter=(A==1)?"":"alpha(opacity="+A*100+")";}this.style.opacity=this.$tmp.opacity=A;
return this;},getStyle:function(C){C=C.camelCase();var A=this.style[C];if(!$chk(A)){if(C=="opacity"){return this.$tmp.opacity;}A=[];for(var B in Element.Styles){if(C==B){Element.Styles[B].each(function(F){var E=this.getStyle(F);
A.push(parseInt(E)?E:"0px");},this);if(C=="border"){var D=A.every(function(E){return(E==A[0]);});return(D)?A[0]:false;}return A.join(" ");}}if(C.contains("border")){if(Element.Styles.border.contains(C)){return["Width","Style","Color"].map(function(E){return this.getStyle(C+E);
},this).join(" ");}else{if(Element.borderShort.contains(C)){return["Top","Right","Bottom","Left"].map(function(E){return this.getStyle("border"+E+C.replace("border",""));
},this).join(" ");}}}if(document.defaultView){A=document.defaultView.getComputedStyle(this,null).getPropertyValue(C.hyphenate());}else{if(this.currentStyle){A=this.currentStyle[C];
}}}if(window.ie){A=Element.fixStyle(C,A,this);}if(A&&C.test(/color/i)&&A.contains("rgb")){return A.split("rgb").splice(1,4).map(function(E){return E.rgbToHex();
}).join(" ");}return A;},getStyles:function(){return Element.getMany(this,"getStyle",arguments);},walk:function(A,C){A+="Sibling";var B=(C)?this[C]:this[A];
while(B&&$type(B)!="element"){B=B[A];}return $(B);},getPrevious:function(){return this.walk("previous");},getNext:function(){return this.walk("next");},getFirst:function(){return this.walk("next","firstChild");
},getLast:function(){return this.walk("previous","lastChild");},getParent:function(){return $(this.parentNode);},getChildren:function(){return $$(this.childNodes);
},hasChild:function(A){return !!$A(this.getElementsByTagName("*")).contains(A);},getProperty:function(D){var B=Element.Properties[D];if(B){return this[B];
}var A=Element.PropertiesIFlag[D]||0;if(!window.ie||A){return this.getAttribute(D,A);}var C=this.attributes[D];return(C)?C.nodeValue:null;},removeProperty:function(B){var A=Element.Properties[B];
if(A){this[A]="";}else{this.removeAttribute(B);}return this;},getProperties:function(){return Element.getMany(this,"getProperty",arguments);},setProperty:function(C,B){var A=Element.Properties[C];
if(A){this[A]=B;}else{this.setAttribute(C,B);}return this;},setProperties:function(A){return Element.setMany(this,"setProperty",A);},setHTML:function(){this.innerHTML=$A(arguments).join("");
return this;},setText:function(B){var A=this.getTag();if(["style","script"].contains(A)){if(window.ie){if(A=="style"){this.styleSheet.cssText=B;}else{if(A=="script"){this.setProperty("text",B);
}}return this;}else{this.removeChild(this.firstChild);return this.appendText(B);}}this[$defined(this.innerText)?"innerText":"textContent"]=B;return this;
},getText:function(){var A=this.getTag();if(["style","script"].contains(A)){if(window.ie){if(A=="style"){return this.styleSheet.cssText;}else{if(A=="script"){return this.getProperty("text");
}}}else{return this.innerHTML;}}return($pick(this.innerText,this.textContent));},getTag:function(){return this.tagName.toLowerCase();},empty:function(){Garbage.trash(this.getElementsByTagName("*"));
return this.setHTML("");}});Element.fixStyle=function(E,A,D){if($chk(parseInt(A))){return A;}if(["height","width"].contains(E)){var B=(E=="width")?["left","right"]:["top","bottom"];
var C=0;B.each(function(F){C+=D.getStyle("border-"+F+"-width").toInt()+D.getStyle("padding-"+F).toInt();});return D["offset"+E.capitalize()]-C+"px";}else{if(E.test(/border(.+)Width|margin|padding/)){return"0px";
}}return A;};Element.Styles={border:[],padding:[],margin:[]};["Top","Right","Bottom","Left"].each(function(B){for(var A in Element.Styles){Element.Styles[A].push(A+B);
}});Element.borderShort=["borderWidth","borderStyle","borderColor"];Element.getMany=function(B,D,C){var A={};$each(C,function(E){A[E]=B[D](E);});return A;
};Element.setMany=function(B,D,C){for(var A in C){B[D](A,C[A]);}return B;};Element.Properties=new Abstract({"class":"className","for":"htmlFor",colspan:"colSpan",rowspan:"rowSpan",accesskey:"accessKey",tabindex:"tabIndex",maxlength:"maxLength",readonly:"readOnly",frameborder:"frameBorder",value:"value",disabled:"disabled",checked:"checked",multiple:"multiple",selected:"selected"});
Element.PropertiesIFlag={href:2,src:2};Element.Methods={Listeners:{addListener:function(B,A){if(this.addEventListener){this.addEventListener(B,A,false);
}else{this.attachEvent("on"+B,A);}return this;},removeListener:function(B,A){if(this.removeEventListener){this.removeEventListener(B,A,false);}else{this.detachEvent("on"+B,A);
}return this;}}};window.extend(Element.Methods.Listeners);document.extend(Element.Methods.Listeners);Element.extend(Element.Methods.Listeners);var Garbage={elements:[],collect:function(A){if(!A.$tmp){Garbage.elements.push(A);
A.$tmp={opacity:1};}return A;},trash:function(D){for(var B=0,A=D.length,C;B<A;B++){if(!(C=D[B])||!C.$tmp){continue;}if(C.$events){C.fireEvent("trash").removeEvents();
}for(var E in C.$tmp){C.$tmp[E]=null;}for(var F in Element.prototype){C[F]=null;}Garbage.elements[Garbage.elements.indexOf(C)]=null;C.htmlElement=C.$tmp=C=null;
}Garbage.elements.remove(null);},empty:function(){Garbage.collect(window);Garbage.collect(document);Garbage.trash(Garbage.elements);}};window.addListener("beforeunload",function(){window.addListener("unload",Garbage.empty);
if(window.ie){window.addListener("unload",CollectGarbage);}});var Event=new Class({initialize:function(C){if(C&&C.$extended){return C;}this.$extended=true;
C=C||window.event;this.event=C;this.type=C.type;this.target=C.target||C.srcElement;if(this.target.nodeType==3){this.target=this.target.parentNode;}this.shift=C.shiftKey;
this.control=C.ctrlKey;this.alt=C.altKey;this.meta=C.metaKey;if(["DOMMouseScroll","mousewheel"].contains(this.type)){this.wheel=(C.wheelDelta)?C.wheelDelta/120:-(C.detail||0)/3;
}else{if(this.type.contains("key")){this.code=C.which||C.keyCode;for(var B in Event.keys){if(Event.keys[B]==this.code){this.key=B;break;}}if(this.type=="keydown"){var A=this.code-111;
if(A>0&&A<13){this.key="f"+A;}}this.key=this.key||String.fromCharCode(this.code).toLowerCase();}else{if(this.type.test(/(click|mouse|menu)/)){this.page={x:C.pageX||C.clientX+document.documentElement.scrollLeft,y:C.pageY||C.clientY+document.documentElement.scrollTop};
this.client={x:C.pageX?C.pageX-window.pageXOffset:C.clientX,y:C.pageY?C.pageY-window.pageYOffset:C.clientY};this.rightClick=(C.which==3)||(C.button==2);
switch(this.type){case"mouseover":this.relatedTarget=C.relatedTarget||C.fromElement;break;case"mouseout":this.relatedTarget=C.relatedTarget||C.toElement;
}this.fixRelatedTarget();}}}return this;},stop:function(){return this.stopPropagation().preventDefault();},stopPropagation:function(){if(this.event.stopPropagation){this.event.stopPropagation();
}else{this.event.cancelBubble=true;}return this;},preventDefault:function(){if(this.event.preventDefault){this.event.preventDefault();}else{this.event.returnValue=false;
}return this;}});Event.fix={relatedTarget:function(){if(this.relatedTarget&&this.relatedTarget.nodeType==3){this.relatedTarget=this.relatedTarget.parentNode;
}},relatedTargetGecko:function(){try{Event.fix.relatedTarget.call(this);}catch(A){this.relatedTarget=this.target;}}};Event.prototype.fixRelatedTarget=(window.gecko)?Event.fix.relatedTargetGecko:Event.fix.relatedTarget;
Event.keys=new Abstract({enter:13,up:38,down:40,left:37,right:39,esc:27,space:32,backspace:8,tab:9,"delete":46});Element.Methods.Events={addEvent:function(C,B){this.$events=this.$events||{};
this.$events[C]=this.$events[C]||{keys:[],values:[]};if(this.$events[C].keys.contains(B)){return this;}this.$events[C].keys.push(B);var A=C;var D=Element.Events[C];
if(D){if(D.add){D.add.call(this,B);}if(D.map){B=D.map;}if(D.type){A=D.type;}}if(!this.addEventListener){B=B.create({bind:this,event:true});}this.$events[C].values.push(B);
return(Element.NativeEvents.contains(A))?this.addListener(A,B):this;},removeEvent:function(C,B){if(!this.$events||!this.$events[C]){return this;}var F=this.$events[C].keys.indexOf(B);
if(F==-1){return this;}var A=this.$events[C].keys.splice(F,1)[0];var E=this.$events[C].values.splice(F,1)[0];var D=Element.Events[C];if(D){if(D.remove){D.remove.call(this,B);
}if(D.type){C=D.type;}}return(Element.NativeEvents.contains(C))?this.removeListener(C,E):this;},addEvents:function(A){return Element.setMany(this,"addEvent",A);
},removeEvents:function(A){if(!this.$events){return this;}if(!A){for(var B in this.$events){this.removeEvents(B);}this.$events=null;}else{if(this.$events[A]){this.$events[A].keys.each(function(C){this.removeEvent(A,C);
},this);this.$events[A]=null;}}return this;},fireEvent:function(C,B,A){if(this.$events&&this.$events[C]){this.$events[C].keys.each(function(D){D.create({bind:this,delay:A,"arguments":B})();
},this);}return this;},cloneEvents:function(C,A){if(!C.$events){return this;}if(!A){for(var B in C.$events){this.cloneEvents(C,B);}}else{if(C.$events[A]){C.$events[A].keys.each(function(D){this.addEvent(A,D);
},this);}}return this;}};window.extend(Element.Methods.Events);document.extend(Element.Methods.Events);Element.extend(Element.Methods.Events);Element.Events=new Abstract({mouseenter:{type:"mouseover",map:function(A){A=new Event(A);
if(A.relatedTarget!=this&&!this.hasChild(A.relatedTarget)){this.fireEvent("mouseenter",A);}}},mouseleave:{type:"mouseout",map:function(A){A=new Event(A);
if(A.relatedTarget!=this&&!this.hasChild(A.relatedTarget)){this.fireEvent("mouseleave",A);}}},mousewheel:{type:(window.gecko)?"DOMMouseScroll":"mousewheel"}});
Element.NativeEvents=["click","dblclick","mouseup","mousedown","mousewheel","DOMMouseScroll","mouseover","mouseout","mousemove","keydown","keypress","keyup","load","unload","beforeunload","resize","move","focus","blur","change","submit","reset","select","error","abort","contextmenu","scroll"];
Function.extend({bindWithEvent:function(B,A){return this.create({bind:B,"arguments":A,event:Event});}});Elements.extend({filterByTag:function(A){return new Elements(this.filter(function(B){return(Element.getTag(B)==A);
}));},filterByClass:function(A,C){var B=this.filter(function(D){return(D.className&&D.className.contains(A," "));});return(C)?B:new Elements(B);},filterById:function(C,B){var A=this.filter(function(D){return(D.id==C);
});return(B)?A:new Elements(A);},filterByAttribute:function(B,A,D,E){var C=this.filter(function(F){var G=Element.getProperty(F,B);if(!G){return false;}if(!A){return true;
}switch(A){case"=":return(G==D);case"*=":return(G.contains(D));case"^=":return(G.substr(0,D.length)==D);case"$=":return(G.substr(G.length-D.length)==D);
case"!=":return(G!=D);case"~=":return G.contains(D," ");}return false;});return(E)?C:new Elements(C);}});function $E(A,B){return($(B)||document).getElement(A);
}function $ES(A,B){return($(B)||document).getElementsBySelector(A);}$$.shared={regexp:/^(\w*|\*)(?:#([\w-]+)|\.([\w-]+))?(?:\[(\w+)(?:([!*^$]?=)["']?([^"'\]]*)["']?)?])?$/,xpath:{getParam:function(B,D,E,C){var A=[D.namespaceURI?"xhtml:":"",E[1]];
if(E[2]){A.push('[@id="',E[2],'"]');}if(E[3]){A.push('[contains(concat(" ", @class, " "), " ',E[3],' ")]');}if(E[4]){if(E[5]&&E[6]){switch(E[5]){case"*=":A.push("[contains(@",E[4],', "',E[6],'")]');
break;case"^=":A.push("[starts-with(@",E[4],', "',E[6],'")]');break;case"$=":A.push("[substring(@",E[4],", string-length(@",E[4],") - ",E[6].length,' + 1) = "',E[6],'"]');
break;case"=":A.push("[@",E[4],'="',E[6],'"]');break;case"!=":A.push("[@",E[4],'!="',E[6],'"]');}}else{A.push("[@",E[4],"]");}}B.push(A.join(""));return B;
},getItems:function(B,E,G){var F=[];var A=document.evaluate(".//"+B.join("//"),E,$$.shared.resolver,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null);for(var D=0,C=A.snapshotLength;
D<C;D++){F.push(A.snapshotItem(D));}return(G)?F:new Elements(F.map($));}},normal:{getParam:function(A,C,E,B){if(B==0){if(E[2]){var D=C.getElementById(E[2]);
if(!D||((E[1]!="*")&&(Element.getTag(D)!=E[1]))){return false;}A=[D];}else{A=$A(C.getElementsByTagName(E[1]));}}else{A=$$.shared.getElementsByTagName(A,E[1]);
if(E[2]){A=Elements.filterById(A,E[2],true);}}if(E[3]){A=Elements.filterByClass(A,E[3],true);}if(E[4]){A=Elements.filterByAttribute(A,E[4],E[5],E[6],true);
}return A;},getItems:function(A,B,C){return(C)?A:$$.unique(A);}},resolver:function(A){return(A=="xhtml")?"http://www.w3.org/1999/xhtml":false;},getElementsByTagName:function(D,C){var E=[];
for(var B=0,A=D.length;B<A;B++){E.extend(D[B].getElementsByTagName(C));}return E;}};$$.shared.method=(window.xpath)?"xpath":"normal";Element.Methods.Dom={getElements:function(A,H){var C=[];
A=A.trim().split(" ");for(var E=0,D=A.length;E<D;E++){var F=A[E];var G=F.match($$.shared.regexp);if(!G){break;}G[1]=G[1]||"*";var B=$$.shared[$$.shared.method].getParam(C,this,G,E);
if(!B){break;}C=B;}return $$.shared[$$.shared.method].getItems(C,this,H);},getElement:function(A){return $(this.getElements(A,true)[0]||false);},getElementsBySelector:function(A,E){var D=[];
A=A.split(",");for(var C=0,B=A.length;C<B;C++){D=D.concat(this.getElements(A[C],true));}return(E)?D:$$.unique(D);}};Element.extend({getElementById:function(C){var B=document.getElementById(C);
if(!B){return false;}for(var A=B.parentNode;A!=this;A=A.parentNode){if(!A){return false;}}return B;},getElementsByClassName:function(A){return this.getElements("."+A);
}});document.extend(Element.Methods.Dom);Element.extend(Element.Methods.Dom);Element.extend({getValue:function(){switch(this.getTag()){case"select":var A=[];
$each(this.options,function(B){if(B.selected){A.push($pick(B.value,B.text));}});return(this.multiple)?A:A[0];case"input":if(!(this.checked&&["checkbox","radio"].contains(this.type))&&!["hidden","text","password"].contains(this.type)){break;
}case"textarea":return this.value;}return false;},getFormElements:function(){return $$(this.getElementsByTagName("input"),this.getElementsByTagName("select"),this.getElementsByTagName("textarea"));
},toQueryString:function(){var A=[];this.getFormElements().each(function(D){var C=D.name;var E=D.getValue();if(E===false||!C||D.disabled){return ;}var B=function(F){A.push(C+"="+encodeURIComponent(F));
};if($type(E)=="array"){E.each(B);}else{B(E);}});return A.join("&");}});Element.extend({scrollTo:function(A,B){this.scrollLeft=A;this.scrollTop=B;},getSize:function(){return{scroll:{x:this.scrollLeft,y:this.scrollTop},size:{x:this.offsetWidth,y:this.offsetHeight},scrollSize:{x:this.scrollWidth,y:this.scrollHeight}};
},getPosition:function(A){A=A||[];var B=this,D=0,C=0;do{D+=B.offsetLeft||0;C+=B.offsetTop||0;B=B.offsetParent;}while(B);A.each(function(E){D-=E.scrollLeft||0;
C-=E.scrollTop||0;});return{x:D,y:C};},getTop:function(A){return this.getPosition(A).y;},getLeft:function(A){return this.getPosition(A).x;},getCoordinates:function(B){var A=this.getPosition(B);
var C={width:this.offsetWidth,height:this.offsetHeight,left:A.x,top:A.y};C.right=C.left+C.width;C.bottom=C.top+C.height;return C;}});Element.Events.domready={add:function(B){if(window.loaded){B.call(this);
return ;}var A=function(){if(window.loaded){return ;}window.loaded=true;window.timer=$clear(window.timer);this.fireEvent("domready");}.bind(this);if(document.readyState&&window.webkit){window.timer=function(){if(["loaded","complete"].contains(document.readyState)){A();
}}.periodical(50);}else{if(document.readyState&&window.ie){if(!$("ie_ready")){var C=(window.location.protocol=="https:")?"://0":"javascript:void(0)";document.write('<script id="ie_ready" defer src="'+C+'"><\/script>');
$("ie_ready").onreadystatechange=function(){if(this.readyState=="complete"){A();}};}}else{window.addListener("load",A);document.addListener("DOMContentLoaded",A);
}}}};window.onDomReady=function(A){return this.addEvent("domready",A);};window.extend({getWidth:function(){if(this.webkit419){return this.innerWidth;}if(this.opera){return document.body.clientWidth;
}return document.documentElement.clientWidth;},getHeight:function(){if(this.webkit419){return this.innerHeight;}if(this.opera){return document.body.clientHeight;
}return document.documentElement.clientHeight;},getScrollWidth:function(){if(this.ie){return Math.max(document.documentElement.offsetWidth,document.documentElement.scrollWidth);
}if(this.webkit){return document.body.scrollWidth;}return document.documentElement.scrollWidth;},getScrollHeight:function(){if(this.ie){return Math.max(document.documentElement.offsetHeight,document.documentElement.scrollHeight);
}if(this.webkit){return document.body.scrollHeight;}return document.documentElement.scrollHeight;},getScrollLeft:function(){return this.pageXOffset||document.documentElement.scrollLeft;
},getScrollTop:function(){return this.pageYOffset||document.documentElement.scrollTop;},getSize:function(){return{size:{x:this.getWidth(),y:this.getHeight()},scrollSize:{x:this.getScrollWidth(),y:this.getScrollHeight()},scroll:{x:this.getScrollLeft(),y:this.getScrollTop()}};
},getPosition:function(){return{x:0,y:0};}});var Fx={};Fx.Base=new Class({options:{onStart:Class.empty,onComplete:Class.empty,onCancel:Class.empty,transition:function(A){return -(Math.cos(Math.PI*A)-1)/2;
},duration:500,unit:"px",wait:true,fps:50},initialize:function(A){this.element=this.element||null;this.setOptions(A);if(this.options.initialize){this.options.initialize.call(this);
}},step:function(){var A=$time();if(A<this.time+this.options.duration){this.delta=this.options.transition((A-this.time)/this.options.duration);this.setNow();
this.increase();}else{this.stop(true);this.set(this.to);this.fireEvent("onComplete",this.element,10);this.callChain();}},set:function(A){this.now=A;this.increase();
return this;},setNow:function(){this.now=this.compute(this.from,this.to);},compute:function(B,A){return(A-B)*this.delta+B;},start:function(B,A){if(!this.options.wait){this.stop();
}else{if(this.timer){return this;}}this.from=B;this.to=A;this.change=this.to-this.from;this.time=$time();this.timer=this.step.periodical(Math.round(1000/this.options.fps),this);
this.fireEvent("onStart",this.element);return this;},stop:function(A){if(!this.timer){return this;}this.timer=$clear(this.timer);if(!A){this.fireEvent("onCancel",this.element);
}return this;},custom:function(B,A){return this.start(B,A);},clearTimer:function(A){return this.stop(A);}});Fx.Base.implement(new Chain,new Events,new Options);
Fx.CSS={select:function(B,C){if(B.test(/color/i)){return this.Color;}var A=$type(C);if((A=="array")||(A=="string"&&C.contains(" "))){return this.Multi;
}return this.Single;},parse:function(C,D,A){if(!A.push){A=[A];}var F=A[0],E=A[1];if(!$chk(E)){E=F;F=C.getStyle(D);}var B=this.select(D,E);return{from:B.parse(F),to:B.parse(E),css:B};
}};Fx.CSS.Single={parse:function(A){return parseFloat(A);},getNow:function(C,B,A){return A.compute(C,B);},getValue:function(C,A,B){if(A=="px"&&B!="opacity"){C=Math.round(C);
}return C+A;}};Fx.CSS.Multi={parse:function(A){return A.push?A:A.split(" ").map(function(B){return parseFloat(B);});},getNow:function(E,D,C){var A=[];for(var B=0;
B<E.length;B++){A[B]=C.compute(E[B],D[B]);}return A;},getValue:function(C,A,B){if(A=="px"&&B!="opacity"){C=C.map(Math.round);}return C.join(A+" ")+A;}};
Fx.CSS.Color={parse:function(A){return A.push?A:A.hexToRgb(true);},getNow:function(E,D,C){var A=[];for(var B=0;B<E.length;B++){A[B]=Math.round(C.compute(E[B],D[B]));
}return A;},getValue:function(A){return"rgb("+A.join(",")+")";}};Fx.Style=Fx.Base.extend({initialize:function(B,C,A){this.element=$(B);this.property=C;
this.parent(A);},hide:function(){return this.set(0);},setNow:function(){this.now=this.css.getNow(this.from,this.to,this);},set:function(A){this.css=Fx.CSS.select(this.property,A);
return this.parent(this.css.parse(A));},start:function(C,B){if(this.timer&&this.options.wait){return this;}var A=Fx.CSS.parse(this.element,this.property,[C,B]);
this.css=A.css;return this.parent(A.from,A.to);},increase:function(){this.element.setStyle(this.property,this.css.getValue(this.now,this.options.unit,this.property));
}});Element.extend({effect:function(B,A){return new Fx.Style(this,B,A);}});Fx.Styles=Fx.Base.extend({initialize:function(B,A){this.element=$(B);this.parent(A);
},setNow:function(){for(var A in this.from){this.now[A]=this.css[A].getNow(this.from[A],this.to[A],this);}},set:function(C){var A={};this.css={};for(var B in C){this.css[B]=Fx.CSS.select(B,C[B]);
A[B]=this.css[B].parse(C[B]);}return this.parent(A);},start:function(C){if(this.timer&&this.options.wait){return this;}this.now={};this.css={};var E={},D={};
for(var B in C){var A=Fx.CSS.parse(this.element,B,C[B]);E[B]=A.from;D[B]=A.to;this.css[B]=A.css;}return this.parent(E,D);},increase:function(){for(var A in this.now){this.element.setStyle(A,this.css[A].getValue(this.now[A],this.options.unit,A));
}}});Element.extend({effects:function(A){return new Fx.Styles(this,A);}});Fx.Elements=Fx.Base.extend({initialize:function(B,A){this.elements=$$(B);this.parent(A);
},setNow:function(){for(var C in this.from){var F=this.from[C],E=this.to[C],B=this.css[C],A=this.now[C]={};for(var D in F){A[D]=B[D].getNow(F[D],E[D],this);
}}},set:function(G){var B={};this.css={};for(var D in G){var F=G[D],C=this.css[D]={},A=B[D]={};for(var E in F){C[E]=Fx.CSS.select(E,F[E]);A[E]=C[E].parse(F[E]);
}}return this.parent(B);},start:function(D){if(this.timer&&this.options.wait){return this;}this.now={};this.css={};var I={},J={};for(var E in D){var G=D[E],A=I[E]={},H=J[E]={},C=this.css[E]={};
for(var B in G){var F=Fx.CSS.parse(this.elements[E],B,G[B]);A[B]=F.from;H[B]=F.to;C[B]=F.css;}}return this.parent(I,J);},increase:function(){for(var C in this.now){var A=this.now[C],B=this.css[C];
for(var D in A){this.elements[C].setStyle(D,B[D].getValue(A[D],this.options.unit,D));}}}});Fx.Scroll=Fx.Base.extend({options:{overflown:[],offset:{x:0,y:0},wheelStops:true},initialize:function(B,A){this.now=[];
this.element=$(B);this.bound={stop:this.stop.bind(this,false)};this.parent(A);if(this.options.wheelStops){this.addEvent("onStart",function(){document.addEvent("mousewheel",this.bound.stop);
}.bind(this));this.addEvent("onComplete",function(){document.removeEvent("mousewheel",this.bound.stop);}.bind(this));}},setNow:function(){for(var A=0;A<2;
A++){this.now[A]=this.compute(this.from[A],this.to[A]);}},scrollTo:function(B,F){if(this.timer&&this.options.wait){return this;}var D=this.element.getSize();
var C={x:B,y:F};for(var E in D.size){var A=D.scrollSize[E]-D.size[E];if($chk(C[E])){C[E]=($type(C[E])=="number")?C[E].limit(0,A):A;}else{C[E]=D.scroll[E];
}C[E]+=this.options.offset[E];}return this.start([D.scroll.x,D.scroll.y],[C.x,C.y]);},toTop:function(){return this.scrollTo(false,0);},toBottom:function(){return this.scrollTo(false,"full");
},toLeft:function(){return this.scrollTo(0,false);},toRight:function(){return this.scrollTo("full",false);},toElement:function(B){var A=this.element.getPosition(this.options.overflown);
var C=$(B).getPosition(this.options.overflown);return this.scrollTo(C.x-A.x,C.y-A.y);},increase:function(){this.element.scrollTo(this.now[0],this.now[1]);
}});Fx.Slide=Fx.Base.extend({options:{mode:"vertical"},initialize:function(B,A){this.element=$(B);this.wrapper=new Element("div",{styles:$extend(this.element.getStyles("margin"),{overflow:"hidden"})}).injectAfter(this.element).adopt(this.element);
this.element.setStyle("margin",0);this.setOptions(A);this.now=[];this.parent(this.options);this.open=true;this.addEvent("onComplete",function(){this.open=(this.now[0]===0);
});if(window.webkit419){this.addEvent("onComplete",function(){if(this.open){this.element.remove().inject(this.wrapper);}});}},setNow:function(){for(var A=0;
A<2;A++){this.now[A]=this.compute(this.from[A],this.to[A]);}},vertical:function(){this.margin="margin-top";this.layout="height";this.offset=this.element.offsetHeight;
},horizontal:function(){this.margin="margin-left";this.layout="width";this.offset=this.element.offsetWidth;},slideIn:function(A){this[A||this.options.mode]();
return this.start([this.element.getStyle(this.margin).toInt(),this.wrapper.getStyle(this.layout).toInt()],[0,this.offset]);},slideOut:function(A){this[A||this.options.mode]();
return this.start([this.element.getStyle(this.margin).toInt(),this.wrapper.getStyle(this.layout).toInt()],[-this.offset,0]);},hide:function(A){this[A||this.options.mode]();
this.open=false;return this.set([-this.offset,0]);},show:function(A){this[A||this.options.mode]();this.open=true;return this.set([0,this.offset]);},toggle:function(A){if(this.wrapper.offsetHeight==0||this.wrapper.offsetWidth==0){return this.slideIn(A);
}return this.slideOut(A);},increase:function(){this.element.setStyle(this.margin,this.now[0]+this.options.unit);this.wrapper.setStyle(this.layout,this.now[1]+this.options.unit);
}});Fx.Transition=function(B,A){A=A||[];if($type(A)!="array"){A=[A];}return $extend(B,{easeIn:function(C){return B(C,A);},easeOut:function(C){return 1-B(1-C,A);
},easeInOut:function(C){return(C<=0.5)?B(2*C,A)/2:(2-B(2*(1-C),A))/2;}});};Fx.Transitions=new Abstract({linear:function(A){return A;}});Fx.Transitions.extend=function(A){for(var B in A){Fx.Transitions[B]=new Fx.Transition(A[B]);
Fx.Transitions.compat(B);}};Fx.Transitions.compat=function(A){["In","Out","InOut"].each(function(B){Fx.Transitions[A.toLowerCase()+B]=Fx.Transitions[A]["ease"+B];
});};Fx.Transitions.extend({Pow:function(B,A){return Math.pow(B,A[0]||6);},Expo:function(A){return Math.pow(2,8*(A-1));},Circ:function(A){return 1-Math.sin(Math.acos(A));
},Sine:function(A){return 1-Math.sin((1-A)*Math.PI/2);},Back:function(B,A){A=A[0]||1.618;return Math.pow(B,2)*((A+1)*B-A);},Bounce:function(D){var C;for(var B=0,A=1;
1;B+=A,A/=2){if(D>=(7-4*B)/11){C=-Math.pow((11-6*B-11*D)/4,2)+A*A;break;}}return C;},Elastic:function(B,A){return Math.pow(2,10*--B)*Math.cos(20*B*Math.PI*(A[0]||1)/3);
}});["Quad","Cubic","Quart","Quint"].each(function(B,A){Fx.Transitions[B]=new Fx.Transition(function(C){return Math.pow(C,[A+2]);});Fx.Transitions.compat(B);
});var XHR=new Class({options:{method:"post",async:true,onRequest:Class.empty,onSuccess:Class.empty,onFailure:Class.empty,urlEncoded:true,encoding:"utf-8",autoCancel:false,headers:{}},setTransport:function(){this.transport=(window.XMLHttpRequest)?new XMLHttpRequest():(window.ie?new ActiveXObject("Microsoft.XMLHTTP"):false);
return this;},initialize:function(A){this.setTransport().setOptions(A);this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.headers={};if(this.options.urlEncoded&&this.options.method=="post"){var B=(this.options.encoding)?"; charset="+this.options.encoding:"";
this.setHeader("Content-type","application/x-www-form-urlencoded"+B);}if(this.options.initialize){this.options.initialize.call(this);}},onStateChange:function(){if(this.transport.readyState!=4||!this.running){return ;
}this.running=false;var A=0;try{A=this.transport.status;}catch(B){}if(this.options.isSuccess.call(this,A)){this.onSuccess();}else{this.onFailure();}this.transport.onreadystatechange=Class.empty;
},isSuccess:function(A){return((A>=200)&&(A<300));},onSuccess:function(){this.response={text:this.transport.responseText,xml:this.transport.responseXML};
this.fireEvent("onSuccess",[this.response.text,this.response.xml]);this.callChain();},onFailure:function(){this.fireEvent("onFailure",this.transport);},setHeader:function(A,B){this.headers[A]=B;
return this;},send:function(A,C){if(this.options.autoCancel){this.cancel();}else{if(this.running){return this;}}this.running=true;if(C&&this.options.method=="get"){A=A+(A.contains("?")?"&":"?")+C;
C=null;}this.transport.open(this.options.method.toUpperCase(),A,this.options.async);this.transport.onreadystatechange=this.onStateChange.bind(this);if((this.options.method=="post")&&this.transport.overrideMimeType){this.setHeader("Connection","close");
}$extend(this.headers,this.options.headers);for(var B in this.headers){try{this.transport.setRequestHeader(B,this.headers[B]);}catch(D){}}this.fireEvent("onRequest");
this.transport.send($pick(C,null));return this;},cancel:function(){if(!this.running){return this;}this.running=false;this.transport.abort();this.transport.onreadystatechange=Class.empty;
this.setTransport();this.fireEvent("onCancel");return this;}});XHR.implement(new Chain,new Events,new Options);var Ajax=XHR.extend({options:{data:null,update:null,onComplete:Class.empty,evalScripts:false,evalResponse:false},initialize:function(B,A){this.addEvent("onSuccess",this.onComplete);
this.setOptions(A);this.options.data=this.options.data||this.options.postBody;if(!["post","get"].contains(this.options.method)){this._method="_method="+this.options.method;
this.options.method="post";}this.parent();this.setHeader("X-Requested-With","XMLHttpRequest");this.setHeader("Accept","text/javascript, text/html, application/xml, text/xml");
this.url=B;},onComplete:function(){if(this.options.update){$(this.options.update).empty().setHTML(this.response.text);}if(this.options.evalScripts||this.options.evalResponse){this.evalScripts();
}this.fireEvent("onComplete",[this.response.text,this.response.xml],20);},request:function(A){A=A||this.options.data;switch($type(A)){case"element":A=$(A).toQueryString();
break;case"object":A=Object.toQueryString(A);}if(this._method){A=(A)?[this._method,A].join("&"):this._method;}return this.send(this.url,A);},evalScripts:function(){var B,A;
if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader("Content-type"))){A=this.response.text;}else{A=[];var C=/<script[^>]*>([\s\S]*?)<\/script>/gi;
while((B=C.exec(this.response.text))){A.push(B[1]);}A=A.join("\n");}if(A){(window.execScript)?window.execScript(A):window.setTimeout(A,0);}},getHeader:function(A){try{return this.transport.getResponseHeader(A);
}catch(B){}return null;}});Object.toQueryString=function(B){var C=[];for(var A in B){C.push(encodeURIComponent(A)+"="+encodeURIComponent(B[A]));}return C.join("&");
};Element.extend({send:function(A){return new Ajax(this.getProperty("action"),$merge({data:this.toQueryString()},A,{method:"post"})).request();}});var Cookie=new Abstract({options:{domain:false,path:false,duration:false,secure:false},set:function(C,D,B){B=$merge(this.options,B);
D=encodeURIComponent(D);if(B.domain){D+="; domain="+B.domain;}if(B.path){D+="; path="+B.path;}if(B.duration){var A=new Date();A.setTime(A.getTime()+B.duration*24*60*60*1000);
D+="; expires="+A.toGMTString();}if(B.secure){D+="; secure";}document.cookie=C+"="+D;return $extend(B,{key:C,value:D});},get:function(A){var B=document.cookie.match("(?:^|;)\\s*"+A.escapeRegExp()+"=([^;]*)");
return B?decodeURIComponent(B[1]):false;},remove:function(B,A){if($type(B)=="object"){this.set(B.key,"",$merge(B,{duration:-1}));}else{this.set(B,"",$merge(A,{duration:-1}));
}}});var Json={toString:function(C){switch($type(C)){case"string":return'"'+C.replace(/(["\\])/g,"\\$1")+'"';case"array":return"["+C.map(Json.toString).join(",")+"]";
case"object":var A=[];for(var B in C){A.push(Json.toString(B)+":"+Json.toString(C[B]));}return"{"+A.join(",")+"}";case"number":if(isFinite(C)){break;}case false:return"null";
}return String(C);},evaluate:function(str,secure){return(($type(str)!="string")||(secure&&!str.test(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/)))?null:eval("("+str+")");
}};Json.Remote=XHR.extend({initialize:function(B,A){this.url=B;this.addEvent("onSuccess",this.onComplete);this.parent(A);this.setHeader("X-Request","JSON");
},send:function(A){return this.parent(this.url,"json="+Json.toString(A));},onComplete:function(){this.fireEvent("onComplete",[Json.evaluate(this.response.text,this.options.secure)]);
}});var Asset=new Abstract({javascript:function(C,B){B=$merge({onload:Class.empty},B);var A=new Element("script",{src:C}).addEvents({load:B.onload,readystatechange:function(){if(this.readyState=="complete"){this.fireEvent("load");
}}});delete B.onload;return A.setProperties(B).inject(document.head);},css:function(B,A){return new Element("link",$merge({rel:"stylesheet",media:"screen",type:"text/css",href:B},A)).inject(document.head);
},image:function(C,B){B=$merge({onload:Class.empty,onabort:Class.empty,onerror:Class.empty},B);var D=new Image();D.src=C;var A=new Element("img",{src:C});
["load","abort","error"].each(function(E){var F=B["on"+E];delete B["on"+E];A.addEvent(E,function(){this.removeEvent(E,arguments.callee);F.call(this);});
});if(D.width&&D.height){A.fireEvent("load",A,1);}return A.setProperties(B);},images:function(D,C){C=$merge({onComplete:Class.empty,onProgress:Class.empty},C);
if(!D.push){D=[D];}var A=[];var B=0;D.each(function(F){var E=new Asset.image(F,{onload:function(){C.onProgress.call(this,B);B++;if(B==D.length){C.onComplete();
}}});A.push(E);});return new Elements(A);}});

// JScript File


Popup = function(title, detail, offset) {
	this.title = title;
	this.detail = detail;
	this.offset = offset;
	var _t = this;
	this.hideTimeout = null;
	this.title.addEvent("click", function(evt) {_t.show(evt)});
	/*
	this.detail.addEvent("mouseover", function(evt) {_t.show(evt)});
	
	this.title.addEvent("mouseout", function(evt) {
		_t.hideTimeout = setTimeout(function(evt) {_t.hide(evt)}, 50);
	});
	this.detail.addEvent("mouseout", function(evt) {
		_t.hideTimeout = setTimeout(function(evt) {_t.hide(evt)}, 50);
	});
	*/
	
}

Popup.prototype.show = function(evt) {
    var tgt = (evt.srcElement || evt.target);
	if (this.hideTimeout != null) {
		clearTimeout(this.hideTimeout);
		this.hideTimeout = null;
	} else {
	    if (nitobi.isMenuVisible) {
	        nitobi.isMenuVisible.detail.style.display = "none";
            nitobi.isMenuVisible = false;
	    } 
        this.detail.style.display = "block";
        // Size multi-column lang drop-down appropriately.
        var ind = (navigator.userAgent.indexOf('MSIE')>-1)?0:1;
        if (this.detail.childNodes[ind].id == "LanguageShadow") {
            this.detail.childNodes[ind].childNodes[ind].style.height = ($('LangList').getSize().size.y) + "px";
        } else if (this.detail.childNodes[ind].id == "LangFilterShadow") {
            this.detail.childNodes[ind].childNodes[ind].style.height = ($('LangFilterList').getSize().size.y) + "px";
        }
        nitobi.isMenuVisible = this;
        nitobi.ClickCount = 1;
	}
}

Popup.prototype.hide = function(evt) {
	this.hideTimeout = null;
	this.detail.style.display = "none";
}

// JScript File

function rate(resource, rating)
{

    var xhr = new XHR();
    //xhr.onSuccess = function() {alert("success");};
    xhr.send("/RatingHandler.ashx", "ResourceId="+resource+"&Stars="+rating);
    

}

// JScript File

function rate(resource, rating)
{
    var xhr = new XHR({method:'POST'});
    xhr.send("/RatingHandler.ashx", "ResourceId="+resource+"&Stars="+rating);
}

// fix ie7 background image caching bug
try {
document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

window.addEvent('domready', function() {

    var mySubBut = $E('.biggerbutton');

    //console.log("dd", $E('.filterbybutton'));
    if ($E('.filterbyfeature')) {
        var dropdowns = $ES(".FilterByFeatureDropDown");
        for (var i = 0; i < dropdowns.length; i++)
        {
            var dropdown = dropdowns[i];
            new Popup(dropdown.getPrevious("a"), dropdown, $("header"));
            new Popup(dropdown.getPrevious("a").getPrevious("a"), dropdown, $("header"));
        }
        //new Popup($E('.filterbyfeature'), $ES('FilterByFeatureDropDown'), $('header'));
    }
    if ($E('.filterbylanguage')) {
        new Popup($E('.filterbylanguage'),  $('FilterByLanguageDropDown'), $('header'));
    }
});

window.addEvent('load', function() {
    if ($('toptopnav')) {
        nitobi.alignUserMenu();      
    }    
});


nitobi.alignUserMenu = function () {
    
    var elem = $E('div.language a');
//    if (elem) {
//        elem.addEvent("click", nitobi.showhideLanguageSelectorDropdown);
//        $('LanguageSelectorDropdown').addEvent("mouseleave", function() {nitobi.showhideLanguageSelectorDropdown();}); 
//    }    
    
    elem = $E('div.download a');
    if (elem) {
        elem.addEvent("mouseenter", nitobi.hoverTopNavLink);
    }    
    
    elem = $E('div.signin a');
    if (elem) {
        elem.addEvent("mouseenter", nitobi.hoverTopNavLink);
        elem.addEvent("mouseleave", nitobi.hoverTopNavLink);
    }

    elem = $E('div.join a');
    if (elem) {
        elem.addEvent("mouseenter", nitobi.hoverTopNavLink);
        elem.addEvent("mouseleave", nitobi.hoverTopNavLink);
    }

    elem = $E('div.profile a');
    if (elem) {
        elem.addEvent("mouseenter", nitobi.hoverTopNavLink);
        elem.addEvent("mouseleave", nitobi.hoverTopNavLink);
    }
       
    elem = $E('div.signout a');
    if (elem) {
        elem.addEvent("mouseenter", nitobi.hoverTopNavLink);
        elem.addEvent("mouseleave", nitobi.hoverTopNavLink);
    }
    
    elem = $E('div.language a');
    if (elem) {
        elem.addEvent("mouseenter", nitobi.hoverTopNavLink);
        elem.addEvent("mouseleave", nitobi.hoverTopNavLink);
    }     
    
    try {
        $E('div.download').style["display"] = (nitobi.isIE8() || nitobi.isWin7()) ? "none" : "block";
    } catch(e) {
        $E('div.download').style["display"] = "block";
    }    
}



nitobi.hoverTopNavLink = function(eObj){
    var target = (eObj.target || eObj.toElement || eObj.srcElement);
    var coords = target.getCoordinates();
    if (eObj.type == "mouseover") {

        var myfd = document.createElement("div");

        myfd.className = "fadehover";
        if (target.id == "homenav" ||  target.id == "searchgallerynav" || target.id == "getstartednav" || target.id == "gallerynav" || target.id == "actnav" || target.id == "slicegallerynav" || target.id == "addonsnav") {
            var xofs = 0;
            var yofs = -5;
            
            myfd.style.top = (coords.top-6+yofs) + "px";
            myfd.style.left = (Math.round((coords.width-109)/2)+coords.left+xofs) + "px";
            
        } else {
            myfd.style.top = (coords.top-10) + "px";
            myfd.style.left = (coords.left-((109-coords.width)/2)) + "px";
        }
        
        $("body_container").appendChild(myfd);
    } else {
        var els = $ES(".fadehover");
        els.each(function(s) {
            s.getParent().removeChild(s);
        });
    
    }
};

nitobi.LanguageSelectorDropdownVisible = false;
nitobi.showhideLanguageSelectorDropdown = function(eObj) {
    var dd = $('LanguageSelectorDropdown');
    if (nitobi.LanguageSelectorDropdownVisible == false) {
        dd.style.display = "block";
        nitobi.LanguageSelectorDropdownVisible = true;
    } else {
        dd.style.display = "none";
        nitobi.LanguageSelectorDropdownVisible = false;
    }
    return false;
}



nitobi.getCoords = function(element)
{
   var ew, eh;
   try {
       var originalElement = element;
       ew = element.offsetWidth;
       eh = element.offsetHeight;
       for (var lx=0,ly=0;element!=null;
           lx+=element.offsetLeft,ly+=element.offsetTop,element=element.offsetParent);
       for (;originalElement!=document.body;
           lx-=originalElement.scrollLeft,ly-=originalElement.scrollTop,originalElement=originalElement.parentNode);
   } catch(e) {}
   return {"x":lx,"y":ly,"height":eh,"width":ew}
};


//this function concatenates the innerhtml of all elements with the class "ellipsis", to the custom element attribute of "limit"
//this only works if if the inner html is the text, or the text is 1 child element deeper, and i think only works for block elements
    function ellipsis(e) {
    var textContainer = e.getFirst();
    if (!textContainer)
        textContainer = e;
    var limit = parseInt(e.getAttribute("limit"));
    var t = textContainer.innerHTML; 
    while (t.length > 0 && e.getSize().size.y >= limit) {
      t = t.substr(0, t.length - 1);
      textContainer.innerHTML = t + "...";
    }
}

window.addEvent( "load", function() {
    $$('.ellipsis').each(ellipsis);
});

/*
window.addEvent('domready', function() {    
    // This adds an onclick to the image masks since we cant have the image mask inside of the <a> tag for accessibility
    $$('.mask a').each(function(e) {e.getNext('img').addEvent('click',function() {window.location = (e.getAttribute('href'))})});
});*/

nitobi.xhrObj = null;
nitobi.resID = 0;
nitobi.subdomainHack = false;

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(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;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

nitobi.registerDownloadForAtlas = function(resourceName) {
    // replace spaces with underscores
    resourceName = resourceName.replace(/\s/g, "_").replace(/[\W]+/,'');
    if (resourceName == 'Billy_Currington_News') {
        resourceName = 'Country_BillyC_Accelerator';
    } else if (resourceName == 'David_Nail_News') {
        resourceName = 'Country_DavidN_Accelerator';
    } else if (resourceName == 'Sugarland_News') {
        resourceName = 'Country_SugarLand_Accelerator';
    }
    // injects the script tag with mootools into the body
    var st = new Element('script', {
        type : 'text/javascript',
        language: 'JavaScript',
        src: 'http://view.atdmt.com/jaction/UMIRF_IE8_AddOns_' + resourceName
    }).injectInside(document.body);
}
nitobi.registerDownloadForAtlasV2 = function(resourceName) {
    // replace spaces with underscores
    resourceName = resourceName.replace(/\s/g, "_").replace(/[\W]+/,'');
    // injects the script tag with mootools into the body
    var st = new Element('script', {
        type : 'text/javascript',
        language: 'JavaScript',
        src: 'http://view.atdmt.com/jaction/UMIRF_' + resourceName
    }).injectInside(document.body);
}

nitobi.registerDownloadForAtlasFull = function(resourceName) {
    // replace spaces with underscores
    resourceName = resourceName.replace(/\s/g, "_").replace(/[\W]+/,'');
    // injects the script tag with mootools into the body
    var st = new Element('script', {
        type : 'text/javascript',
        language: 'JavaScript',
        src: 'http://view.atdmt.com/jaction/' + resourceName
    }).injectInside(document.body);
}

nitobi.registerDownloadForAtlasUM = function(resourceName) {
    // replace spaces with underscores
    resourceName = resourceName.replace(/\s/g, "_").replace(/[\W]+/,'');
    // injects the script tag with mootools into the body
    var st = new Element('script', {
        type : 'text/javascript',
        language: 'JavaScript',
        src: 'http://view.atdmt.com/jaction/UMIRF_IE8_AddOns_' + resourceName
    }).injectInside(document.body);
}

nitobi.downloadResource = function(resID, resourceName, resourceType, partnerName, isLarge, trackForAtlas) {
    var rl = nitobi.rootLocation;
    if (nitobi.subdomainHack == true)
        rl = "http://img1.ie8gallery.com/";
    nitobi.resID = resID;
    if (nitobi.isIE8() == true) {
        try {
            nitobi.manageDownload(resID);
            window.external.addService(rl + "DownloadHandler.ashx?ResourceId=" + nitobi.resID);
            nitobi.registerDownloadForOmniture(resourceName, resourceType, partnerName, resID, isLarge);

            if (trackForAtlas) {
                nitobi.registerDownloadForAtlas(trackForAtlas);
            }

        } catch (e) {
            nitobi.registerFailedInstall();
        }
    } else {
        nitobi.showSplash();
    }

}

nitobi.registerFailedInstall = function() {
     s.linkTrackVars='events,eVar6,eVar9,eVar10';
     s.linkTrackEvents='event9';
     
     // this would be optional if you want to track the resources that failed
     s.eVar6=s.prop6;
     // converting page
     s.eVar9=s.pageName;
     // reason for failed install
     s.eVar10='';
     // this will capture the failure
     s.events='event9';
     
     // link will take user away from page
     //s.tl(this, 'o', 'Gallery Install Failed');
     
     // link will not take user away from page
     s.tl(true, 'o', 'Gallery Install Failed');

}
nitobi.downloadWebsliceUM = function(resID, url, title, resourceType, partnername, isLarge) {
    if (nitobi.isIE8() == true) {
        try {
            nitobi.manageDownload(resID);
            window.external.addToFavoritesBar(url, title, 'slice');
            nitobi.registerDownloadForOmniture(title, resourceType, partnername, resID, isLarge);
            nitobi.registerDownloadForAtlasUM(title);
            
        } catch(e) {
            nitobi.registerFailedInstall();
        }    
    } else {
        nitobi.showSplash();
    }
};

nitobi.downloadWebslice = function(resID, url, title, resourceType, partnername, isLarge, trackForAtlas) {
    if (nitobi.isIE8() == true) {
        try {
            nitobi.manageDownload(resID);
            window.external.addToFavoritesBar(url, title, 'slice');
            nitobi.registerDownloadForOmniture(title, resourceType, partnername, resID, isLarge);

            if (trackForAtlas) {
                nitobi.registerDownloadForAtlas(trackForAtlas);
            }
            
        } catch(e) {
            nitobi.registerFailedInstall();
        }    
    } else {
        nitobi.showSplash();
    }
};

nitobi.installSearchProvider = function(resID, url, resourceName, resourceType, partnername, isLarge, trackForAtlas) 
{
        if (nitobi.isIE8() == true) {
            try {
                nitobi.manageDownload(resID);
                window.external.AddSearchProvider(nitobi.rootLocation + "DownloadHandler.ashx?ResourceId=" + resID);
                nitobi.registerDownloadForOmniture(resourceName, resourceType, partnername, resID, isLarge);

                if (trackForAtlas) {
                    nitobi.registerDownloadForAtlas(trackForAtlas);
                }
            }
            catch (e)
            {
                nitobi.registerFailedInstall();
            }
        } else {
            // <BING>
            if (resID == 790) {
                window.external.AddSearchProvider(nitobi.rootLocation + "bing.xml");
                nitobi.registerDownloadForOmniture(resourceName, resourceType, partnername, resID, isLarge);

                if (trackForAtlas) {
                    nitobi.registerDownloadForAtlas(trackForAtlas);
                }
            } else {
            // </BING>
                nitobi.showSplash();
            }
        }
    
};


nitobi.finishedDownloading = function() {

};
nitobi.isWin7 = function () {
    return (window.navigator.userAgent && window.navigator.userAgent.indexOf('Windows NT 6.1') > -1);
}
nitobi.isIE8 = function() {
    return (window.navigator.userAgent && window.navigator.userAgent.indexOf('Trident/4.0') > -1);
};
nitobi.isIE = function() {
    return (window.navigator.userAgent && window.navigator.userAgent.indexOf('MSIE') > -1);
};
nitobi.registerDownload = function(resID) {
    if (nitobi.isIE8() == true) {
        nitobi.manageDownload(resID);
        return true;                
    } else {
        nitobi.showSplash();
        return false; 
    }
};
nitobi.manageGWSInstall = function(WSID, name) {
    nitobi.xhrObj = new XHR();
    nitobi.xhrObj.send(nitobi.rootLocation + "WSInstallHandler.ashx?Id="+WSID, "");
    window.external.addToFavoritesBar("http://" + location.host + nitobi.rootLocation + "ie8slice/wsUpdate.aspx?id=" + WSID, name, 'slice');
    nitobi.registerWSFInstall(name);
    return false;
};
nitobi.manageDownload = function(resID) {
    nitobi.xhrObj = new XHR();
    nitobi.xhrObj.send(nitobi.rootLocation + "DownloadHandler.ashx?ResourceId="+resID, "");
    return true;
};

nitobi.downloadAddOn = function(resID, url, resourceName, resourceType, partnername, isLarge, trackForAtlas) {
    nitobi.manageDownload(resID);
    nitobi.registerDownloadForOmniture(resourceName, resourceType, partnername, resID, isLarge);

    if (trackForAtlas) {
        nitobi.registerDownloadForAtlas(trackForAtlas);
    }

    window.open(url);
    
    return false;
};

var gImage = null;
nitobi.registerDownloadForOmniture = function(resName, resType, partnerName, resID, isLarge) {
   try {
     path = window.location.pathname;
     // Check for home page.
     dlLocation = "";
     pageCode = "";
     largeStr = "";
     fromMarquee = false;
     if (isLarge != null) {
        if (isLarge) {
            largeStr = "lg";
            fromMarquee = true;
        } else {
            largeStr = "sm";
        }
     } else {
        fromMarquee = false;
     }
     if (path.substring(4).toLowerCase() == "") {
        // On the home page.
        dlLocation = "Home Page";
        pageCode = "hm";
     } else {
        // Check for main resource type pages.
        if (path.substring(4).toLowerCase() == "accelerators/") {
            dlLocation = "Accelerators Page";
            pageCode = "ac";
        } else if (path.substring(4).toLowerCase() == "webslices/") {
            dlLocation = "Web Slices Page";
            pageCode = "ws";
        } else if (path.substring(4).toLowerCase() == "searchproviders/") {
            dlLocation = "Search Providers Page";
            pageCode = "sp";
        } else if (path.substring(4).toLowerCase() == "extensions/") {
            dlLocation = "Toolbars and Extensions Page";
            pageCode = "ex";
        } else if (path.substring(4,11).toLowerCase() == "details") {
            dlLocation = "Details Page";
        }
     }
     s.events="";
     s.linkTrackEvents='event6';
     if (fromMarquee) {
        s.eVar1 = pageCode + "_" + largeStr + "_" + resID;
        s.products = ";" + s.eVar1;
		s.events=s.apl(s.events,"event12",",",2);
        s.linkTrackEvents = s.apl(s.linkTrackEvents,'event12',',',2);
        s.linkTrackVars='prop6,prop7,eVar1,eVar6,eVar7,eVar9,eVar11,eVar13,products,events';
     } else {
        s.linkTrackVars='prop6,prop7,eVar6,eVar7,eVar9,eVar11,eVar13,events';
     }
     s.prop6=resName; // install name
     s.prop7=s.pageName;
     s.eVar6=s.prop6;
     s.eVar7=resType;
     s.eVar9=s.pageName;
     s.eVar13=dlLocation;
	 s.events=s.apl(s.events,"event6",",",2);
     s.eVar11=partnerName;
     
     // link will take user away from page
     //s.tl(this, 'o', 'Gallery Install');
     
     // link will not take user away from page
     s.tl(true, 'o', 'Gallery Install');
} catch(e) {}
};
nitobi.registerWSFInstall = function (sliceName) {
    s.events = "event15";
    s.linkTrackEvents = 'event15';
    s.linkTrackVars = 'prop6,prop7,eVar9,eVar13,eVar15,events';
    s.prop6 = sliceName;
    s.prop7 = s.pageName;
    s.eVar9 = s.pageName;
    if (s.pageName.substring(0, 5) == 'Creat') {
        s.eVar13 = 'Create Slice Page';
    } else if (s.pageName.substring(0, 5) == 'admin') {
        s.eVar13 = 'Account Home Page';
    } else {
        s.eVar13 = 'Share Slice Page';
    }
    s.eVar15 = sliceName;
    // link will not take user away from page
    s.tl(true, 'o', 'WSF Install');
};
nitobi.trackIE8DL = function(isIE6) {
     s.linkLeaveQueryString=true;
     s.linkTrackVars='events,eVar9';
     s.linkTrackEvents='event3';
     s.eVar9=s.pageName;
     s.events='event3';
     //should get picked up by exit link tracking
     //s.tl(this, 'o', 'IE8 Download');
	 
	 s.linkType='e';
	 s.linkName='Download IE8';
	 if (isIE6) {
	    if (isIE6 == 67) {
	        if (nitobi.IE6) {
	            nitobi.registerDownloadForAtlasV2('Gallery_Interstitial_IE6_DL_Button');
	        } else if (nitobi.IE7) {
	            // Track IE7 upgrade download.
	            nitobi.registerDownloadForAtlasV2('Gallery_Interstitial_IE7_DL_Button');
	        }
	    } else if (isIE6 == 21) {
	        // Track other browser upgrade download.
	        nitobi.registerDownloadForAtlasV2('Gallery_Interstitial_NonIE_DL_Button');
	    }
	 }
}

nitobi.logit = function() {
    s.linkTrackVars='events,eVar2';
    s.linkTrackEvents='event2';
    s.events='event2';
    s.eVar2 = "review reported";
    s.tl(true, 'o', 'Review Reported');
}
nitobi.splashOpacity = 0.0;
nitobi.dsfsd = null;
nitobi.ie6timer = null;
nitobi.showSplash = function(isOldIE) {
    if (!isOldIE) {
        clearTimeout(nitobi.dsfsd);
        if (!$('whitebackground')) {
            nitobi.dsfsd = setTimeout("nitobi.showSplash()", 2000);
        } else {
            var winSize = Window.getSize();
            var wb = $('whitebackground');
            wb.setOpacity(0.01);
            wb.style.top = "0px";
            wb.style.left = "0px";
            wb.style.width = winSize.scrollSize.x + "px";
            wb.style.height = winSize.scrollSize.y + "px";
            wb.style.display = "block";
            wb.setOpacity(0.01);
            nitobi.fadeInSplash();
        }
    } else {
        if (nitobi.isIE8()) { return; }
        clearTimeout(nitobi.ie6timer);
        if (!$('whitebackground')) {
            nitobi.ie6timer = setTimeout("nitobi.showSplash(" + isOldIE + ")", 2000);
        } else {
            // Razorfish instrumentation, IE6 & 7 and other browsers.
            if (isOldIE == 6) {
                nitobi.registerDownloadForAtlasV2('Gallery_Interstitial_IE6_Users');
            } else if (isOldIE == 7) {
                nitobi.registerDownloadForAtlasV2('Gallery_Interstitial_IE7_Users');
            } else if (isOldIE == 21) {
                nitobi.registerDownloadForAtlasV2('Gallery_Interstitial_NonIE_Users');
            }
            var winSize = Window.getSize();
            var wb = $('whitebackground');
            wb.setOpacity(0.01);
            wb.style.top = "0px";
            wb.style.left = "0px";
            wb.style.width = winSize.scrollSize.x + "px";
            wb.style.height = winSize.scrollSize.y + "px";
            wb.style.display = "block";
            wb.setOpacity(0.01);
            nitobi.fadeInSplash(isOldIE);
        }
    }
};


nitobi.fadeInSplash = function(isIE6) {
    if (!isIE6) {
        clearTimeout(nitobi.dsfsd);
        if (!nitobi.splashLaunchTime)
            nitobi.splashLaunchTime = new Date();
        var nowdate = new Date();
        var tdiff = nowdate - nitobi.splashLaunchTime;
    
        var prog = (tdiff/800);
        if (prog > 1.0)
            prog = 1.0;
        $('whitebackground').setOpacity(prog*0.7);
        nitobi.splashOpacity = prog;
    
        if (prog < 1.0) {
            setTimeout("nitobi.fadeInSplash()", 1);
        } else {
            nitobi.revealSplashWindow();
        }
    } else {
        clearTimeout(nitobi.ie6timer);
        if (!nitobi.splashLaunchTime)
            nitobi.splashLaunchTime = new Date();
        var nowdate = new Date();
        var tdiff = nowdate - nitobi.splashLaunchTime;
    
        var prog = (tdiff/800);
        if (prog > 1.0)
            prog = 1.0;
        $('whitebackground').setOpacity(prog*0.7);
        nitobi.splashOpacity = prog;
    
        if (prog < 1.0) {
            setTimeout("nitobi.fadeInSplash(" + isIE6 + ")", 1);
        } else {
            nitobi.revealSplashWindow(isIE6);
        }
    }
};


nitobi.revealSplashWindow = function(isIE6) {
    if (!isIE6) {
        var ug = $('ie8upgradesplash');
    
        ug.style.visibility = "hidden";
        ug.style.display = "block";
        try {
            $('ie8close').onclick = function() {nitobi.closeSplash()};
        } catch(e) {
            nitobi.eraseCookie('SplashDisabled');
        };
        setTimeout("nitobi.positionSplashWindow()", 1);
    } else {
        var ug = $('ie8fromie6');
        if (isIE6 == 21) ug = $('ie8upgradeother');
        ug.style.visibility = "hidden";
        ug.style.display = "block";
        try {
            if (isIE6 == 21) {
                $('ie8close2').onclick = function() {nitobi.closeSplash(isIE6)};
            } else {
                $('ie8close1').onclick = function() {nitobi.closeSplash(isIE6)};
            }
        } catch(e) {
            nitobi.eraseCookie('SplashDisabled');
        };
        setTimeout("nitobi.positionSplashWindow(" + isIE6 + ")", 1);
    }
};
nitobi.isPopupVisible = false;
nitobi.ClickCount = 0;
nitobi.timmer = null;
nitobi.ie6timmer = null;
nitobi.positionSplashWindow = function(isIE6) {
    if (!isIE6) {
        var ug = $('ie8upgradesplash');
        var winSize = nitobi.getWindowSize();
        var winScroll = Window.getSize();
        var uwidth = ug.offsetWidth;
        var uheight = ug.offsetHeight;
        ug.style.top = (Math.round((winSize.height - uheight)/2) + winScroll.scroll.y) + 'px';
        ug.style.left = (Math.round((winSize.width - uwidth)/2) + winScroll.scroll.x) + 'px';
        ug.style.visibility = "visible";
        nitobi.timmer = setTimeout("nitobi.positionSplashWindow()", 1000);
    } else {
        var ug = $('ie8fromie6');
        if (isIE6 == 21) ug = $('ie8upgradeother');
        var winSize = nitobi.getWindowSize();
        var winScroll = Window.getSize();
        var uwidth = ug.offsetWidth;
        var uheight = ug.offsetHeight;
        ug.style.top = (Math.round((winSize.height - uheight)/2) + winScroll.scroll.y) + 'px';
        ug.style.left = (Math.round((winSize.width - uwidth)/2) + winScroll.scroll.x) + 'px';
        ug.style.visibility = "visible";
        nitobi.ie6timmer = setTimeout("nitobi.positionSplashWindow(" + isIE6 + ")", 1000);
    }
}
nitobi.showPopup = function(element,feature) {
    var id = "";
    switch(feature){
        case 0: id = "web"; break;
        case 1: id = "accel"; break;        
        case 2: id = "search"; break;
        default: return false;
    }
    var pop = $(id + "Popup");
    var leftOffset = (nitobi.isRTL)?(nitobi.Debug.getCoords(element).x - Math.abs(element.offsetWidth) - element.offsetWidth/2):(nitobi.Debug.getCoords(element).x/* + element.offsetWidth/2*/);
    pop.style.top = (nitobi.Debug.getCoords(element).y + 15) + "px";
    pop.style.left = leftOffset + "px";
    pop.style.display = "inline";
    pop.focus();
    nitobi.isPopupVisible = id;
    nitobi.ClickCount = 1;
    return true;
}
nitobi.getWindowSize = function()
{
    var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return {width: myWidth, height: myHeight};
  
}

nitobi.closeSplash = function(isIE6) {
    if (!isIE6) {
        $('ie8upgradesplash').style.display = 'none';
        $('whitebackground').style.display = 'none';
        clearTimeout(nitobi.timmer);
    } else {
        $('ie8fromie6').style.display = 'none';
        $('ie8upgradeother').style.display = 'none';
        $('whitebackground').style.display = 'none';
        clearTimeout(nitobi.ie6timmer);
    }
}

nitobi.createCookie = 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 var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

nitobi.readCookie = 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;
}

nitobi.eraseCookie = function (name) {
	createCookie(name,"",-1);
}

window.addEvent('domready', function() {
    if ($$('#recaptcha_widget_div IMG').length > 0)
    {
        $$('#recaptcha_widget_div IMG')[0].alt='Captcha';
        $$('#recaptcha_widget_div INPUT')[1].title='Type the two words:';
        var list = $$('#recaptcha_area a[tabindex=-1]', 'recaptcha_area');
        for(var i=0;i<list.length;i++) {
            list[i].tabIndex = "0";
        }
        // Move all the hidden labels out of the label element otherwise Jaws will read them
        $$('LABEL.recaptcha_input_area_text SPAN').each(function(e) {if (e.getStyle('display') == 'none') {e.parentNode.parentNode.appendChild(e);}});
        $$('#recaptcha_switch_img_btn').addEvent('click', function() {
            // Swap the text label and audio label text
            $$('LABEL.recaptcha_input_area_text')[0].appendChild($('recaptcha_instructions_image'));
            $$('.recaptcha_input_area')[0].appendChild($('recaptcha_instructions_audio'));
        });
        $$('#recaptcha_switch_audio_btn').addEvent('click', function() {
            // Swap the text label and audio label text
            $$('LABEL.recaptcha_input_area_text')[0].appendChild($('recaptcha_instructions_audio'));
            $$('.recaptcha_input_area')[0].appendChild($('recaptcha_instructions_image'));
        });
    }
});

document.onclick = function(e) {            
    try {
        if (nitobi.isPopupVisible) {
            var tgt = e.target;
            nitobi.ClickCount--;
            var pop = $(nitobi.isPopupVisible + "Popup");
            if (nitobi.ClickCount < 0 && tgt != pop) {
                pop.onblur.call();
            }
        }
        if (nitobi.isMenuVisible) {
            nitobi.ClickCount--;
            var menuObject = nitobi.isMenuVisible;
            if (nitobi.ClickCount < 0) {
                menuObject.detail.style.display = "none";
                nitobi.isMenuVisible = false;
            }
        }
    } catch(e) {}
};

window.addEvent('load', function() {$$('.install').addEvent('onclick',prompt_upgrade);});
function prompt_upgrade() {
    var cookie = nitobi.readCookie("SplashDisabled");
    if (!cookie) {    
        nitobi.createCookie("SplashDisabled","true",1);
        try {
            var browser = navigator.appVersion;
            if (browser.indexOf('MSIE 7.0') > -1) {
                if (!XDomainRequest) {
                    setTimeout("nitobi.showSplash();", 2000);
                }
            } else if (browser.indexOf('MSIE 6') > -1) {
                setTimeout("nitobi.showSplash();", 2000);
            }
            if (browser.indexOf('MSIE') < 0) {
               setTimeout("nitobi.showSplash();", 2000);
            }
        } catch(e) {
            setTimeout("nitobi.showSplash();", 2000);
        }
    }
}

function closeLocaleNotification(){
    if ($('localeNotification')) {
        $('localeNotification').style.display = 'none';
        nitobi.createCookie('localeNotificationDisabled', "true", 1000);
    }
    return false;
}

function loadLocaleNotification(){
    if ($('localeNotification')) {
        $('localeNotification').style.display = nitobi.readCookie('localeNotificationDisabled') != null ? 'none' : '';
    }
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
        oldonload();
        func();
        }
    }
}
addLoadEvent(loadLocaleNotification);
