var GLOBAL_VARS ={} //temporary cache for any global var usage. please do not erase.


/***************** LoggedInState *******************/		
/*** To Turn certain divs into hidden depending on **/
/**logged in state **/
var LoggedInState = 
{
	verify:	function()
	{
		if(isLoggedIn != undefined && isLoggedIn){
			LoggedInState.hideElements('div.loggedOutUser');
			LoggedInState.showElements('div.loggedInUser');			
		}
		else
		{
			LoggedInState.hideElements('div.loggedInUser');
			LoggedInState.showElements('div.loggedOutUser');
		} 
	},	
	
	hideElements:	function(elements)
	{
		eleArray = $$(elements);				
		
		for (var i = 0;i<eleArray.length;i++)
		{
		  eleArray[i].style.display="none";
		}
	},
	
	showElements:	function(elements)
	{
		eleArray = $$(elements);
		
		for (var i = 0;i<eleArray.length;i++)
		{
		  eleArray[i].style.display="block";
		}
	}
}



/***************** OwnerViewState *******************/		
var OwnerViewState = 
{
	verify:	function()
	{
	
		var currentUserUid = OwnerViewState.getCookie("Uid");

		if(typeof(_userUcid) != undefined)
		{ 
			if(_userUcid != "" && currentUserUid != "" && currentUserUid == _userUcid)
			{			
				
				OwnerViewState.showElements('div.isOwnerView');			
			}else
			{
				OwnerViewState.hideElements('div.isOwnerView');
			}
		}
		else
		{
			OwnerViewState.hideElements('div.isOwnerView');
		} 
	},	
	
	hideElements:	function(elements)
	{
		eleArray = $$(elements);				
		
		for (var i = 0;i<eleArray.length;i++)
		{
		  eleArray[i].style.display="none";
		}
	},
	
	showElements:	function(elements)
	{
		eleArray = $$(elements);
		
		for (var i = 0;i<eleArray.length;i++)
		{
		  eleArray[i].style.display="block";
		}
	},

	getCookie:	function(c_name)
	{
		if (document.cookie.length>0)
		  {
		  c_start=document.cookie.indexOf(c_name + "=");
		  if (c_start!=-1)
			{ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
			} 
		  }
		return "";
	}	
	
}





var UTILS = {	
	/***************** ELLIPSIS / TRUNCATE TEXT *******************/		
	/***USAGE: "elementID" is the element you want to operate on***/
	/***"length" is the length you want the element to truncate at*/
	/**************************************************************/
	truncateText: function(elementId, truncateLength){ 				
		var p = document.getElementById(elementId);
		if (p) {			
		  var trunc = p.innerHTML;
		  if (trunc.length> truncateLength) {
		  
			/* Truncate the content of the element, then go back to the end of the
			   previous word to ensure that we don't truncate in the middle of
			   a word */
			trunc = trunc.substring(0, truncateLength);
			trunc = trunc.replace(/\w+$/, '');

			/* Add an ellipses to the end and make it a link that expands
			   the paragraph back to its original size */
			trunc += '<a href="#" ' +
			  'onclick="this.parentNode.innerHTML=' +
			  'unescape(\''+escape(p.innerHTML)+'\');return false;">' +
			  '...<\/a>';			
			p.innerHTML = trunc;
		  }
		}
	},
	
	/************** LISTEN ON KEYSTROKE *******************/
	keyListener: function (evnt, element)	
	{	
		var processKey = {			
			enter:	function(element)
			{
				switch(element.id){
					//search in header
					case "search_input":
						submitSearch(document.getElementById('search_input'),document.getElementById('searchType').value);
						break;
						
					//search in user search page
					case "search_input_user":
						submitSearch(document.getElementById('search_input_user'),document.getElementById('searchType').value);
						break;
						
					//search in search page
					case "search_input_content":
						submitParametricSearch();
						break;
					
					//Vote Button
					default: 						
						var tempId = (element.id).substring(("captchaInput").length, (element.id).length);
						eval("window."+tempId+".processMessageBox('submitCaptchaAndCast')");
						break;
				}
			}
		}		
		
		if(!evnt){evnt = window.event;} //for IE	   			
		switch(evnt.keyCode)
		{
			case 13: processKey.enter(element);break; //enter key
		}
		
		
	}


}

function refreshParent(){ 
	var parentLoc = window.parent.location.href;
	if (parentLoc.substring(parentLoc.length-1,parentLoc.length) == "#") parentLoc = parentLoc.substring(0,parentLoc.length-1);
	window.parent.location.href = parentLoc;
};

function signOff(){
	var repopulate = false;
	olLogin.onHide = refreshParent;
	olLogin.populate('/sitewide/inc/overlay/login.jhtml?hdrType=simple&login=out','iframe');
	olLogin.show(repopulate);
	/*
	var loginForm = document.loginForm;
	if (loginForm){
		loginForm.login.value = "out";
		loginForm.submit();
	}
	*/
	/*
	var logoutString = "?login=out";
	if (location.href.indexOf("?") >= 0 || location.href.indexOf("com/media/") >= 0 || location.href.indexOf("com/profile/") >= 0 ) { logoutString = "&login=out"}
	var logoutUrl = location.href + logoutString;
	window.location.replace(logoutUrl);
	*/
}

function signupCancel(){
	window.location='/';
}

function getEventTarget(e){
	var targ;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
		
	return targ;
}

function checkExtension(fileName,ext){
	var _ext = fileName.substring(fileName.length-4,fileName.length);
	var _accepted = false;
	for (var i=0; i < ext.length; i++){
		if (_ext.toLowerCase() == ext[i].toLowerCase()) _accepted = true;
	}
	return _accepted;
}

function drawHover(container, newDivId, msg, w, h, tOffset, lOffset, divClassName){ //#### No longer used.
	var drawnDiv;
	if ($(newDivId)){
		var el = document.getElementById(newDivId);
		el.parentNode.removeChild(el);
	}

	contDiv = $(container);
	contDivTop = Position.cumulativeOffset(contDiv)[1];
	contDivLeft = Position.cumulativeOffset(contDiv)[0];
	
	drawnDiv = document.createElement('div');
	drawnDiv.id = newDivId;
	drawnDiv.style.position = "absolute";
	if (divClassName){
		drawnDiv.className = divClassName;
	}else{
		drawnDiv.className = 'drawnDivs'
	}
	iFrameBlock = document.createElement('iframe');
	iFrameBlock.src = "http://" + location.host + "/sitewide/inc/blank.html";
	//iFrameBlock.style.position = "absolute";
	iFrameBlock.style.border = '0px';
	//iFrameBlock.style.top = '0px';
	//iFrameBlock.style.left = '0px';
	iFrameBlock.style.height = h + 'px';
	iFrameBlock.style.width = w + 'px';
	//iFrameBlock.style.visibility = 'hidden';
	innerDiv = document.createElement('div');
	innerDiv.className = 'opaquetext';
	innerDiv.style.position = "absolute";
	innerDiv.style.top = '0px';
	innerDiv.style.left = '0px';
	innerDiv.innerHTML = msg;
	drawnDiv.appendChild(iFrameBlock);
	drawnDiv.appendChild(innerDiv);
	
	document.body.appendChild(drawnDiv);
	Element.hide(drawnDiv);
	drawnDiv.style.top = (contDivTop + tOffset) + 'px';
	drawnDiv.style.left = (contDivLeft + lOffset) + 'px';
	drawnDiv.style.height = h + 'px';
	drawnDiv.style.width = w + 'px';
	
	return drawnDiv;
}

function clearText(thefield){
	if (thefield.defaultValue==thefield.value)
	thefield.value = "";
}

function restoreText(thefield){
	if (thefield.value=='')
	thefield.value = thefield.defaultValue;
}


function rmTags(oldString){
	newString = oldString.replace(new RegExp('<','g'), "&amp;lt;");
	newString = newString.replace(new RegExp('>','g'), "&amp;gt;");
	return newString;
}
function rmTags2(oldString){
	newString = oldString.replace(new RegExp('<','g'), "&lt;");
	newString = newString.replace(new RegExp('>','g'), "&gt;");
	return newString;
}

function rstTags(oldString){
	newString = oldString.replace(new RegExp('&lt;','g'), "<");
	newString = newString.replace(new RegExp('&gt;','g'), ">");
	return newString;
}

function stripHTML(oldString) {
  return oldString.replace(/<&#91;^>&#93;*>/g, "");
}

function validateNotEmpty( strValue ) {
	var strTemp = strValue;
	strTemp = trimAll(strTemp);
	if(strTemp.length > 0){	
		return true; 
	}
	return false;
}

function checkEmail(f){
	testresults = false;
	e1=f.email.value;
	e2=f.emailConfirm.value;
	filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if ((filter.test(e1) && filter.test(e2)) && e1 == e2)
		testresults=true;
	else
		testresults=false;
	
	return (testresults);
}

function validateZIP(field)  {
	var valid = "0123456789-";
	var hyphencount = 0;
	
	if (field.length!=5 && field.length!=10) {
		//alert("Please enter your 5 digit or 5 digit+4 zip code.");
		return false;
	}
	for (var i=0; i < field.length; i++) {
		temp = "" + field.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1") {
			//alert("Invalid characters in your zip code.  Please try again.");
			return false;
		}
		if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
			//alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
			return false;
		}
	}
	return true;
}

function clearTextPro(t){
	if (t.defaultValue==t.value) t.style.color = '#000';
	clearText(t);
}
function restoreTextPro(t){
	if (t.value=='') t.style.color = '#A5ABBB';
	restoreText(t);
}


function buttonDivUpdate(divId, msg, effect){
	if ($(divId)){ // update button if they're on edit profile page
		$(divId).update(msg);
		if (effect){ new Effect.Highlight($(divId)); }
	}
}


function parseUri(sourceUri){
    var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
    var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
    var uri = {};
    
    for(var i = 0; i < 10; i++){
        uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
    }
    
    // Always end directoryPath with a trailing backslash if a path was present in the source URI
    // Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
    if(uri.directoryPath.length > 0){
        uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
    }
    
    return uri;
}

function trimAll( strValue ) {
/************************************************
DESCRIPTION: Removes leading and trailing spaces.

PARAMETERS: Source string from which spaces will
  be removed;

RETURNS: Source string with whitespaces removed.
*************************************************/
 var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }

   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}


function checkURLAvail(ln){
	var checkButton = $('checkAvail');
	if (checkButton){
		//$('checkAvail').setAttribute("src","/sitewide/img/buttons/btn-accounts-checking.gif")
		checkButton.update("Comprobando...");
		checkButton.setStyle({backgroundColor:"#666"});
	};
	//ln = document.signup.loginName.value;
	new Ajax.Request('/sitewide/inc/profile/accounts/isLoginAvail.jhtml?url='+ln, {
		method: 'get',
		contentType: 'text/xml',
		onSuccess: function(transport) {
			xml = transport.responseXML;
			body = xml.documentElement;

			suggDiv = $('suggestedURLs');
			_process = body.getElementsByTagName('process')[0];
			_processVal = _process.firstChild ? _process.firstChild.data : "";
			_result = body.getElementsByTagName('result')[0];
			_resultVal = _result.firstChild ? _result.firstChild.data : "";
			_message = body.getElementsByTagName('message')[0];
			_messageVal = _message.firstChild ? _message.firstChild.data : "";

			if ( _processVal == "success" && _resultVal == "true" ){
				if (checkButton){
					//checkButton.setAttribute("src","/sitewide/img/buttons/btn-accounts-urlavail-green.gif");
					checkButton.update("Dirección disponible");
					checkButton.setStyle({backgroundColor:"#0C0"});
				}
				else
					alert("Dirección disponible");
			}
			else if ( _processVal == "success" && _resultVal == "false" ){
				if (checkButton){
					//checkButton.setAttribute("src","/sitewide/img/buttons/btn-accounts-urlnotavail2.gif");
					checkButton.update("Dirección NO disponible");
					checkButton.setStyle({backgroundColor:"#C00"});
				}
				else
					alert("Dirección NO disponible");
				
				// prepare the suggested names	
				suggestions = "La dirección que pediste ya está siendo usada. Por favor selecciona otra u opta por alguna de la siguiente lista.<br/><br/>";
				_suggs = body.getElementsByTagName('suggested')[0];
				aSuggs = $A(_suggs.childNodes);
				if (aSuggs.length > 0){
					aSuggs.each(function(__el){
						suggestions += '<a href="#" onclick="useSuggestion(\''+__el.firstChild.data+'\',\'suggestedURLs\');return false;">'+ __el.firstChild.data +'</a><br/>';
					});
					if (suggDiv){
						suggDiv.update(suggestions);
						_newTop = Position.cumulativeOffset(checkButton)[1] + 30;
						_newLeft = Position.cumulativeOffset(checkButton)[0];
						suggDiv.style.top = _newTop + 'px';
						suggDiv.style.left = _newLeft + 'px';
						Element.hide(suggDiv);
						
						
						new Effect.Appear(suggDiv);
					}
				}
				
			}
			else if ( _processVal != "success" ){
				if (checkButton){
					//checkButton.setAttribute("src","/sitewide/img/buttons/btn-accounts-urlinvalid.gif");
					checkButton.update("Dirección inválida");
					checkButton.setStyle({backgroundColor:"#C00"});
				}
				else
					alert("Dirección inválida");
			}
			
		},
		onFailure: function(){ 
			alert('Error al comprobar dirección. Por favor intenta de nuevo.');
		}
	});
	
	return false;
}

function useSuggestion(newName, suggDiv){
	cURL = $('custom_URL');
	if (cURL){
		cURL.value = newName;
		new Effect.Fade($(suggDiv));
		checkURLAvail(cURL.value)
	}
	else
		return false;
}

function submitSearch(inputElement) {
	location.href='/search/?searchterm='+inputElement.value;
}



function blockKeys(e){
	var blocking;
	evt = (e) ? e : ((window.event) ? window.event : "noEvent");
	kCode = evt.keyCode ? evt.keyCode : evt.which;
	//alert(kCode)
	if (kCode == "9" || kCode == "16"){
		blocking = true;
	}
	else{
		blocking = false;
	}
	return blocking;
}


document.getElementsByClass = function (needle) {
	function _GetElementsByClass(outArray, seed, needle) {
		while (seed) {
			if (seed.nodeType == 1) {
				if (seed.className) {
					var c = " " + seed.className + " ";
					if (c.indexOf(" " + needle + " ") != -1)
					outArray.push(seed);
				}
				_GetElementsByClass(outArray, seed.firstChild, needle)
			}
			seed = seed.nextSibling;
		}
	}
	var outArray = new Array();
	_GetElementsByClass(outArray, document.documentElement, needle);
	return outArray;
}


function charConversion(intext){ //Converts some Windows-1252 characters
	var intext;
	var outtext = '';

	// loop through the text one character at a time.
	for (var i=0; i<intext.length; i++) {
		var code = intext.charCodeAt(i);
		
		// Setup single char to single char conversions to be made
		if (code == 8220){code = 34;} //  curly-double quote open  to "
		if (code == 8221){code = 34;} //  curly-double quote close  to "
		if (code == 8217){code = 39;} //  curly-single quote open  to '
		if (code == 8216){code = 39;} //  curly-single quote close  to '
		if (code == 8211){code = 45;} //  en-dash with -

		// Setup and handle single char to multiple char replacements
		if (code == 8212){ //  em-dash with --
			code = '';
			outtext = outtext+String.fromCharCode(45,45);
		}		
		if (code == 8482){ //  TM symbol  to (TM)
			code = '';
			outtext = outtext+String.fromCharCode(40,84,77,41);
		}		
		if (code == 8230){ //  ellipsis  to three-periods
			code = '';
			outtext = outtext+String.fromCharCode(46,46,46);
		} 
		
		// Handles all single char to single char replacements.
		if (code!=''){	
			outtext = outtext+String.fromCharCode(code);
		}
	}
	return outtext;

}

function replaceAmp(str){
	return str.replace(/&/g, "&amp;");
}
function escapeSQ(str){
	return str.replace(/'/g, "\\'");
}