String.prototype.trim=function()
{	return this.replace(/^\s+|\s+$/g,'') ;
} ;

String.prototype.setChar=function(pos,c)
{	return this.substring(0,pos)+c+this.substr(pos+1) ;
} ;

Array.prototype.find=function(element)
{	for(var i=0 ; i<this.length ; ++i)
		if(this[i]==element)
			return i ;
	return false ;
} ;

Array.prototype.remove=function(element)
{	this[this.find(element)]=undefined ;
} ;

Array.prototype.add=function(element,insert){
	if(insert || this.find(element)===false){
		this.push(element) ;
		return true ;
	}
	return false ;
} ;

Array.prototype.apply=function(func)
{	for(var i=0, l=this.length ; i<l ; ++i)
		func(this[i],i) ;
} ;

Array.prototype.isSubSetOf=function(superSet){
	for(var i=0, l=this.length ; i<l ; ++i)
		if(superSet.find(this[i])===false)
			return false ;
	return true ;
} ;

function gebid(objId,container)
{	if(typeof(objId)!='object')
	{	if(container)
			return gebat({id:objId},container,1) ;
		return document.getElementById(objId+'') ;
	}
	else return objId ;
}

function gebat(propertySet,container,maxElems,levels)
{	if(!(container=gebid(container))) container=document.body ;
	if(!maxElems) maxElems=Infinity ;
	var elems=[], attrVal=null, temp, node ;
	var nodes=container.childNodes?container.childNodes:container ;
	for(var i=0, len=nodes.length ; node=nodes[i], i<len && elems.length<maxElems ; ++i)
		if(node.nodeType==1)
		{	if(hasPropertySet(node,propertySet))
			{	elems.push(node) ;
				if(elems.length==maxElems)
					break ;
			}
			if(levels!==0)
				if(temp=gebat(propertySet,node,maxElems-elems.length,levels?levels-1:null))
					elems=elems.concat(temp) ;
		}
	if(maxElems==1 && elems.length==1)
		return elems[0] ;
	return elems ;
}

function gebany(id){
	if(typeof id=='string')
		return gebid(id) ;
	else if(typeof id=='object')
		return gebat(id) ;
	else
		return null ;
}

function showOneChild(container,childId)
{	container=gebid(container) ;
	if(IS_IE){
		container.style.filter="progid:DXImageTransform.Microsoft.Slide(slidestyle=PUSH,Bands=1)" ;
		container.filters[0].apply() ;
	}
	for(var i in container.childNodes)
		if(container.childNodes[i].nodeType==1)
			container.childNodes[i].style.display='none' ;
	if(typeof childId=='number')
		var child=container.childNodes[childId] ;
	else
		child=gebid(childId,container) ;
	if(child)
		child.style.display='block' ;
	if(IS_IE) container.filters[0].play(0.3) ;
}

function setCssClass(state,objId,className)
{	var obj=gebid(objId) ;
	var classesArray=obj.className.split(' ') ;
	if(state)
		classesArray.add(className) ;
	else
		classesArray.remove(className) ;
	obj.className=classesArray.join(' ') ;
}

var IS_IE=(function isIE()
{	try{
	if(!document.all) return false ;
	var pos=navigator.userAgent.indexOf('MSIE') ;
	if(pos==-1) return false ;
	if(navigator.appName.indexOf('Microsoft')==-1) return false ;
	if(navigator.appVersion.indexOf('MSIE')==-1) return false ;
	if(navigator.appMinorVersion.indexOf('SP2')>=0) return 'sp2' ;
	if(navigator.appMinorVersion.indexOf('SP3')>=0) return 'sp3' ;
	return navigator.userAgent.substr(pos+5,3) ;
	}catch(e){return false}
})() ;


function hasPropertySet(objId,propertySet)
{	var obj=gebid(objId), propVal ;
	mainFor:
	for(var i in propertySet)
	{	propVal=propertySet[i] ;
		if((attrVal=obj[i])==undefined || attrVal==null)
			if(obj.getAttribute)
				attrVal=obj.getAttribute(i) ;
		if(propVal instanceof RegExp)
		{	if(!propVal.test(attrVal/*?attrVal:''*/))
				return false ;
		}
		else if(propVal!=attrVal)
			return false ;
		//if(!valueMatch(propertySet[i],attrVal))
		//	return false ;
	}
	return true ;
}

function getAncestor(propertySet,objId)
{	var obj=gebid(objId) ;
	do
	{	if(hasPropertySet(obj,propertySet))
			return obj ;
	}
	while(obj=obj.parentNode) ;
	return null ;
}

function getFirstElementChild(obj){
	var child=obj.firstChild ;
	if(child && child.nodeType!=1)
		child=getNextElementSibling(child) ;
	return child ;
}

function getNextElementSibling(obj){
	do
		obj=obj.nextSibling ;
	while(obj && obj.nodeType!=1);
	return obj ;
}

function setPropertySet(objId,propertySet){
	var obj=gebid(objId) ;
	for(var i in propertySet){
		var valType=typeof propertySet[i] ;
		if(i=='style')
			obj.style.cssText=propertySet[i] ;
		else if(obj[i]==undefined && (valType=='string' || valType=='integer' || valType=='boolean'))
			obj.setAttribute(i,propertySet[i]) ;
		else
			obj[i]=propertySet[i] ;
	}
}

function setPropertySetToCollection(collection,propertySet){
	for(var i=0 ; i<collection.length ; ++i)
		setPropertySet(collection[i],propertySet) ;
}

function setTabsPosition(tabsContainer){
	tabsContainer=gebid(tabsContainer) ;
	var marginLeft=tabsContainer.getAttribute('marginLeft')-0 ;
	var marginInBetween=tabsContainer.getAttribute('marginInBetween')-0 ;
	for(var tab=getFirstElementChild(tabsContainer) ; tab ; tab=getNextElementSibling(tab))
		if(tab.tagName=='TABLE'){
			tab.style.left=marginLeft ;
			marginLeft+=tab.offsetWidth+marginInBetween ;
		}
}

function selectTab(tabObj){
	tabObj=gebid(tabObj) ;
	var tabsContainer=tabObj.parentNode ;
	if(tabObj.className=='inactiveTab'){
		gebat({className:'activeTab'},tabsContainer).apply(function(tab){tab.className='inactiveTab'}) ;
		tabObj.className='activeTab' ; 
		setTabsPosition(tabsContainer) ;
		showOneChild(tabsContainer.getAttribute('assocCont'),tabObj.getAttribute('assocCont')) ;
	}
}

function setPermanentCookie(name,value,path){
	setCookie(name,value,60*24*365*1000,path) ;
}

function delCookie(name){
	setCookie(name,'',-999) ;
}

function setCookie(name,value,time,path){
	if(!path) path = '/' ;
	else if(path=='.') path = '' ;
	if(path) path = '; path='+path ;
	var expires = '' ;
	if(time)
		expires = "; expires="+(new Date((new Date).getTime()+1000*60*time)).toGMTString() ;
	document.cookie = name+"="+value+expires+path ;
}

function getCookie(cookieName){
	cookieName+='=' ;
	var cookieArray = document.cookie.split(';') ;
	for(var i=0 ; i<cookieArray.length ; ++i)
	{	var nameValuePair=cookieArray[i].trim() ;
		if(nameValuePair.indexOf(cookieName)==0)
			return nameValuePair.substring(cookieName.length,nameValuePair.length) ;
	}
	return '' ;
}

function manualAddItemToFavorites(E,itemId){
	if(addItemToFavorites(itemId)){
		var obj=getTarget(E) ;
		obj.disabled = true ;
		getFirstElementChild(obj).rows[0].cells[1].innerHTML = '&nbsp;'+TEXTOS.alreadyAddedToFavs ;
		if(!LOGGED_IN)
			Effect.toggle('noLoggedInFavAddMsg') ;
	}
}

function addItemToFavorites(itemId,limit){
	if(LOGGED_IN){
		setPermanentCookie('pendingFavItemAddition',itemId) ;
	}else{
		var favList = JSON.parse(getCookie(favItemsCookieName),[]) ;
		if(!limit || favList.length<limit)
			favList.add(itemId) ;
		else
			return false ;
		setPermanentCookie(favItemsCookieName,JSON.stringify(favList)) ;
	}
	return true ;
}
var favItemsCookieName='favItems' ;

function removeItemFromFavs(itemId){
	if(LOGGED_IN){
		var favRemList=JSON.parse(getCookie('pendingFavItemRemoval'),[]) ;
		favRemList.add(itemId) ;
		setPermanentCookie('pendingFavItemRemoval',JSON.stringify(favRemList)) ;
	}else{
		var favList=JSON.parse(getCookie(favItemsCookieName),[]) ;
		favList.remove(itemId) ;
		setPermanentCookie(favItemsCookieName,JSON.stringify(favList)) ;
	}
}

function favStrip_removeItemFromFavs(E,itemId){
	if(confirm(TEXTOS.confirmFavDeletion)){
		removeItemFromFavs(itemId) ;
		var itemCell=getAncestor({className:'itemLayoutCont'},getTarget(E)).parentNode ;
		itemCell.parentNode.deleteCell(itemCell.cellIndex) ;
	}
}

function setupFlashProgressBar(flashObj,flashObjWrapper,progressBar){
	function setBarPercentage(barObj,percentage){
		barObj.firstChild.style.width = percentage+'%' ;
		barObj.lastChild.innerHTML = percentage+'%' ;
	}
	flashObj = getFlashObject(flashObj) ;
	flashObjWrapper = gebid(flashObjWrapper) ;
	progressBar = gebid(progressBar) ;
	progressBar.parentNode.style.display = 'block' ;
	flashObjWrapper.style.cssText = 'width: 0 ; height: 0 ; overflow: hidden' ;
	flashObj.style.visibility = 'hidden' ;
	var flashProgressTimer = setInterval(
		function(){
			var percent = flashObj.PercentLoaded() ;
			setBarPercentage(progressBar,percent)
			if(percent==100){
				flashObjWrapper.style.cssText = 'width: 100% ; height: 100%' ;
				flashObj.style.visibility = 'visible' ;
				progressBar.parentNode.style.display = 'none' ;
				clearInterval(flashProgressTimer) ;
			}
		} ,
		300
	) ;
}

function favList_removeItemFromFavs(E,itemId){
	if(confirm(TEXTOS.confirmFavDeletion)){
		removeItemFromFavs(itemId) ;
		var itemLayout=getTarget(E).parentNode ;
		itemLayout.parentNode.removeChild(itemLayout) ;
	}
	//cancelBubbling(E) ;
}

function getFlashObject(id){
	if(window.document[id])
		return window.document[id] ;
	if(document.embeds && document.embeds[id])
		return document.embeds[id] ;
	return document.getElementById(id) ;
}

function getTarget(E){
	return E.srcElement?E.srcElement:E.target ;
}

function cancelBubbling(E){
	if(!E) E=window.event ;
	E.cancelBubble=true ;
	if(E.stopPropagation) E.stopPropagation() ;
}

function adjustStripScrollCont(obj){
	obj=gebid(obj) ;
	obj.style.width = obj.parentNode.clientWidth ;
}

function scrollObject(obj,movX,movY,freq,dMovX,dMovY,dFreq,accelCycles,runAtEnd){
	obj=gebid(obj) ;
	var scroller=function(timeout,mX,mY){
		var prevScrollLeft=obj.scrollLeft, prevScrollTop=obj.scrollTop ;
		obj.scrollLeft+=mX ;
		obj.scrollTop+=mY ;
		if(obj.scrollLeft!=prevScrollLeft || obj.scrollTop!=prevScrollTop){
			obj.scrollTimerId = setTimeout(function(){
				if(accelCycles){
					scroller(timeout-dFreq,mX+dMovX,mY+dMovY) ;
					--accelCycles ;
				}else
					scroller(timeout,mX,mY) ;
			},timeout) ;
		}else if(runAtEnd)
			runAtEnd() ;
	} ;
	scroller(freq+dFreq,movX,movY) ;
}

function stopScrollObject(obj){
	clearTimeout(gebid(obj).scrollTimerId) ;
}

function toggleItemStripScroller(stripObj,pos,state){
	var scrollerId = pos=='left'?'scrollLeft':'scrollRight' ;
	gebat({id:scrollerId},gebid(stripObj),1).style.visibility = state?'visible':'hidden' ;
}

function startItemStripScrolling(stripId,pos){
	if(pos=='left'){
		var dir=-1 ;
		var oppositePos='right' ;
	}else{
		var dir=1 ;
		var oppositePos='left' ;
	}
	toggleItemStripScroller(stripId,oppositePos,true) ;
	scrollObject(gebat({className:'scrollContainer'},stripId,1),dir*4,0,50,dir*2,0,1,15,function(){toggleItemStripScroller(stripId,pos,false)}) ;
}

function arrayGetTheGreatest(n,array){
	return array.sort(function(a,b){return b-a}).slice(0,n) ;
}

function autoAddItemsToFavorites(limit,watchPeriod,eligAddThres){
	var siteVisits=JSON.parse(getCookie('siteVisits'),[]) ;
	var itemVisits=JSON.parse(getCookie('itemVisits'),[]) ;
	var currentDay = Math.floor((new Date).getTime()/1000/60/60/24) ;
	siteVisits.add(currentDay) ;
	itemVisits.add(currentDay) ;
	siteVisits=arrayGetTheGreatest(watchPeriod,siteVisits)
	itemVisits=arrayGetTheGreatest(eligAddThres,itemVisits)
	if(siteVisits.length==watchPeriod && itemVisits.length==eligAddThres && itemVisits.isSubSetOf(siteVisits))
		addItemToFavorites(ITEM_ID,limit) ;
	setPermanentCookie('siteVisits',JSON.stringify(siteVisits)) ;
	setPermanentCookie('itemVisits',JSON.stringify(itemVisits),'.') ;
}

function getMousePos(E){
	if(E.pageX || E.pageY)
		return {x: E.pageX, y: E.pageY} ;
	else
		return {x: E.clientX+document.body.scrollLeft, y: E.clientY+document.body.scrollTop} ;
}

function popUpLoginForm(E){
	if(!E) var E=window.event ;
	var popUp = gebid('_inplaceLoginFormCont') ;
	if(!popUp){
		var popUp = document.createElement('DIV') ;
		document.body.appendChild(popUp) ;
		popUp.id = '_inplaceLoginFormCont' ;
		popUp.style.cssText = "position: absolute ;  width: 150px ; height: 280px" ;
		var innerHtml = "<div id=inplaceLoginForm><div><a href='#' onclick='gebid(\"_inplaceLoginFormCont\").style.display=\"none\";return false'>cerrar <span>x</span></a></div>" ;
		innerHtml += "<iframe src='/login.php' width=140 height=180 frameborder=no allowtransparency=true></iframe>" ; // codigo del formulario propiamente tal: lo mejor sería sacarlo de aqui
		innerHtml += "</div>" ;
		popUp.innerHTML = innerHtml ;
	}
	var mousePos = getMousePos(E) ;
	popUp.style.top = mousePos.y ;
	popUp.style.left = mousePos.x ;
	popUp.style.display = 'block' ;
}

function adjustInnerWindowSize(){
	frameElement.height=document.body.scrollHeight+10 ;
	frameElement.height=document.body.offsetHeight+10 ;
}

function replaceTagsForText(tagName,text){
	var elemList = document.getElementsByTagName(tagName) ;
	while(elemList.length){
		var textNode = document.createTextNode(text) ;
		elemList[0].parentNode.replaceChild(textNode,elemList[0]) ;
	}
}

function addBookmark(title,url){
	if(window.sidebar){ 
		window.sidebar.addPanel(title, url,""); 
	}else if( document.all ){
		window.external.AddFavorite( url, title);
	}else if( window.opera && window.print ){
		return true;
	}
}

function URLObject(url,makeItAbsolute){
	if(!(this instanceof arguments.callee))
		return new URLObject(url) ;
	if(!url) url = '' ;
	if(makeItAbsolute){
		var aElem = document.createElement('A') ;
		aElem.href=url ;
		if(!aElem.protocol)
			aElem.protocol = location.protocol ;
		var urlComps =  {
			protocol: aElem.protocol.replace(/:$/,'') ,
			host: aElem.hostname ,
			port: aElem.port ,
			path: '/'+aElem.pathname.replace(/^\//,'') ,
			query: parseQueryString(aElem.search.replace(/^\?/,'')) ,
			anchor: aElem.hash.replace(/^#/,'')
		} ;
	}else
		var urlComps = parseUrl(url) ;
	for(var prop in urlComps)
		this[prop] = urlComps[prop] ;
	
	this.getUrl = function(){
		if(makeItAbsolute){
			aElem.protocol = this.protocol ;
			aElem.hostname = this.host ;
			aElem.port = this.port ;
			aElem.pathname = this.path ;
			aElem.search = '?'+makeQueryString(this.query) ;
			aElem.hash = this.anchor ;
			return aElem.href ;
		}else
			return makeUrl(this) ;
	} ;

	this.addQueryParams = function(newParams){
		for(var parName in newParams)
			addQueryParam(this.query,parName,newParams[parName]) ;
		return this ;
	} ;
	
	this.getQueryString = function(){
		return makeQueryString(this.query) ;
	} ;
	
	this.toString = function(){
		return	'protocol: '+this.protocol + '\nusername: '+this.username + '\npassword: '+this.password+'\nhost: '
				+ this.host+'\nport: '+this.port+'\npath: '+this.path+'\nquery: '+JSON.stringify(this.query)+'\nanchor: '+this.anchor
		;
	} ;

	function parseUrl(url){
		var urlObj = {}, comps2=['','','','',''] ;
		var comps = url.match(/^(?:(\w+):\/\/)?([^/?#]*)([^?#]*)(?:\?([^#]*))?(.*)$/) ;
		if(comps[2])
			comps2 = comps[2].match(/^(?:([^:@]+)(?:\:([^@]*))?@)?([^:]+)(?:\:(\d+))?$/) ;
		if(!comps || !comps2) return {} ;
		return {
			protocol: comps[1] ,
			username: comps2[1] ,
			password: comps2[2] ,
			host: comps2[3] ,
			port: comps2[4] ,
			path: comps[3] ,
			query: parseQueryString(comps[4]) ,
			anchor: comps[5].substr(1)
		} ;
	}

	function makeUrl(urlObj){
		return function(obj){
			var url='' ;
			if(typeof(obj)=='string')
				url=obj ;
			else if(obj instanceof Object){
				for(var elemName in obj){
					var elem = urlObj[elemName]
					if(elemName=='query')
						elem=makeQueryString(elem) ;
					if(elem)
						url+=arguments.callee(obj[elemName][0])+elem+arguments.callee(obj[elemName][1]) ;
					url+=arguments.callee(obj[elemName][2]) ;
				}
			}
			return url ;
		}({protocol:[,'://'],username:[,{password:[':',,'@']}],host:[],port:[':'],path:[],query:['?'],anchor:['#']}) ;
	}

	function addQueryParam(obj,parName,parValue){
		if(obj[parName]){
			if( !(obj[parName] instanceof Array) )
				obj[parName] = [ obj[parName] ] ;
			obj[parName] = obj[parName].concat(parValue) ;
		}else
			obj[parName] = parValue ;
	}

	function parseQueryString(str){
		var ret = {}, comps, varsArray = str?str.split('&'):[] ;
		for(var i=0 ; i<varsArray.length ; ++i)
			if( comps = varsArray[i].match(/^([^=]+)(?:=(.*))?$/) )
				addQueryParam(ret,comps[1],comps[2]) ;
		return ret ;
	}

	function makeQueryString(dataObj){
		var appendVar = function(str,name,value){
			if(str) str += '&' ;
			str += escape(name)+'='+escape(value.toString()) ;
			return str ;
		} ;
		var ret = '' ;
		for(var propName in dataObj){
			if(dataObj[propName] instanceof Array)
				dataObj[propName].apply(function(elem){ret = appendVar(ret,propName,elem)}) ;
			else
				ret = appendVar(ret,propName,dataObj[propName]) ;
		}
		return ret ;
	}
}

function sendHTTPRequest(method,url,vars,files,callback){
	try{
		var xmlhttp = new XMLHttpRequest ;
	}catch(e){try{
		var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP") ;
	}catch(e){try{
		var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP") ;
	}catch(e){}}}
	method = method.toLowerCase() ;
	if(method == 'get')
		url = URLObject(url).addQueryParams(vars).getUrl() ;
	xmlhttp.open(method, url) ;
	if(method == 'post'){
		xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded") ;
		var postVars = URLObject().addQueryParams(vars).getQueryString() ;
	}
	xmlhttp.onreadystatechange = function(){
		if(xmlhttp.readyState == 4 && callback)
			callback(xmlhttp) ;
	} ;
	xmlhttp.send(postVars) ;
}

function reportNotWorkingItem(E,itemId){
	if(confirm(TEXTOS.confirmItemReport)){
		var target = getTarget(E) ;
		sendHTTPRequest('post','/actions.php',{itemNotWorking:1,itemId:itemId},null,function(req){
			if(req.responseText == 'done'){
				setCookie('notWorkingReported', 1, 60*24*3, '.') ;
				getAncestor({tagName:'BUTTON'},target).style.display = 'none' ;
				gebid('itemArea').innerHTML = "<div id=itemReportDone>El problema ha sido informado.<br><br> Gracias por tu colaboración</div>" ;	
			}
		}) ;
	}
}

function reportComment(E,commentId){
	if(confirm(TEXTOS.confirmSpamReport)){
		var target = getTarget(E) ;
		sendHTTPRequest('post','/actions.php',{reportComment:1,commentId:commentId},null,function(req){
			var ret = req.responseText ;
			//alert(ret) ;
			if(ret == 'repeated' || ret == 'done'){
				if(ret == 'repeated')
					alert(TEXTOS.spamReportedAlready) ;
				with(getAncestor({tagName:'TABLE'},target)){
					deleteRow(0) ; deleteRow(0) ;
					insertRow(-1).insertCell(-1).className = 'reported' ;
					rows[0].cells[0].innerHTML = TEXTOS.commentReported ;
				}
			}
		}) ;
	}
}



var JSON=function(){var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"',"'":"\\'",'\\':'\\\\'},s={'boolean':function(x){return String(x);},number:function(x){return isFinite(x)?String(x):'null';},string:function(x,quote){if(/['"\\\x00-\x1f]/.test(x)){x=x.replace(/([\x00-\x1f\\'"])/g,function(a,b){var c=m[b];if(c){return c;}
c=b.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);});} if(quote==undefined)quote="'";return quote+x+quote;},object:function(x,quote){if(x){var a=[],b,f,i,l,v;if(x instanceof Array){a[0]='[';l=x.length;for(i=0;i<l;i+=1){v=x[i];f=s[typeof v];if(f){v=f(v,quote);if(typeof v=='string'){if(b){a[a.length]=',';}
a[a.length]=v;b=true;}}} a[a.length]=']';}else{a[0]='{';for(i in x){v=x[i];f=s[typeof v];if(f){v=f(v,quote);if(typeof v=='string'){if(b)a[a.length]=',';if(/(^[a-zA-Z_][a-zA-Z_0-9]*$)|(^[0-9]+$)/.test(i)) quot='';else quot=quote;a.push(s.string(i,quot),':',v);b=true;}}} a[a.length]='}';} return a.join('');}
return'null';}};return{stringify:function(v,quote){var f=s[typeof v];if(f){v=f(v,quote);if(typeof v=='string'){return v;}} return null;},parse:function(text,returnOnError){try{return!(/[^,:{}\[\]0-9a-zA-Z_.\-+ \n\r\t]/.test(text.replace(/("(\\.|[^"\\])*")|('(\\.|[^"\\])*')/g,'')))&&eval('('+text+')');}catch(e){return returnOnError;}}};}();
