var caution = false;

function setCookie(name, value, expires, path, domain, secure)
{
	var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
	
	if (!caution || (name + "=" + escape(value)).length <= 4000) {
		document.cookie = curCookie;
	} else {
		if (confirm("Cookie exceeds 4KB and will be cut!")) {
			document.cookie = curCookie;
		}
	}
}

function fixDate(date)
{
	var base = new Date(0);
	var skew = base.getTime();
	if (skew > 0) { date.setTime(date.getTime() - skew); }
}

function getCookie(name)
{
	var prefix = name + "=";
	var cookieStartIndex = document.cookie.indexOf(prefix);

	if (cookieStartIndex == -1){return null;}
	var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
	if (cookieEndIndex == -1){cookieEndIndex = document.cookie.length;}
	return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

var now = new Date();
fixDate(now);
now.setTime(now.getTime() + 24 * 60 * 60 * 1000 );
var current_cc_referrer = getCookie("cc_referrer");

if ((!(current_cc_referrer)) ||
    (current_cc_referrer=='no referrer') ||
    (current_cc_referrer=='bookmarked or typed') ||
    ((document.referrer) &&
        (document.referrer.substring(0,7)=='http://') &&
        (document.referrer.substring(7,23)!='www.onesite.com/') &&
        (document.referrer.substring(7,27)!='hosting.catalog.com/'))) {
	if (!(document.referrer)){
		setCookie("cc_referrer",'bookmarked or typed',now,'/',".onesite.com");
	}else{
		setCookie("cc_referrer",document.referrer,now,'/',".onesite.com");
	}
}
function goPop(url, wide, high)
{
	window.open(url,"popup",'width=' + wide + ',height=' + high);
}

/********************************************************************
** displays the login or find form in the toolbar and hides the other
*********************************************************************/
function toggleLoginSearch( goDo )
{
	formFind = document.getElementById("tbFindPeople");
	formLog = document.getElementById("tbLogin");
	
	if ( goDo == "login" ) {
		
		formFind.style.display = "none";
		formLog.style.display = "inline";
		
		document.loginForm.username.focus();

	} else if ( goDo == "find" ) {
		
		formFind.style.display = "inline";
		formLog.style.display = "none";

	}
	
	return false;
}

/**
* Submits a given form on the "enter" keypress. Used b/c different browsers
* handle the enter key in different ways. Especially if there are multiple forms
* on the page.
*/
function entsub(myform) 
{     
	if (window.event && window.event.keyCode == 13) {
		myform.submit();
		return false; //return false until i can fix this problem
	} else {
		return true;
	}
}


/*
* From toolbar common
*/
function confirm_prompt(text,link) {
    if (confirm(text)) {
      window.location = link;
    }
}

function submitenter(field,e)
{
    var keycode;
    if (window.event) {keycode = window.event.keyCode;}
    else if (e) {keycode = e.which;}
    else {return true;}
    
    if (keycode == 13)
       {
       field.submit();
                    if (field.name == 'Terms'){
                            opencontent('sc4');
                    }
       return false;
       }
    else
    {
       return true;
    }
}
function closecontent(eid)
{
    document.getElementById(eid).style.display="none";
}

function opencontent(eid)
{
    document.getElementById(eid).style.display="block";
}

function menuexpander(me, length) 
{
	for(i=1;i<=length;i++)
	{
		var uls = document.getElementById("ulmenuitem" + i);
		if(uls)
		{
			uls.style.display = "none";
		}
	}
	
	var ul = document.getElementById("ul" + me.id);
	if(ul.style.display == "none") {
		ul.style.display = "block";
	 }
	else {
		ul.style.display = "none";
	}
	return false;
}



/*  initialize friend search loaded file to false */
var friend_search_loaded = false;
/* initialize and load all of the functions necessary for using the "friend search" with the "send to friend" */
function friend_search_for_send_to_friend(content_id,link,sendtofriend_ajax,friend_search_ajax,sendtofriend_server,friendsearch_server)  {

	//if not already loaded...load files necessary
	if(friend_search_loaded===false)  {	
 		
		//dynamically append the send to friend div
		var sendtofriend = document.createElement('div');
		sendtofriend.setAttribute('id', 'sendtofriend_div');		
		sendtofriend.setAttribute('style', 'display:none;');
		document.body.appendChild(sendtofriend);
		
		//dynamically append the friend search holder
		var friendsearchholder = document.createElement('div');
		friendsearchholder.setAttribute('id', 'friendSearchHolder');		
		document.body.appendChild(friendsearchholder);
		
		dynamicLoadFile(sendtofriend_ajax,'js');	
		dynamicLoadFile(friend_search_ajax,'js');				
		
		friend_search_for_send_to_friend_loader(sendtofriend_server,friendsearch_server,content_id,link);		
	
		friend_search_loaded = true;
							
	} else {  
		
		//already loaded, so, just format it		
		format_friend_search_div(content_id); 
	}
	
}

//function to load div...logic built in to not actually call the div loader function until the js lib is loaded completely.
function friend_search_for_send_to_friend_loader(sendtofriend_server,friendsearch_server,content_id,link) {
	//see if js file is loaded
	if (!window.process_load_friend_search_div||!window.format_friend_search_div) {
  		//wait .5 seconds and try again
  		
  		setTimeout('friend_search_for_send_to_friend_loader(\''+sendtofriend_server+'\',\''+friendsearch_server+'\',\''+content_id+'\',\''+link+'\')',500);
  		return;
	}
	
	//process_load_friend_search_div(url,cid,link,act)
	process_load_friend_search_div(sendtofriend_server,friendsearch_server,content_id,link,'load');
}

/*  general message to let users know they must log in to access a feature  

relative_to_elem ~ the element that the loading element is set relative to
element ~ the element being loaded
x ~ the x offset
y ~ the y offset
*/
function must_login_to_access(relative_to_elem,element,x,y)  {
	document.getElementById(element).innerHTML = 'You must Login or Sign Up to access';
	
	//alert(document.getElementById(element).innerHTML);
	setPosition(relative_to_elem,element,x,y);
	
	document.getElementById(element).toggle();
}


/*******************************************************************************
* Get the x and y coordinates of the given element.
*/
function getElementCoordinates(obj) {
	var point = { x: 0, y: 0 }; 
	  
	while(obj) {
	    point.x += obj.offsetLeft ;
	    point.y += obj.offsetTop;
	    obj = obj.offsetParent;
	} 
  
	return point;
}

/*  set the position of an element (such as a div) based on the location of another element  */
function setPosition(x,e,offset_left,offset_top)  {
	var pos = getElementCoordinates(e);

	//Make sure the new coordinates won't be off the left or top of the page
	if(pos.x-offset_left<=0){pos.x=1;}
	else{pos.x=pos.x-offset_left;}
	
	if(pos.y+offset_top<=0){pos.y=1;}
	else{pos.y=pos.y+offset_top;}
	
	//Set the new coordinates for element x
	document.getElementById(x).style.left = (pos.x + 'px' );
	document.getElementById(x).style.top = (pos.y + 'px');

}

/***********************************************************************************************/
/***************** FUNCTIONS FOR DYNAMICALLY LOADING AND TOGGLING FILES ***********************/
/*********************************************************************************************/

/*Dynamically loads a file of type 'type' (js/css) anytime during program execution.*/
function dynamicLoadFile(url,type) {
	if (type == 'js') {
  		var e = document.createElement("script");
  		e.type = "text/javascript";
  		e.src = url;
	} else if (type == 'css') {
  		var e = document.createElement("link");
  		e.type = "text/css";
  		e.rel = "stylesheet";
  		e.href = url;
	} else { return; }

	document.getElementsByTagName("head")[0].appendChild(e);
}

/************************************ FINI *****************************************************/

// Reload leaderboard ad
function oneReloadLeaderboardAd() {
	var tmpAdEl = document.getElementById('oneToolbarAdContainer');
	var tmpAdCode = tmpAdEl.innerHTML;
	tmpAdEl.innerHTML = '';
	tmpAdEl.innerHTML = tmpAdCode;
}

// Reload the Usersub TD contents (ad on some pages)
function oneReloadUsersubTdContent() {
	var tmp2AdEl = document.getElementById('usersub-td-right');
	var tmp2AdCode = tmp2AdEl.innerHTML;
	tmp2AdEl.innerHTML = '';
	tmp2AdEl.innerHTML = tmp2AdCode;
}

// Base64 encode / decode
var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = 0;
        var c1 = 0;
        var c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
};


///////////////////////////////////////////////////////////////////////////////
// Functions for Ajax Windows /////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/* This function is called when a user clicks on a button to open (launch) some Ajax Window. */
/* Attempts to load an instance of the window if it is not already created. */
var show_ajax_window = function(el, window) {
	// Return if the attributes object has not been defined for this obj
	if (typeof ajax_window_elements == 'undefined') {alert('Window attributes not found: ' + el); return;}
	if (typeof ajax_window_elements[window] == 'undefined') {alert('Window attributes not found: ' + el); return;}
	
	// See if the main js file has already been loaded
	var js_already_loaded = false;
	var eval_str = "if (typeof " + ajax_window_elements[window][el].main_js_classname + "_loaded != 'undefined' && " +
	               "typeof Mod_ajax_window_loaded != 'undefined') {js_already_loaded = true;}";
	eval(eval_str);
	
	// Get attributes object
	var cur_attr = ajax_window_elements[window][el];
	
	// Create an element to show a loading indicator (if not already created)
	if (!document.getElementById(el)) {
		if (cur_attr.display_position == 'relative') {
			var container_attr = {
				'width'      : '100%',
				'position'   : 'relative'
			};
		}
		else {
			// Get window height so we can set the top position correctly
			var myHeight = 0;
			if( typeof( window.innerWidth ) == 'number' ) {
				myHeight = window.innerHeight; //Non-IE
			}
			else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
				myHeight = document.documentElement.clientHeight; //IE 6+ in 'standards compliant mode'
			}
			
			// Get vertical scroll position to help center window
			var n_win = window.pageYOffset ? window.pageYOffset : 0;
			var n_docel = document.documentElement ? document.documentElement.scrollTop : 0;
			var n_body = document.body ? document.body.scrollTop : 0;
			var n_result = n_win ? n_win : 0;
			if (n_docel && (!n_result || (n_result > n_docel))) {
				n_result = n_docel;
			}
			var scroll_top = n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
			
			// Do the math
			var top = (myHeight / 2) - (cur_attr.container_height / 2) + scroll_top;
			if (top < 0) {top = 0;}
			
			var margin_left_value = (document.body.offsetWidth - cur_attr.container_width) / 2;
			if (margin_left_value < 0) margin_left_value = 0;
			var container_attr = {
				'width'      : cur_attr.container_width + 'px',
				'height'     : cur_attr.container_height + 'px',
				'position'   : 'absolute',
				'top'        : top + 'px',
				'left'       : '0',
				'marginLeft' : margin_left_value + 'px',
				'border'     : '1px solid #bbbbbb',
				'background' : 'white'
			};
		}
		SiteUtil.createContainer(el, container_attr, cur_attr.parent_el);
		SiteUtil.showLoading(el, cur_attr.loading_image_url);
	}
	
	// Skip loading js file if already loaded
	if (js_already_loaded) {
		// Get Window object
		eval_str = "var window_obj = " + ajax_window_elements[window][el].main_js_classname + ".singleton(el, ajax_window_elements[window][el]);";
		eval(eval_str);
		window_obj.show();
		return;
	}
	
	// See if the window js file has already been loaded
	if (typeof Mod_ajax_window == "undefined") {
		SiteUtil.dynamicLoadFile(cur_attr.aw_js_url, 'js');
	}
	
	// Otherwise, we need to load main js file
	SiteUtil.dynamicLoadFile(cur_attr.main_js_url, 'js');
	
	// Now wait for media_manager.js to load
	setTimeout(function() {
		show_ajax_window_wait(el, window);
	}, 150);
};
var show_ajax_window_wait = function(el, window) {
	// See if js file is loaded
	var js_already_loaded = false;
	var eval_str = "if (typeof " + ajax_window_elements[window][el].main_js_classname + "_loaded != 'undefined' && " +
	               "typeof Mod_ajax_window_loaded != 'undefined') {js_already_loaded = true;}";
	eval(eval_str);
	
	// Wait longer if still not loaded
	if (!js_already_loaded) {
		// Wait .4 seconds and try again
		setTimeout(function() {
			show_ajax_window_wait(el, window);
		}, 400);
		return;
	}
	
	// Get Window object
	eval_str = "var window_obj = " + ajax_window_elements[window][el].main_js_classname + ".singleton(el, ajax_window_elements[window][el]);";
	eval(eval_str);
	window_obj.show();
};

/**
 * Provides handy utilities used by other js files.
 * Defines several static methods that can be called like this:
 *   SiteUtil.methodName(var1);
 * 
 * @class SiteUtil
 */
SiteUtil = function() {
	
	return {
		
		/**
		 * Method goes here...
		 */
		showLoading: function(el, loading_image, attr) {
			// Get parent el
			var element = document.getElementById(el);
			element.style.display = 'block';
			
			// Build container for loading image
			var container = document.createElement('div');
			container.id = el + '_loadingimage';
			container.className = 'site_loadingimage';
			container.style.position = 'absolute';
			container.style.top = '1px';
			container.style.left = '1px';
			container.style.width = '99%';
			container.style.textAlign = 'center';
			container.style.zIndex = '500';
			container.innerHTML = "<img src='" + loading_image + "' />";
			
			// Assign each custom style attribute
			for (var elstyle in attr) {
				var eval_str = "container.style." + elstyle + " = '" + attr[elstyle] + "';";
				eval(eval_str);
			}
			
			//element.appendChild(container);
			element.insertBefore(container, element.firstChild);
		},
		
		/**
		 * Dynamically loads a file of type 'type' (js/css) anytime during 
		 * program execution.
		 * 
		 * @param String url   URL of file to load
		 * @param String type  Type of file being loaded [js, css]
		 */
		dynamicLoadFile: function(url, type) {
			if (type == 'js') {
		  		var e = document.createElement("script");
		  		e.type = "text/javascript";
		  		e.src = url;
			}
			else if (type == 'css') {
		  		var e = document.createElement("link");
		  		e.type = "text/css";
		  		e.rel = "stylesheet";
		  		e.href = url;
			}
			else { return; }
			
			// Append file to header
			document.getElementsByTagName("head")[0].appendChild(e);
		}, 
		
		/**
		 * Get the HTMLElement for the given id.
		 * 
		 * @param String el   Id of the element we want to get
		 */
		$: function(el) {
			return document.getElementById(el);
		},
		
		/**
		 * Attempt to create a new container (div) and append it to the parent.
		 *
		 * @param id         element_id of the new container
		 * @param attr       object of style properties to set
		 * @param parent_el  parent id to append new container to (or: document.body)
		 */
		createContainer: function(id, attr, parent_el) {
			// Create new element
			var container = document.createElement('div');
			container.id = id;
			container.className = 'siteUtilContainer';
			container.style.display = 'none';
			container.style.zIndex = '9999';
			
			// Assign each custom style attribute
			for (var elstyle in attr) {
				var eval_str = "container.style." + elstyle + " = '" + attr[elstyle] + "';";
				eval(eval_str);
			}
			
			// Get parent element
			if (parent_el == 'document.body') {
				parent_el = document.body;
			}
			else {
				parent_el = document.getElementById(parent_el);
			}
			
			// Append new element to parent
			parent_el.appendChild(container);
		}
        
	};
	
}();

//limits text input to a certain number of of characters (2nd parameter)
//e.g., <textarea onkeyup="return textInputMaxLength(this, 10000, '<?php echo _tt("You have reached the maximum length for your message."); ?>')">
function textInputMaxLength(obj, maxLength, alertMsg){
	if (obj.value.length>maxLength) {
		obj.value=obj.value.substring(0,maxLength);
		alert(alertMsg);
	}
}


/**
 *	Class:	OneScript
 *	Purpose:	Master autoloader for javascript files - allows for 
 *				on demand script loading
 *
 *				Class names are in the format FolderName_(Sub)_(Sub)..._Name
 *				based from the root dir resources/scripts/classes
 *
 *				Example Class: Send2Friend_Master 
 *				Location:		resources/scripts/classes/send2friend/Master.js
 */
var OneScript = {
		
	/**
	 *	The main root directory for all onesite javascript classes
	 *
	 *	@var string
	 */
	_jsRootDir : null,
	
	/**
	 *	The main root directory for all onesite CSS files
	 *
	 *	@var string
	 */
	_cssRootDir : null,	
	
	/**
	 *	The current version number of the js
	 *
	 *	@var string
	 */
	_version : null,		
	
	/**
	 *	The class to load
	 *
	 *	@var string
	 */
	_className : null,
	
	/**
	 *	The function to call on load
	 *
	 *	@var string
	 */
	_functionName : null,
	
	/**
	 *	Tracking array to see if a class has been loaded
	 *
	 *	@var array
	 */
	_classList : null,
	
	/**
	 *	Tracks if the init function has been loaded
	 *
	 *	@var bool
	 */
	 _initLoaded : false,
	
	/**
	 *	Event that fires after the script is loaded
	 *
	 *	@var YAHOO.util.CustomEvent
	 */
	scriptLoaded :null,	
	
	/**
	 *	Event that fires after there is an error loading the script
	 *
	 *	@var YAHOO.util.CustomEvent
	 */		
	scriptError : null,		
	
	/**
	 *	Event that fires after the script is loaded
	 *
	 *	@var YAHOO.util.CustomEvent
	 */		
	classExists : null,		
	
	/**
	 *	Function:	init
	 *	Purpose:		Initialize the loader
	 *
	 */
	init : function() {
		
		//Initialize the events
		OneScript.scriptLoaded = new YAHOO.util.CustomEvent("scriptLoaded");
		OneScript.classExists = new YAHOO.util.CustomEvent("classExists");
		OneScript.scriptError = new YAHOO.util.CustomEvent("scriptError");
		 
		//Define the root directory for JS classes and CSS files	 
		OneScript._jsRootDir = baseJsUrl + 'classes/';
		OneScript._cssRootDir = baseCssUrl;
		OneScript._version = oneVersion;
		
		//Clear out the classList array
		OneScript._classList = [];
				
		//Listen for the script load and error events
		OneScript.scriptLoaded.subscribe(OneScript.onScriptLoad);
		OneScript.classExists.subscribe(OneScript.onScriptLoad);
		OneScript.scriptError.subscribe(OneScript.onScriptError);	
		
		//Mark that script is initialized
		OneScript._initLoaded = true;
	},	 
	 
	/**
	 *	Function:	exec
	 *	Purpose:		To call any class function from any userEvent on
	 *					page, this function will auto-include the source
	 *					file needed.  If the file has already been included,
	 *					then the funciton will just be called
	 *
	 *					Sample Call: 
	 *						OneScript.exec('Send2Friend_Master','buildWindow',81793421,'http://url_here');
	 *
	 *						(This will call the buildWindow function of the Send2Friend_Master class, with 
	 *						the source file located in resources/scripts/classes/send2friend/Master.js)
	 *	
	 *	@params unknown ~Passes in any number of args, but first 2 are class,function
	 *	@return void
	 */
	exec : function() {
		
		//Make sure the class has been initialized
		if(!OneScript._initLoaded) {
			OneScript.init();
		}
		 
		//Grab the number of arguments
		var numArgs = OneScript.exec.arguments.length;

		//make sure there are enough args
		if(numArgs < 2) {

			alert('minimun number of args - 2 (ClassName,FunctionName)');
			return;
		}

		//Convert the magic arguments object to array
		var argList = [];
		
		//Loop through and grab the argements - create array primitive
		for(var i=0 ; i<numArgs ; i++) {
			
			argList.push(OneScript.exec.arguments[i]);	
		}

		//Grab the first 2 args and set as class and function
		OneScript._className = argList.shift();
		OneScript._functionName = argList.shift();

		//Make sure the class name is a script
		if((typeof OneScript._className) != 'string') {

			alert('Classname not a string');
			return;
		}

		//Make sure the function is a string
		if((typeof OneScript._functionName) != 'string') {

			alert('Function not a string');
			return;
		}		 
		
		//Check if the class already exists
		if(OneScript.isClassLoaded(OneScript._className)) {
			
			//Fire the classExists event and break
			OneScript.classExists.fire(argList);
			return;
		}
		else {
			
			//Parse the script name and try to include it
			var script = OneScript.parseClassName(OneScript._className);
			script += '?ver=' + OneScript._version;

			//Invalid class name or other error
			if(!script) {
				
				OneScript.scriptError.fire(null);
				return;
			}
			
			//Set up the options
			var opts = { onSuccess: OneScript.scriptLoadSuccess,
							 onFailure: OneScript.scriptLoadFail,
							 data : argList
						  };
							 
			//Try to get the script
			var objTransaction = YAHOO.util.Get.script(script,opts);			
			return;
		}		 
	},
	 
 	/**
    *	Function:	parseClassName
    *	Purpose:		Parse the class name to determine a full path of
    *					the script
    *
    *	@param string class ~The actual classname
    *	@return string ~The directory structure
    */
	parseClassName : function(className) {
		 
		//Explode the class string
		var dirList = className.split('_');
		
		//Make sure that there is at least a folder and filename
		if(dirList.length < 2) {
			
			alert('Invalid class name');
			return false;
		}
		
		//Grab the file and the directory
		var fileName = dirList.pop();
		var dirStructure = dirList.join('/');
		
		//Parse for lowerCamelCase
		var firstLetter = dirStructure.charAt(0).toLowerCase();
		dirStructure = firstLetter + dirStructure.substring(1);
		
		return OneScript._jsRootDir + dirStructure + '/' + fileName + '.js';
	},
	
	/**
	 *	Function:	onScriptLoad
	 *	Purpose:		Route the initial request
	 *
	 */
	onScriptLoad : function(type,fired,subscribed) {
		
		//Grab pass-through params
		var args = fired[0];
		
		//Store the class name (if new load)
		if(type == 'scriptLoaded') {
			
			OneScript._classList.push(OneScript._className);
		}

		//Build the actual call
		var classFunc = OneScript._className + '.' + OneScript._functionName;
		var callParams = []; 
		
		//Loop through and preserve the type of each param
		for(var i=0 ; i<args.length ; i++) {
			
			var singleParam = args[i];
		
			//If it is a string, append quoutes
			if((typeof singleParam) == 'string') {
				
				singleParam = "'" + singleParam + "'";
			}
			else if(((typeof singleParam) == 'object')){
				
				singleParam = YAHOO.lang.JSON.stringify(singleParam);  
			}
		
			//Add to the running array or params
			callParams.push(singleParam);		
		}
		
		//Build the string for the call
		var paramString = callParams.join(',');
		var fullCall = classFunc + '(' + paramString + ');';		
		
		//Make the actual function call		
		return eval(fullCall);
	},
	
	/**
	 *	Function:	onScriptError
	 *	Purpose:		Quietly stop execution on error
	 *
	 *	@param string type ~The type of event fired
	 *	@param unknown fired ~Data passed when the event fired
	 *	@param unknown subscribed ~Data passed when the event was subscribed to
	 *	@return void		 
	 */
	onScriptError : function(type,fired,subscribed) {

		return;		
	},
	
	/**
	 *	Function:	isClassLoaded
	 *	Purpose:		Check to see if the class has already been loaded
	 *
	 *	@param string className ~The name of the class to check for
	 *	@return bool ~True if the class exists, false otherwise
	 */
	isClassLoaded : function(className) {

		//Loop through and look for the script
		for(var i=0 ; i<OneScript._classList.length ; i++) {
			
			if (className == OneScript._classList[i]) {
				return true;
			}
		}
		return false;	
	},
		
	/**
	 *	Function:	loadCSS
	 *	Purpose:		General wrapper for YUIs loading a css funtion
	 *
	 *	@param string file ~The filename to load
	 */
	loadCSS : function(file,opts) {
		
		//Build the filename
		var fileName = "";
		
		//Build the full filename
		if('fullScriptName' in opts) {
			
			if(opts['fullScriptName']) {
				
				//Full script name included - don't append root
				fileName = file;
			}
			else {
				
				//Needs root - append
				fileName = OneScript._cssRootDir + file + '?ver=' + OneScript._version;
			}
			
			//Clear the option
			delete opts['fullScriptName'];
		}	
		else {

			//Needs root - append
			fileName = OneScript._cssRootDir + file + '?ver=' + OneScript._version;
		}		
							
		var objTransaction = YAHOO.util.Get.css(fileName,opts);
		return;		
	},
	
	/**
	 *	Function:	loadScript
	 *	Purpose:		General wrapper for YUIs loading a script funtion
	 *
	 *	@param string file ~The filename to load
	 *	@param unknown opts ~The callback options
	 */
	loadScript : function(file,opts,fullScript) {
		
		//Build the filename
		var fileName = "";
		
		//Build the full filename
		if(fullScript === true) {
			
			fileName = file;
		}	
		else {

			//Needs root - append
			fileName = OneScript._jsRootDir + file + '?ver=' + OneScript._version;
		}		
		
		var objTransaction = YAHOO.util.Get.script(fileName,opts);
		return;		
	},
	
	// Callback to fire the scriptLoaded event on YUI get success
	scriptLoadSuccess : function(o) {

		OneScript.scriptLoaded.fire(o.data);
		return;		
	},
	
	// Callback to fire the scriptError event on YUI get failure
	scriptLoadFail : function(o) {

		OneScript.scriptError.fire(o.data);
		return;		
	}	
};

/**
*	Object:		OneAjax
*	Purpose:		Generic object to handle and route AJAX requests on the
*					onesite platform
*
*	@author Mike Benshoof <mbenshoof@onesite.com>
*/
var OneAjax = {
	
	//Required Request Configuration
	_ajaxPath : '/resources/ajax/_router.one',
	_method : 'POST',
	_requestType : 'service',
	_handlerName : null,
	_responseFunction : null,
	_action : null,
	
	//Response Configuration
	_responseType : 'XML',		
	
	//User Passed Params
	_params : null,	
	
	//Holds generated data to pass to string
	_varString : null,
	
	//Varible to determine if request is valid
	_isValid : true,	
	
	//Holds any extra vars to pass to handling function
	_extraVars : null,
	
	/**
	*	Function:	request
	*	Purpose:		Build the param string to pass to the handling function, 
	*					make the AJAX call, and route the response
	*
	*	@param array params ~Array of parameters to build the request/response
	*/
	request : function(params) {

		/*
		*	Check for all the required parameters:
		*		-responseFunction
		*		-action
		*	If they exist, set them in the object and remove from
		*	from the array of params - otherwise, stop processing
		*/
		if(('responseFunction' in params) && ('action' in params) && ('handlerName' in params)) {
			
			this._responseFunction = params['responseFunction'];
			this._action = params['action'];
			this._handlerName = params['handlerName'];
			delete params['responseFunction'];
			delete params['action'];
			delete params['handlerName'];
		}	
		else {

			return;
		}

		//Store the user params and update optional params passed by user
		this._params = params;		
		this._setOptionalVars();
				
		//Set up the initial parser function based on the response type (ie xml)
		switch (this._responseType) {
			
			case 'XML':
				var handlerFunction = this.parseXmlResponse;
				break;
			case 'JSON':
				var handlerFunction = this.parseJsonResponse;
				break;
			case 'text':
				var handlerFunction = this.parseTextResponse;
				break;
			default:
				var handlerFunction = this.parseXmlResponse;
				break;				
		}

		//Generate the variable string to pass for the AJAX request
		this._generateVarString();
		
		//Check to make sure that the request is valid
		if(this._isValid === false) {
			
			return;
		}
		
		//Build the argument to pass to the handler function
		var passArgument = new Array();
		passArgument['responseFunction'] = this._responseFunction;
		passArgument['extraVars'] = this._extraVars;
		
		//Make the AJAX request, passing addition post process params
		var request = YAHOO.util.Connect.asyncRequest(	this._method, 
																		this._ajaxPath, 
																		{
																			success: handlerFunction, 
																			failure: this._genericFail, 
																			argument: passArgument
																		}, 
																		this._varString);		
	},	
	
	/**
	*	Function:	_setOptionalVars	
	*	Purpose:		Check for the optional parameters
	*						-ajaxPath (custom path)
	*						-responseType (XML,JSON,Text)
	*						-requestType (service or class)
	*						-serviceName (needed if type is service)
	*						-className (needed if type is class)
	*					If an param exists, then set it in the object, overwriting 
	*					the default and remove it from the params array
	*
	*	@return void
	*/
	_setOptionalVars : function() {	
		
		//Check for a user passed path
		// /resources/ajax/_router.one by default
		if('ajaxPath' in this._params) {
			
			this._path = this._params['ajaxPath'];
			delete params['ajaxPath'];
		}
		
		//Check for a user passed response type
		// *XML by default
		if('responseType' in this._params) {
			
			this._responseType = this._params['responseType'];
			delete this._params['responseType'];
		}	
		
		//Check for a user passed request type 
		// *Service by default
		if('requestType' in this._params) {
			
			this._requestType = this._params['requestType'];
			delete this._params['requestType'];
		}
		
		//Check for extra, pass through vars
		if('extraVars' in this._params) {
			
			this._extraVars = this._params['extraVars'];
			delete this._params['extraVars'];
		}
		
		return;
	},	
	
	/**
	*	Function:	_generateVarString
	*	Purpose:		Validate the variable string based on the request type
	*					and then build the variable string to pass to the router
	*					with all arbitrary params passed in
	*
	*	@return void
	*/
	_generateVarString : function() {
		
		//Initialize the post string and create
		this._varString = 'action=' + this._action;
		this._varString += '&requestType=' + this._requestType;
		this._varString += '&handlerName=' + this._handlerName;
	
		//Loop through all the params, remove any that are functions, and
		//append to the param string to pass to the router
		for (key in this._params) {
			
			//Grab the type of the value
			var valType = typeof this._params[key];
			
			//Strip out functions from array prototype
			if(valType !== 'function') {
				
				this._varString += '&' + key + '=' + this._params[key];
			}			
		}	
		
		//Exit the function
		return;		
	},
		
	/**
	*	Function:	parseXmlReponse
	*	Purpose:		Parse the response text from the AJAX request as 
	*					an XML document and pass the xml object to the 
	*					main handling function
	*
	*	@param object o ~The YUI Ajax response object
	*	@return object ~The response text parsed as an xml object
	*/
	parseXmlResponse : function(o) {

		//Grab the parameters passed
		var params = o.argument;
		
		//Parse the response function and extra, pass through vars
		responseFunc = params['responseFunction'];
		extra = params['extraVars'];
		
		//Return the XML object from the response object
		responseFunc(o.responseXml,extra);
	},	

	/**
	*	Function:	parseJsonReponse
	*	Purpose:		Parse the response text from the AJAX request as 
	*					a JSON encoded array and pass the actual array to the 
	*					main handling function
	*
	*	@param object o ~The YUI Ajax response object
	*	@return array ~The response text parsed as an array
	*/
	parseJsonResponse : function(o) {
		
		try {
			
			//Try to parse the response into an array
			var resultArray = eval('(' + o.responseText + ')');
		}
		catch(e) {
			
			//Caught an exception - alert the message
			return;
		}
		
		//Grab the parameters passed
		var params = o.argument;
		
		//Parse the response function and extra, pass through vars
		responseFunc = params['responseFunction'];
		extra = params['extraVars'];
		
		//Pass the resulting array to the original handling function
		responseFunc(resultArray,extra);
		
	},	

	/**
	*	Function:	parseTextReponse
	*	Purpose:		Simply pass the text value of the YUI response
	*					value back to the main handling function
	*
	*	@param object o ~The YUI Ajax response object
	*	@return string ~The response text as a string
	*/
	parseTextResponse : function(o) {
		
		//Grab the parameters passed
		var params = o.argument;
		
		//Parse the response function and extra, pass through vars
		responseFunc = params['responseFunction'];
		extra = params['extraVars'];		
		
		//Simply pass the text back to the original handling function
		responseFunc(o.responseText,extra);
		
	},	
	
	/**
	*	Function:	_genericFail
	*	Purpose:		Catch all function that will stop processing after
	*					a failure without calling the main handling function
	*
	*	@param object o ~The YUI Ajax response object
	*	@return void	
	*/
	_gerericFail : function(o) {
		
		//alert('Failed Ajax Request');
		return;
	}		

};//End of OneAjax object


/**
 * Calls Ajax heartbeat function to heartbeat the current user on given heartbeatKeys
 *
 * @var string heartbeatKeys  CSV keys for heartbeats (for a page, forum, blog etc...)
 */
function one_heartbeat(heartbeatKeys)
{
	var params = new Array();

	// Empty response function is required by OneAjax
	params['responseFunction'] = function(response){};
	params['requestType']      = 'class';
	params['action']           = 'beat';
	params['responseType']     = 'JSON';
	params['handlerName']      = 'one_ajax_heartbeat';
	params['heartbeatKeys']     = heartbeatKeys;

	OneAjax.request(params);
};

/**
 *	Utility functions
 *
 */
var OneUtil = {
	
	getElementsByName : function(elmName) {
		
		var agt=navigator.userAgent.toLowerCase();
		
		if (agt.indexOf("msie") != -1) {

			return YAHOO.util.Dom.getElementsBy(function(el) {														
								if(el.name == elmName) {
										return true;
								}
							});	
		}
		
		else {

			return document.getElementsByName(elmName);	
		}				
	}	
};