/* variable para controlar que el script de FB Share solo se agregue una vez */
var scriptFBShare = null;
var scriptTWTShare = null;
/* common.js, autocomplete.js, playboy.js, selector.js, dragAndDrop.js, Resizable.beta.class.js, Window.beta.class.js, Window.beta.utilities.js  */
/* INICIA COMMON.JS */
var ua = navigator.userAgent.toLowerCase();
var isBrowser = {'IE':!!(window.attachEvent && !window.opera),'IE6':(navigator.userAgent.indexOf("MSIE 6.0")>=0),'GK':(ua.indexOf("gecko") != -1),'SF':(ua.indexOf("safari") != -1),'KQ':(ua.indexOf("konqueror") != -1),'OP':!!window.opera};
var emptyFunction = function(){}; 
function roundNumber(rnum, rlength){
	return Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
}
var GalleriesObj = new Galleries();
var ImgUploadObj = new ImgUpload();
function setCookie(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+"="+escape(value)+"; path=/; domain="+DOMAIN_COOKIE+expires;
}
function clearCookie(name) {
	var cookie = name+"=; path=/; domain="+DOMAIN_COOKIE+"; expires=Thu, 01-Jan-1970 00:00:01 GMT";
	document.cookie = cookie;
}
function getCookie(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 getBrowser()
{
	for(index in isBrowser)
		if(isBrowser[index])
			return index;
}
var errorCache = new Array();
/*
 * window.onerror = function () { var x = window.onerror.arguments;
 * errorHandle(x); };
 */

function pxToNum(string)
{
	return parseInt(string.replace('px',''));
}
function errorHandle(e)
{
	var x = new Array();
	if(/\?/.test(e[1]))
	{
		var xr = e[1].split('?');
		e[1] = xr[0];
	}
	for(var i = 0;i<e.length; i++)
		x.push(e[i]);
	
	var par = x.join('|');
	par =  addSlashes(par);
	try
	{	if(!/(woopra|_gat|quantserve|adtech|nspmotion|msn\.com)/.test(par))
		{
			errorCache.push
			(
				{
					'error'				:	par,
					'action'			:	'javascript_error_reporting',
					'browser'			:	getBrowser(),
					'host'				:	isBrowser.IE || isBrowser.SF ? window.location.host: window.location.hostname,
					'current_action'	:	CURRENT_ACTION,
					'current_section'	:	CURRENT_SECTION,
					'cookie'			: 	window.document.cookie
				}
			);
			reportErrors();
		}
	}catch(e){}
}
function reportErrors()
{
	
	var i = errorCache.length;while(i--)
	{
		httpRequest(EXTERNAL_ERRORS_DOMAIN,errorCache.pop());
	}
}
windowOnloadAdd(reportErrors);
windowOnloadAdd(function(){
	var forms = document.getElementsByTagName('form');
	var length = forms.length;
	for(var i = 0;i<length;i++)
	{
		if(forms[i].method.toLowerCase()== 'post')
		{
			var input = createNamedElement('input','domain_referer');
			input.setAttribute('type','hidden');
			input.value = isBrowser.IE || isBrowser.SF ? window.location.host: window.location.hostname;
			forms[i].appendChild(input);
			var input_2 = createNamedElement('input','iframe_request');
			input_2.setAttribute('type','hidden');
			input_2.value = '1';
			forms[i].appendChild(input_2);
		}
	}
});

var httpRquestCache =  new Array();
function httpRequest(url,object,method){
	var form = document.createElement('form');
	form.action = url;
	form.method = method == 'get'?'get':'post';
	var randStr = randomString();
	var iframe_name = randStr+'_iframe';
	var iframe = createNamedElement('iframe',iframe_name);
	// iframe.onload = function (){alert(1);} does'nt work on IE,SF
	form.appendChild(iframe);
	
	var input_request = createNamedElement('input','iframe_request');
	input_request.value = 1;
	form.appendChild(input_request);
	form.target = iframe_name;
	form.id = randStr+'_form';
	object.domain_referer = isBrowser.IE || isBrowser.SF ? window.location.host: window.location.hostname;
	for(ins in object){
		var el = createNamedElement('input',ins);
		el.value = object[ins];
		form.appendChild(el);
	}
	form.style.display = "none";
	document.body.appendChild(form);
	
	form.submit();
	httpRquestCache.push([form,iframe]);
	return {'iframe':iframe,'form':form};
}
function randomString() {
	var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 8;
	var randomstring = '';
	for (var i=0; i<string_length; i++){
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

function createNamedElement(type, name) {
  var element = null;
  // Try the IE way; this fails on standards-compliant browsers
  try {
    element = document.createElement('<'+type+' name="'+name+'">');
  } catch (e) {}
  if (!element || element.nodeName != type.toUpperCase()) 
  {
    // Non-IE browser; use canonical method to create named element
    element = document.createElement(type);
    element.name = name;
  }
  return element;
}
/*
 * addEvent( window, 'load', function(){ var img =
 * document.getElementsByTagName('img'); var i = img.length; while(i--){ try{ if
 * (img[i].width > 430) if (img[i].getAttribute('resizemod')) {
 * img[i].style.cursor = 'pointer'; img[i].src_popup = img[i].src;
 * img[i].onclick = function(e){ var x = getTarget(e);
 * openImagePopUp(x.src_popup); }; } } catch(e) {} } var linksx =
 * document.getElementsByTagName('a'); var length = linksx.length; for(var j=0;
 * j < length; j++) {
 * 
 * if(!/levelup/.test(linksx[j].href.toLowerCase())) { //linksx[j].rel =
 * 'nofollow'; } if(linksx[j].getElementsByTagName('img').length>0)
 * if(/(jpg|png|gif)$/.test(linksx[j].href.toLowerCase())) linksx[j].href
 * ='javascript:openImagePopUp("'+linksx[j].href+'");'; } } );
 */
function openImagePopUp(url)
{
	var img = new Image();
	img.onload = function ()
	{
		var width = img.width + 20;
		var height = img.height + 20;
		if(screen.width < width || screen.height < height)
		{
			width = screen.width;
			height = screen.height;
		}
		window.open(url,'levelUP','width='+width+',height='+height+',resizable=yes');
	};
	img.src = url;	
}

function windowOnloadAdd(funct){addEvent(window,'load',funct);};
function windowOnloadRemove(funct){removeEvent(window,'load',funct);};
function fixResizeIMG(img,widthdef)
{
}
function getY(idElement){
	oElement = $$(idElement);
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

function onTabClick(args){
	eval('if (typeof '+args['tabid']+'_click == \'function\') '+args['tabid']+'_click();');
	if (typeof customTabClick == 'function')
		customTabClick(args);
}

function insertAfter(newNode, refNode) {
  	refNode.parentNode.insertBefore(newNode, refNode.nextSibling);
}

function appendChildFirst(newNode,refNode)
{
	refNode.insertBefore(newNode,refNode.firstChild);
}

function copyDiv(idDest, idSource){
	return $$(idDest).innerHTML = $$(idSource).innerHTML;
}

function debugArray(arr,separator){
	var flag = 0;
	var str = '';
	var i = 0;
	
	if (!separator)
		separator = '';
		
	for (var index in arr){
		str += '['+i+'] '+index+': '+arr[index]+separator;
		flag = 1;
		i++;
	}
	
	str = (flag==0) ? 'No es un arreglo:\n\n'+arr : 'Arreglo ajax:\n\n'+str;
	
	$$('console').value += str;
}

function getValue(idObj){
	return (document.getElementById) ? document.getElementById(idObj).value : document.all[idObj].value;
}

function getObject(idObj){
	return (document.getElementById) ? document.getElementById(idObj) : document.all[idObj];
}

function pageWidth(){
	return window.innerWidth != null? window.innerWidth: document.body != null? document.body.clientWidth:null;
}

function pageHeight(){
	return window.innerHeight != null? window.innerHeight: document.body != null? document.body.clientHeight:null;
}

function openNode(){
	for (var i=0; i<openNode.arguments.length; i++)
		if (node = $$(openNode.arguments[i]))
			node.style.display = '';
}

function closeNode(){
	for (var i=0; i<closeNode.arguments.length; i++)
		if (node = $$(closeNode.arguments[i]))
			node.style.display = 'none';
}


function removeNode(){
	for (var i=0; i<removeNode.arguments.length; i++)
		if (node = $$(removeNode.arguments[i]))
			node.parentNode.removeChild(node);
}

function getSelectedItem(idSelect){
	var select = $$(idSelect);
	
	for(i=0; i<select.length; i++) 
		if (select.options[i].selected == true)
			return select.options[i];
	return false;
}

function move(idSource,idDest,moveAll){

	var source = $$(idSource);
	var dest = $$(idDest);

	for (var i = 0; i<source.length; i++){

		if (source.options[i].selected||moveAll){

	    	var opt = document.createElement('option');
   			opt.text = source.options[i].text;
   			opt.value = source.options[i].value;
   			
   			try {
     				dest.add(opt, null);
   			}catch(ex){
     				dest.add(opt);
   			}
	    }
	}
	
	for (var i = 0; i<source.length; i++)
	  	if (source.options[i].selected||moveAll){
	   		source.remove(i);
	   		i--;
	 	}

}

function selectOpt(idSel,arr){
	var source = $$(idSel);
	
	for (var j = 0; j<source.length; j++)source.options[j].selected = false;
	for (var i in arr)
		for (var j = 0; j<source.length; j++)
			if (source.options[j].value == arr[i])
				source.options[j].selected = true;
}

function insertSel(idDest,text,value)
{
	var dest = $$(idDest);
	var opt = document.createElement('option');
   	opt.text = text;
   	opt.value = value;
   	opt.selected = true;
	
   	try {
    	dest.add(opt, null);
   	}catch(ex){
    	dest.add(opt);
   	}
}

function copySel(idSource,idDest,copyAll){
	var source = $$(idSource);
	var dest = $$(idDest);
			
	for (var i = 0; i<source.length; i++){	
		if (source.options[i].selected||copyAll){
		
	    	var opt = document.createElement('option');
   			opt.text = source.options[i].text;
   			opt.value = source.options[i].value;
   			
   			try {
     			dest.add(opt, null);
   			}catch(ex){
     			dest.add(opt);
   			}
	    }
	}
}

function findSelectValue(idSelect,value){
	var select = $$(idSelect);
	
	for(var i=0; i<select.length; i++)
		if (select.options[i].value == value)
			return i;
	
	return false;
}

function findSelectText(idSelect,text){
	var select = $$(idSelect);
	
	for(i=0; i<select.length; i++) 
		if (select.options[i].text == text)
			return i;
}

function sortSelect(idSelect){
	var select = $$(idSelect);
	var arrTexts = new Array();

	for(i=0; i<select.length; i++) 
		arrTexts[i] = select.options[i].text+':'+select.options[i].value+':'+select.options[i].selected;
	
	arrTexts.sort();
	
	for(i=0; i<select.length; i++) {
		duo = arrTexts[i].split(':');
		select.options[i].text = duo[0];
		select.options[i].value = duo[1];
		select.options[i].selected = (duo[2]=='false')?false:true;
	}
}

function getSelValues(idSelect){
	var select = $$(idSelect);
	
	var result = new Object();
	
	for(var i=0; i<select.length; i++){
		result[i] = new Object();
		result[i].text = select.options[i].text;
		result[i].value = select.options[i].value;
	}
	
	return result;
}

function getSelValuesStr(idSelect){
	var arr = new Array();
	arr = getSelValues(idSelect);
	var str = '';
		
	for (var index in arr)
		str+=arr[index].value+',';

	return str.substring(0,str.length-1);
}

function getSelTextStr(idSelect){
	var arr = new Array();
	arr = getSelValues(idSelect);
	str = '';

	for (var index in arr)
		str+=arr[index].text+', ';
	
	return str.substring(0,str.length-2);
}

function validateEmail(str) 
{
	return /((?:(?:(?:[a-zA-Z0-9][\.\-\+_]?)*)[a-zA-Z0-9])+)\@((?:(?:(?:[a-zA-Z0-9][\.\-_]?){0,62})[a-zA-Z0-9])+)\.([a-zA-Z0-9]{2,6})/.test(str);
}

function isEmail(email){
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; 
	return email.match(re);
}

function disable(){
	for (var i=0; i<disable.arguments.length; i++)
		if (node = $$(disable.arguments[i]))
			node.disabled = true;
}

function enable(){
	for (var i=0; i<enable.arguments.length; i++){
		if (node = $$(enable.arguments[i]))
			node.disabled = '';
	}
}

function endisButton(value,idButton){
	$$(idButton).disabled = (trim(value)=='')?'disabled':''; 
}

function test(arr){
	
	if ($$('testx')){
		div = $$('testx');
	}else{
		div = document.createElement('div');
		document.body.appendChild(div);
	}
	div.id = 'testx';
	div.style.color = 'black';

	if (typeof arr == 'object')
		div.innerHTML = debugArray(arr,'<br/><br/>');
	else
		div.innerHTML = arr;
}

function toggle(linkObj, idContainer){
	div = $$(idContainer);
	
	if (div.style.display == 'none'){
		openNode(idContainer);
		if(linkObj.tagName == 'A') linkObj.innerHTML = 'ocultar';
	}else{
		closeNode(idContainer);
		if(linkObj.tagName == 'A') linkObj.innerHTML = 'mostrar';
	}
}

function clientWidth() {
	return filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function clientHeight() {
	return filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function scrollLeft() {
	return filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function scrollTop() {
	return filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function documentHeight(){
	return window.innerHeight ?	window.scrollMaxY ?	window.innerHeight + window.scrollMaxY : document.height : document.documentElement.scrollHeight;
}

function Thumb(opt){
	
	var thumb = new Object();
	
	var div = document.createElement('div');
	div.className = 'thumbnail_screen';
	div.id = opt.id;
	
	thumb.waitGif = opt.waitGif;
	thumb.waitFlag = false;
	thumb.width = opt.width;
	thumb.height = opt.height;
	thumb.src = opt.src;
	thumb.onclick = opt.onclick || false;
	thumb.resizeImages = opt.resize || false;
	
	var img = document.createElement('img');
	img.src = opt.src;
	img.id = 'image'+opt.id+'int';
	
	if(!thumb.resizeImages){					
		if(img.width>img.height){
			var tmp_width=true;
			var tmp_height=false;
		}else if(img.height>img.width){
			var tmp_width=false;
			var tmp_height=true;
		}else{
			var tmp_width=true;
			var tmp_height=true;
		}
	}	
	
	tmp_img_width = img.width;
	tmp_img_height = img.height;
					
	// var img_div = document.createElement('div');
	// img_div.className = 'img_container';
	
	var img_table = document.createElement('table');
	img_table.className = 'img_container';	
	
	var img_tbody = document.createElement('tbody');
	var img_tr = document.createElement('tr');
	var img_td = document.createElement('td');
	img_td.valign = 'middle';	
	
	img_tr.appendChild(img_td);
	img_tbody.appendChild(img_tr);
	img_table.appendChild(img_tbody);
		
	/*
	 * var wait_label = document.createElement('p'); wait_label.id =
	 * 'wait'+opt.id+'label'; wait_label.className = 'wait_label';
	 * wait_label.innerHTML = 'Cargando...';
	 */
	// wait_label.style.verticalAlign = 'middle';
	
	// img_div.appendChild(wait_label);
	// img_div.appendChild(img);
	img_td.appendChild(img);
	
	// thumb.waitLabel = wait_label;
	// thumb.imgDiv = img_div;
	// thumb.imgTable = img_div;
	thumb.imgTd = img_td;
	
	if (opt.title){
		var title =  document.createElement('div');
		title.className = 'title';
		title.innerHTML = opt.title;
		
		thumb.title = title;
		div.appendChild(title);
	}

	if (opt.width){
	
		if(!thumb.resizeImages){	
			if(navigator.userAgent.indexOf("MSIE")>=0) 	
				if(tmp_width)
					img.style.width =(opt.width-4)+'px';
				else			
					img.style.width =((tmp_img_width*opt.height)/tmp_img_height)+'px';
				
			img.style.maxWidth = (opt.width-4)+'px';
		}else{
			img.style.width =(opt.width-4)+'px';	
		}
	
		// img_div.style.width = opt.width+'px';
		img_table.style.width = opt.width+'px';
		div.style.width = opt.width+'px';
		
		if (title)
			title.style.width = opt.width+'px';
	}
	
	if (opt.height){
		
		if(!thumb.resizeImages){				
			if(navigator.userAgent.indexOf("MSIE")>=0) 
				if(tmp_height)
					img.style.height = (opt.height-4)+'px';	
				else
					img.style.height =((tmp_img_height*opt.width)/tmp_img_width)+'px';	
							     
			img.style.maxHeight = (opt.height-4)+'px';
		}else{
			img.style.height = (opt.height-4)+'px';
		}			
			
		// img_div.style.height = opt.height+'px';
		img_table.style.height = opt.height+'px';
		div.style.height = opt.height+'px';
	}
	
	div.image = img;
	// div.appendChild(img_div);
	div.appendChild(img_table);
	
	if (opt.removeFnc){
		var remove = document.createElement('a');
		remove.className = 'link';
		remove.id = 'remove'+opt.id+'link';
		remove.innerHTML = 'X';
		remove.href = 'javascript:void(null);';
		remove.itemId = opt.id;
		remove.thumb = thumb;
		remove.removeFnc = 	opt.removeFnc; 
		remove.onclick = function (){
			this.removeFnc(this.thumb);
		};
		
		thumb.removeLink = remove;
		div.appendChild(remove);
	}
	
	if (opt.editFnc){
		var edit = document.createElement('a');
		edit.className = 'link';
		edit.id = 'edit'+opt.id+'link';
		edit.innerHTML = 'Editar';
		edit.href = 'javascript:void(null);';
		edit.itemId = opt.id;
		edit.thumb = thumb;
		edit.editFnc = 	opt.editFnc; 
		edit.onclick = function (){
			this.editFnc(this.thumb);
		};
		
		thumb.editLink = edit;
		div.appendChild(edit);
	}
	
	$$(opt.idContainer).appendChild(div);
	// closeNode(wait_label.id);
	
	thumb.thumb = div;
	
	thumb.remove = function(){
		this.thumb.parentNode.removeChild(this.thumb);
	};
	
	thumb.hide = function(){
		closeNode(this.thumb.id);
	};
	
	thumb.show = function(){
		openNode(this.thumb.id);
	};
	
	thumb.changeImg = function (src){
		this.thumb.image.src = src;
	};
	
	thumb.getImg = function (){
		return this.thumb.image.src;
	};
	
	thumb.wait = function(){
	
		if (this.waitGif){
			this.thumb.image.src = this.waitGif;
		}else{
			closeNode(this.thumb.image.id);
			openNode(this.waitLabel.id);
		}
		
		if (this.removeLink)
			closeNode(this.removeLink.id);
				
		if (this.editLink)	
			closeNode(this.editLink.id);
				
		this.waitFlag = true;
	};
	
	thumb.disableWait = function(src){
		if (this.waitFlag){
			
			closeNode(this.thumb.image.id);
			this.thumb.image.src = src ? src : this.src;
														
			openNode(this.thumb.image.id);
			// closeNode(this.waitLabel.id);
			
			if (this.removeLink)
				openNode(this.removeLink.id);
					
			if (this.editLink)
				openNode(this.editLink.id);
					
			this.waitFlag = false;
		}
	};
	
	thumb.setTitle = function (title){
		if (this.title)
			this.title.innerHTML = title;
		else
			return false;
	};
	
	thumb.setItemId = function (id){
		this.itemId = id;
	};
	
	thumb.getItemId = function (){
		return this.itemId;
	};
	
	thumb.setThumbNum = function (num){
		this.thumbNum = num;
	};
	
	thumb.getThumbNum = function (){
		return this.thumbNum;
	};
	
	thumb.setDesc = function (desc){
		this.description = desc;
		this.thumb.image.alt = desc;
	};
	
	thumb.getDesc = function (){
		return this.description;
	};
	
	thumb.setPhotographer = function (photographer){
		this.photographer = photographer;	
	};
	
	thumb.getPhotographer = function (){
		return this.photographer;
	};
	
	thumb.addLink = function(text,onclick){
	
		var link = document.createElement('a');
		link.className = 'link';
		link.id = 'edit'+this.thumb.id+'link';
		link.innerHTML = text;
		link.href = 'javascript:void(null);';
		link.itemId = this.thumb.id;
		link.thumb = thumb;
		link.clickFnc = onclick;
		link.onclick = function (){
			this.clickFnc(this.thumb);
		};
				
		this.thumb.appendChild(link);
	};
	
	if (thumb.onclick){
			
		var link = document.createElement('a');
		link.className = 'unlink';
		link.id = 'edit'+opt.id+'link';
		link.href = 'javascript:void(null);';
		link.itemId = thumb.id;
		link.thumb = thumb;
		link.clickFnc = link.onclick;
				
		link.onclick = function (){
			thumb.onclick(this.thumb);
		};
				
		link.appendChild(img);
		// img_div.appendChild(link);
		img_td.appendChild(link);
		// img.onclick = thumb.onclick;
	}	
	
	return thumb;
}

function $$(id) {return document.getElementById(id);};
function $c(string) { return document.createElement(string);};
function $a(parent,child) {parent.appendChild(child);};
function $tN(string){return document.createTextNode(string);};
function addEvent (obj, evType, fn, useCapture) {
	try{
		(obj.addEventListener) ? obj.addEventListener(evType, fn, useCapture) : (obj.attachEvent) ? obj.attachEvent("on"+evType, fn) : '';
	}catch(e){}
}
function removeEvent (obj,evType,fn) {
	(obj.attachEvent) ? obj.detachEvent("on" + evType, fn) : obj.removeEventListener(evType, fn, false);
}
function findParentNode(tagName, node){while (node.tagName != "HTML"){if (node.tagName.toLowerCase() == tagName.toLowerCase()) return node;node = node.parentNode;}return null;}
function trim(str){ var rstr = new String(str);return rstr.replace(/^\s*|\s*$/g,"");};
function isDefined(par){return typeof par == "undefined" ? false : true;};
function hide(){trasverseForHideAndShow(arguments,false);};
function show(){trasverseForHideAndShow(arguments,true);};

function removeEl(el) {
el.parentNode.removeChild(el);
}
function trasverseForHideAndShow(arg,is){
	try {
		var i = arg.length;
		while (i--) {
			if ((typeof arg[i]).toLowerCase() == 'string') {
				$$(arg[i]).style.display = is?"block":"none";
			} else {
				if ((typeof arg[i]).toLowerCase() == 'object') {
					arg[i].style.display = is?"block":"none";
				}
			} 
		}
	} catch(e) {}
}

function toogle(element){element.style.display = element.style.display =="none" ? "block":"none";};
function getTarget(e)
{
	try
	{
		var targ = false;
		if (!e) var e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		try
		{if (targ.nodeType == 3) targ = targ.parentNode;}
		catch(e){}
	}catch(e){}
	return targ;
}
function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B);}
function toHex(N) 
{
 if (N==null) return "00";
 N=parseInt(N); if (N==0 || isNaN(N)) return "00";
 N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
 return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}
function getE (event){return event || window.event;}
function getPressedKey (event)
{
	var event = getE(event); 
	return event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
}
function stopEvent(event)
{
	if ( event.stopPropagation) 
	{
		event.preventDefault();
		event.stopPropagation();
	} 
	else 
	{
		event.cancelBubble = false;
		event.returnValue = false;
	} 
}
function insertAfter(newNode, refNode) { refNode.parentNode.insertBefore(newNode, refNode.nextSibling);};

function getStyle(oElm, strCssRule){
	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

function addClass(el,className)
{
	if(isDefined(el.className))
	{
		if(el.className!='')
		{
			if(el.className.indexOf(className)==-1)
				el.className += ' '+className;
		}		
		else
			el.className = className;
	}
	else
	{
		el.className = className;
	}

}
function removeClass (el,className){el.className = el.className.replace(className,'');}
function disabledDiv(opt){
	if(!opt.element)
		return;
	if(opt.disable){
		if(!opt.element.divdisabled){
			opt.element.divdisabled = true;
			
			var width = getStyle(opt.element,'width');
			var height = getStyle(opt.element,'height');
				
			var div = $c('div');
			div.innerHTML = '&nbsp;';
			div.style.position = 'absolute';
			div.style.width = width;
			div.style.height = height;
			opacity = opt.opacity ? opt.opacity : 0.6;
			div.style.opacity = opacity;
			opacity = parseInt(opacity)*10;
			div.style.filter = 'alpha(opacity='+opacity+')';
			div.style.backgroundColor = opt.bgcolor ? opt.bgcolor : 'white';
			div.style.zIndex = 100;
			opt.element.insertBefore(div, opt.element.childNodes[0]);
			opt.element.blockerDiv = div;
		}
	}else{
		if (!opt.element.divdisabled)
			return;
		opt.element.divdisabled = false;
		if(opt.element.blockerDiv){
			if(opt.element.blockerDiv.parentNode != null){
				removeEl(opt.element.blockerDiv);
			}
		}
	}
}
function stripTags(string){return string.replace(/<\/?[^>]+>/gi, '');}
// object extender
Object.extend = function(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
};

/*-----------------------------Ajax Request Object----------------------------------*/

var Ajax = function (url,options)
{
	var _this = this;
	this.URL = url || '';
	this.options = 
	{
		method			: 'post',
		asynchronous	: true,
		parameters		: null,
		onComplete  	: options.onComplete || false
    };
    Object.extend(this.options, options || { });
    
// try{if (isDefined(ajax_debug)) $$('console').value +=
// "\rparameters--------------------------------\r"+_this.options.parameters+"\n-----------------------------------\n";}catch(e){}

	if (typeof XMLHttpRequest != "undefined") this.XHR = new XMLHttpRequest();
	else if (typeof ActiveXObject != "undefined")
	this.XHR = new ActiveXObject("Microsoft.XMLHTTP");
	if(this.XHR)
	{
		this.XHR.onreadystatechange = function (res)
		{
			if (_this.XHR.readyState == 4)
			{ 
				if (_this.XHR.status == 200) 
					if(_this.options.onComplete)
					{									  
						// /try{ if (isDefined(ajax_debug)) $$('console').value
						// +="\nAjax response----------------------\n"+
						// _this.XHR.responseText+"\n-----------------------------------\n";}catch(e){}
						if(_this.options.asynchronous)_this.options.onComplete(_this.XHR.responseText);
					}
			}
			else if(_this.XHR.readyState == 1)
			{
				// console.log(_this.XHR);
			}
			else if(_this.XHR.readyState == 2)
			{
				/*
				 * console.log(_this.XHR);
				 * console.log(_this.XHR.getAllResponseHeaders());
				 */
			}
			else if(_this.XHR.readyState == 3)
			{
				/*
				 * console.log(_this.XHR);
				 * console.log(_this.XHR.getAllResponseHeaders());
				 */
			}	
		};
		if(this.options.method == 'post')
		{
			this.XHR.open('post',this.URL, this.options.asynchronous);
			this.XHR.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.XHR.setRequestHeader("Content-length", this.options.parameters.length);
			this.XHR.setRequestHeader("Connection", "close");
		}
		else
		{
			this.XHR.open('get', this.URL + '?' + this.options.parameters , this.options.asynchronous);
			this.options.parameters = null;
		}
	}
	this.XHR.send(this.options.parameters);
	if(!this.options.asynchronous)this.options.onComplete(this.XHR.responseText);
};

function objectToQuery(object)
{
	var query='';
	for(x in object) query += '&'+x+'='+encodeHTML(object[x]);
	return query.substring(1);   
};

function ajaxRequest(section,action,params,funct,localdata,asyn,nocache,get)
{
	var pluginRef = '';
	if (isDefined(nocache)){
		pluginRef = DOMAIN + nocache;
	}
		
	if(pluginRef == '')
		pluginRef = DOMAIN + '?'+SECTION  + '=' + section + '&'+ ACTION + '=' + action +'&ajax_request=1';
	
	if(isDefined(get)){
		if(get){
			$.get(
				pluginRef,
				params,
				function(obj){
					if(localdata) obj.localdata = localdata;
					funct(obj);
				}, 'json'
			);
			return;
		}
	}
	
	var varAjax = new Ajax
	(
		pluginRef,
		{
			parameters: (typeof params == 'object') ? objectToQuery(params) : objectToQuery({'postAjaxParam':params}),
			onComplete: function (r)
			{
				// console.log(r);
				var obj = parseJson(r);
				
				if(obj){
					if (typeof obj.debug != 'undefined') {
						if (typeof ADMIN != 'undefined') {
							var _getAjaxParams = function(data) {
								if (typeof data == 'object') {
									var parameters = $.param(data).split("&");
									var i;
									var paramFinal = '<b>PARAMETERS</b><br/><hr>';
									for (i=0 ; i<parameters.length ; i++) {
										paramFinal += '&nbsp;&nbsp;&nbsp;&nbsp;' + parameters[i] + '<br/>';
									}
									paramFinal += '<br/>';
									return paramFinal;
								} else {
									return null;
								}
							};
							var _setDebugData = function(data) {
								$('<div id="ajaxDebug_header'+id+'" class="debug_header"><span style="margin:0px 5px;padding-bottom:3px">'+data.header+'</span></div>').appendTo('#ajaxDebug');
								$('<div id="ajaxDebug_content'+id+'" class="debug_content">'+data.content+'</div>').appendTo('#ajaxDebug');
							};
							var _checkDebugData = function(data) {
								var result;
								switch(typeof data) {
									case 'object':
										result = { 'header' : data.header, 'content' : _getAjaxParams(params) + '<b>DEBUG</b><br/><hr>' + data.content };
										break;
									case 'string':
										result = { 'header' : SECTION  + '=' + section + '&'+ ACTION + '=' + action, 'content' : _getAjaxParams(params) + '<b>DEBUG</b><br/><hr><br/>' + data };
										break;
									default:
										return false;
								}
								return result;
							};
							var id = Math.floor(Math.random()*100);
							var debugData = _checkDebugData(obj.debug);
							if (debugData) {
								if ( !$$('ajaxDebug') ) { 
									$('<div id="ajaxDebug" class="debug_conteiner"><P><B>AJAX DEBUG</B></P></div>').appendTo('body');
								}
								_setDebugData(debugData);
								$('#ajaxDebug_header'+id).bind('click',function(){
									if ($('#ajaxDebug_content'+id).css('display') == 'none') {
										$('#ajaxDebug_content'+id).slideDown('slow');
									} else {
										$('#ajaxDebug_content'+id).slideUp('slow');
									}
								});
							}
						}
						delete obj.debug;
					}
					obj.localdata = localdata;
					switch(obj.status_code){
						case 1:
							obj.funct = eval('('+obj.funct+')');
							obj.funct();
							funct(obj);
							break;
						case 2:
							obj.funct();
							break;
						default:
							funct(obj);
							break;	
					}
				}
			},
			asynchronous: isDefined(asyn)?asyn:true
		}
	);
}

function remoteAjax(host, section,action,params,funct,localdata,asyn)
{	
	var pluginRef = host + '?'+SECTION  + '=' + section + '&'+ ACTION + '=' + action +'&ajax_request=1';
	new Ajax
	(
		pluginRef,
		{
			parameters: (typeof params == 'object')?objectToQuery(params):objectToQuery({'postAjaxParam':params}),
			onComplete: function (r)
			{
				var obj = parseJson(r);
				if(obj){
					switch(obj.status_code){
						case 1:
							obj.localdata = localdata;
							obj.funct = eval('('+obj.funct+')');
							obj.funct();
							funct(obj);
							break;
						case 2:
							obj.funct();
							break;
						default:
							funct(obj);
							break;	
					}
				}
			},
			asynchronous: isDefined(asyn)?asyn:true
		}
	);
}

function encodeHTML(string)
{
	 var string = new String (string);
	 var comillas1 = new RegExp(String.fromCharCode(8220),"g");
	 var comillas2 = new RegExp(String.fromCharCode(8221),"g");
	 var guionlargo = new RegExp(String.fromCharCode(8212),"g");
	 string =  string.replace(comillas1 ,"&ldquo;");
	 string =  string.replace(comillas2,"&rdquo;");
	 string =  string.replace(guionlargo,"&mdash;");
	 string =  escape(string);
     string =  string.replace(/\//g,"%2F");
     string =  string.replace(/\?/g,"%3F");
     string =  string.replace(/=/g,"%3D");
     string =  string.replace(/&/g,"%26");
     string =  string.replace(/@/g,"%40");
     string =  string.replace(/\+/g,"%2B");
     return string;
}

function parseJson(json){return eval('('+json+')');};

/* Pagination */

/*
 * function pagination(element_id,item_id,section,action,element,op) { var
 * elementDiv = $$(element_id); var backupEl = elementDiv.parentNode;
 * if(!isDefined(backupEl.page)) { backupEl.page = 1; backupEl.more = true; }
 * else if(backupEl.page==1 && op == "-") backupEl.page = 2; if(op==
 * "-")backupEl.more = true; if(backupEl.more || op== "-" ) { var x =
 * ((op=="+")?(backupEl.page + 1):(backupEl.page - 1)); backupEl.page = x;
 * ajaxRequest ( section, action, {'item_id':item_id,'page' : x}, function
 * (response) { if(response['more_items'] == '')backupEl.more = false;
 * elementDiv.innerHTML = response['html']; } ); } }
 */
function pagination(element_id,item_id,section,action,element,op,params)
{
	var elementDiv = $$(element_id);
	var backupEl =  elementDiv.parentNode;
	if(!isDefined(backupEl.page))
	{
		backupEl.page = 1;
		backupEl.more = true;
		backupEl.cache = new Array();
		backupEl.cache.push({'html':elementDiv.innerHTML,'more_items':true});
	}
	else if(backupEl.page==1 && op == "-") backupEl.page = 2;
	if(op== "-")backupEl.more = true;
	if(backupEl.more || op== "-" )
	{
		var x = ((op=="+")?(backupEl.page + 1):(backupEl.page - 1));
		backupEl.page = x;
		var yF = function (response)
		{
			if(response['more_items'] == '')
			{
				backupEl.more = false;
				response['more_items'] =false;
			}
		    elementDiv.innerHTML = response['html'];
		    backupEl.cache[x-1] = {'html':response['html'],'more_item': response['more_items']};
		};
		if(!backupEl.cache[x-1])
		{
			if((element_id == 'box_blogs_otros_blogs_usuario' || element_id == 'box_blogs_blogs_amigos') && op =='+')
				$('#'+element_id+' div ul').fadeOut('fast', function (){
					$('#'+element_id+' div img').fadeIn('fast');
				});		
			var obj = [];
			if (params)
				obj = params;
			obj.item_id = item_id;
			obj.page = x;
			ajaxRequest
			(
				section,
				action,
				obj,
				yF
			);
		}
		else
		{
			if(element_id == 'box_blogs_otros_blogs_usuario' || element_id == 'box_blogs_blogs_amigos'){
				$('#'+element_id+' div ul').fadeOut('fast', function (){
					$('#'+element_id+' div img').fadeIn('fast');
				});			
				setTimeout(function (){
					yF(backupEl.cache[x-1]);
				}, 1000);
			}else{
				yF(backupEl.cache[x-1]);
			}
		}
	}
}
function resetPagination(element_id){
	var elementDiv = $$(element_id);
	var backupEl =  elementDiv.parentNode;
	backupEl.page = 1;
	backupEl.more = true;
	delete backupEl.cache;
	backupEl.cache = new Array();
	backupEl.cache.push({'html':elementDiv.innerHTML,'more_items':true});
}
function ScrollTo(theElement)
{
  var selectedPosX = 0;
  var selectedPosY = 0;      
  while(theElement != null){
    selectedPosX += theElement.offsetLeft;
    selectedPosY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }                       		      
  window.scrollTo(selectedPosX,selectedPosY);
}

function evalString(string)
{
    var str = eval(string);
    return str ? str :false;
}

function responseExec(obj)
{
	// console.log(obj);
	if(obj.status){
		if(obj.funct){
			obj.funct();
		}else if(obj.link){
			window.location = obj.link;
		}else if(obj.html){
			obj.localdata.container.innerHTML = obj.html;
		}else if(obj.message){
			alert(obj.message);
		}
	}else if(obj.error){
		alert(obj.error);
	}else if(obj.message){
		alert(obj.message);
	}else{
		alert('unknown responsed object');
	}
}



/*
 * var els = $$('slider_files_refresh'); els =
 * $$('slider_files_refresh').style.overflow ='hidden'; els =
 * $$('slider_files_refresh').style.width ='300px';(); ScrollTox(els);
 */
function myScrollTo(container, element)
{
   
    /*
	 * container = $$(container); element = $$(element); var x = element.x ?
	 * element.x : element.offsetLeft, y = element.y ? element.y :
	 * element.offsetTop; element.time = element.time? ((x+y)/2) : 1;
	 * if(element.actualX) { lement.actualX }
	 */
   // element.topY =
   /*
	 * setTimeout ( function () {
	 * container.scrollLeft=x-(document.all?0:container.offsetLeft),1);
	 * container.scrollTop=y-(document.all?0:container.offsetTop ,1);
	 * myScrollTo( }, element.time )
	 */
    
    return element;
}
  function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
function addSlashes(str) 
{
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function include(source){
	document.write("<scr"+"ipt type='text/javascript' src='"+source+"'></scr"+"ipt>");
	/*
	 * var script = document.createElement('script'); script.type
	 * ="text/javascript"; script.src = source;
	 * document.body.appendChild(script);
	 */
}

function domjs_includer(src)
{
	var script =  document.createElement('script');
	script.type ="text/javascript";
	script.src = src;
	document.body.appendChild(script);
}


function http_build_query( formdata, numeric_prefix, arg_separator ) {
    // http://kevin.vanzonneveld.net
    // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + improved by: Legaev Andrey
    // + improved by: Michael White (http://getsprink.com)
    // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // - depends on: urlencode
    // * example 1: http_build_query({foo: 'bar', php: 'hypertext processor',
	// baz: 'boom', cow: 'milk'}, '', '&amp;');
    // * returns 1:
	// 'foo=bar&amp;php=hypertext+processor&amp;baz=boom&amp;cow=milk'
    // * example 2: http_build_query({'php': 'hypertext processor', 0: 'foo', 1:
	// 'bar', 2: 'baz', 3: 'boom', 'cow': 'milk'}, 'myvar_');
    // * returns 2:
	// 'php=hypertext+processor&myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_3=boom&cow=milk'
 
    var key, use_val, use_key, i = 0, j=0, tmp_arr = [];
 
    if (!arg_separator) {
        arg_separator = '&';
    }
 
    for (key in formdata) {
        use_val = urlencode(formdata[key].toString());
        use_key = urlencode(key);
 
        if (numeric_prefix && !isNaN(key)) {
            use_key = numeric_prefix + j;
            j++;
        }
        tmp_arr[i++] = use_key + '=' + use_val;
    }
 
    return tmp_arr.join(arg_separator);
}

function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // + original by: Philip Peterson
    // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + input by: AJ
    // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // % note: info on what encoding functions to use from:
	// http://xkr.us/articles/javascript/encode-compare/
    // * example 1: urlencode('Kevin van Zonneveld!');
    // * returns 1: 'Kevin+van+Zonneveld%21'
    // * example 2: urlencode('http://kevin.vanzonneveld.net/');
    // * returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // * example 3:
	// urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // * returns 3:
	// 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                                     
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding
	// functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret); // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

function filter(element)
{
	ajaxRequest(CURRENT_SECTION, CURRENT_ACTION, {page: $$('current_page').value, filter: element.innerHTML}, filterResponse);
}

function filterResponse(response)
{
	if (response.status)
	{
		$$('lista_juegos').innerHTML = response.data;
	} 
	else
	{
		alert(response.message);
	}
}

/* ELIMINAR Array.prototype.remove */
/*
 * Array.prototype.remove = function(from, to){ var rest = this.slice((to ||
 * from) + 1 || this.length); this.length = from < 0 ? this.length + from :
 * from; return this.push.apply(this, rest); };
 */
function cl(x){
	if (typeof console != 'undefined')
		if (console.log)
			console.log(x);
}


var escaleDiv = function (div,clicker,freq)
	{
		var _this = this;
		this.toogle = false;
		this.heigth = getStyle(div,'height').replace('px','');
		div.style.height = '0px';
		show(this.div);
		div.style.overflow ='hidden';
		if(!freq)
			freq = 1;
		this.scale = (this.heigth/freq);
		this.div = div;
		this.count = 0;
		addEvent
		(
			clicker,
			'click',
			function ()
			{
				_this.expandFuct(_this.toogle?false:true);
			}
		);
	};
	escaleDiv.prototype.expandFuct = function (bool)
	{
		this.toogle = bool;
		this.expand();
	};
	escaleDiv.prototype.expand = function ()
	{
		var _this = this;
		setTimeout(function()
		{	
			
			if(_this.toogle)
			{
				if(_this.count<_this.heigth)
				{
					_this.count += Math.floor (_this.scale);
					_this.div.style.height = _this.count+'px';
					_this.expand(_this.count);
				}
				else
				{
					setTimeout(
						function()
						{
							_this.div.style.height = _this.heigth+'px';
						},
						1
					);
				}
			}
			else
			{
				if(_this.count>0)
				{
					
					_this.count -= Math.floor (_this.scale);
					_this.div.style.height = _this.count+'px';
					_this.expand(_this.count);
				}
				else
				{
					setTimeout(
						function()
						{
							_this.div.style.height = 0+'px';
						},
						1
					);
				}
			}
		},1);
	};
function script(code)
{
	window.eval(code);
}

/* TERMINA COMMON.JS */

/* INICIA AUTOCOMPLETE.JS */

// autocomplete
var autoCompleteDrop = function (options)
{
	var _this = this;
	this.options = options;
	this.input = $$(this.options.input_id);
	this.input.setAttribute("autocomplete", "off");
	this.lastValue = "";
	this.timeout;
	if(typeof this.options.min_length == 'undefined'){
		this.options.min_length = 1;
	}
	this.processKeywords = this.options.processKeywords || false;
	addEvent
	(
		this.input,
		'keyup',
		function(e){
			_this.onKeyUp(e);
		}
	);
	addEvent
	(
		document.body,
		'click',
		function(e){
			if (!/autocomplete|acNoHide|toggleSelector/.test(getTarget(e).className)) {
				_this.dropDownDIV.style.display = 'none';
			}
		}
	);
	this.buildDropDown();
	this.isFirstRequest = true;
	this.Request = new Array();
	this.autoSelectFirst = this.options.autoSelectFirst;
};
autoCompleteDrop.prototype.buildDropDown = function()
{
	var div = $c('div');
	this.dropDownDIV = div;
	div.className = 'autocomplete';
		
	if (isBrowser.IE){	
		// div.style.marginTop = '18px';
		// div.style.marginLeft = '279px';
		// div.style.width = '228px';
		var mBottom = getStyle(this.input,'margin-bottom');
		div.style.marginTop = '-'+(mBottom == 'auto')?'0px':mBottom;
		div.style.width = getStyle(this.input,'width');
		var mLeft = getStyle(this.input,'margin-left');
		div.style.marginLeft = (mLeft == 'auto')?'0px':mLeft;
	}else{
		div.style.marginTop = '-'+getStyle(this.input,'margin-bottom');
		// div.style.marginTop = '-'+this.input.style.marginBottom+'px';
		if(CURRENT_SECTION == 'admin'){
			var selectorWidth = parseInt(getStyle(this.input,'width').replace('px','')) + 24;
			selectorWidth = selectorWidth + 'px';
		} else {
			var selectorWidth = getStyle(this.input,'width');
		}
		div.style.width = selectorWidth;
		// div.style.width = this.input.style.width+'px';
		div.style.marginLeft = getStyle(this.input,'margin-left');
		// this.input.style.left = getStyle(this.input,'left');
		// div.style.top =
		// (this.input.offsetTop+pxToNum(getStyle(this.input,'height')))+'px'
		// div.style.marginLeft = this.input.style.marginLeft;
	}
	
	// div.style.left = (this.input.offsetLeft+5)+'px';
	// div.style.marginTop = this.input.style.height;
	// div.style.marginLeft = pxToNum(div.style.marginLeft) +
	// pxToNum(getStyle(this.input,'padding-left'));
	div.style.display = 'none';
	insertAfter(div,this.input);
};

autoCompleteDrop.prototype.getDiv =  function ()
{
	return this.dropDownDIV;
};

autoCompleteDrop.prototype.onKeyUp =  function (e){
	var text = getTarget(e).value;
	var elementId = $$('current_cascade_hidden') ? $$('current_cascade_hidden').value : undefined;
	var key = getPressedKey(e);
	var _this =  this;
	if(!/(38|40|13|27)/.test(key)){
		if (this.input.value != '' && this.input.value.length >= this.options.min_length && this.lastValue != this.input.value){
			this.lastValue = this.input.value;
			var xhrCallBack = function (r){
				_this.getData(r);
			};
			if (this.options.processData){
				this.showAndhideSelects(false);
				xhrCallBack(this.options.processData(text));
			} else {
				if(this.timeout) { clearTimeout(this.timeout); }
				this.timeout = setTimeout(function(){
					if (_this.processKeywords) {
						text = encodeURIComponent(text);
					}
					$.ajax( {
						url: DOMAIN,
						data: { 
							'seccion': _this.options.section, 'accion': _this.options.action,
							'keywords': text, 'dependsOn': elementId, 'other_params':_this.options.extra_params, 'ajax_request': 1 
						},
						success: function(obj) {
							xhrCallBack(obj);
						}
					} );
					_this.showAndhideSelects(false);
				}, 250);
			}
		}else{
			this.dropDownDIV.style.display = 'none';
			this.showAndhideSelects(true);
		}
	}else{
		if (key == '38'){
			if (this.position-1<0){
				return;
			}
			this.last = this.position;
			if(this.last>=0){
				this.arrayDivs[this.last].className = 'out';
			}
			this.position --;
			this.arrayDivs[this.position].className = 'in';
		}else if(key == '40'){
			if (this.position+1>this.arrayDivs.length-1){
				return;
			}
			this.last = this.position;
			if(this.last>=0){
				this.arrayDivs[this.last].className = 'out';
			}
			this.position ++;
			this.arrayDivs[this.position].className = 'in';
		}else if(key == '13'){
			if (this.position==-1)return;
			this.dropDownDIV.style.display = 'none';
			if (this.options.autoInsert)
				this.input.value = stripTags(this.arrayDivs[this.position].innerHTML);
			if (typeof this.options.dropDownClick == 'function'){
				this.options.dropDownClick(this.arrayItems[this.position]['id'],this.arrayItems[this.position]['value']);
			}
			this.showAndhideSelects(true); 
		}else if(key == '27'){
			if(_this.autoSelectFirst)
				this.input.value = stripTags(this.arrayDivs[this.position].innerHTML);
			this.dropDownDIV.style.display = 'none';
			this.showAndhideSelects(true); 
		}
	}
};

autoCompleteDrop.prototype.getData = function (obj){
	var _this = this;
	this.dropDownDIV.innerHTML='';
	x = obj.data;
	if (typeof obj.data != 'object' | x == null){
		this.dropDownDIV.style.display = 'none';
		return;
	}
	this.lengthList = x.length;
	this.position = -1;
	this.last = 0;  
	this.arrayDivs = new Array();
	this.arrayItems = new Array();
	var withSubs = false;
	for(iz in x){
		if(typeof x[iz] != 'object'){
			continue;
		}
		var div_child = $c('div');
		div_child.className = 'out';
		div_child.onmouseover = function(){
			removeClass(this, 'out');
			addClass(this, 'min');
		};
		div_child.onmouseout = function(){
			removeClass(this, 'min');
			addClass(this, 'out');
		};
		if (obj.singleArray){
			div_child.innerHTML = x[iz];
			div_child.itemId = x[iz];
			div_child.itemValue = x[iz];
			this.arrayItems.push({ id: x[iz], value: x[iz] });
		}else{
			if(typeof x[iz]['value']['subs'] == 'object' || withSubs){
				withSubs = true;
				div_child.innerHTML = x[iz]['value']['value'];
				div_child.itemId = x[iz]['id'];
				div_child.itemValue = x[iz]['value']['value'];
				addClass(div_child, 'level1');
				this.arrayItems.push({ id: x[iz]['id'], value: x[iz]['value']['value'] });
			} else {
				if( typeof x[iz]['value'] == 'object' ) {
					div_child.innerHTML = x[iz]['value']['value'];
					div_child.itemId = x[iz]['id'];
					div_child.itemValue = x[iz]['value']['value'];
					this.arrayItems.push({ id: x[iz]['id'], value: x[iz]['value']['value'] });
				} else {
					div_child.innerHTML = x[iz]['value'];
					div_child.itemId = x[iz]['id'];
					div_child.itemValue = x[iz]['value'];
					this.arrayItems.push({ id: x[iz]['id'], value: x[iz]['value'] });
				}
			}
		}
		div_child.autoCompleteObj = this;
		div_child.onclick = function(){
			_this.dropDownDIV.style.display = 'none';
			_this.clickDiv(this);
			_this.showAndhideSelects(true);
		};
		this.arrayDivs.push(div_child);
		$a(this.dropDownDIV,div_child);
		if( !obj.singleArray ) {
			if(typeof x[iz]['value']['subs'] == 'object'){
				var subs = x[iz]['value']['subs'];
				for(siz in subs){
					var div_child2 = $c('div');
					div_child2.className = 'out level2';
					div_child2.onmouseover = function(){
						removeClass(this, 'out');
						addClass(this, 'min');
					};
					div_child2.onmouseout = function(){
						removeClass(this, 'min');
						addClass(this, 'out');
					};
					
					div_child2.innerHTML = subs[siz];
					div_child2.itemId = siz;
					div_child2.itemValue = subs[siz];
					this.arrayItems.push({ id: siz, value: subs[siz] });
					
					div_child2.autoCompleteObj = this;
					div_child2.onclick = function(){
						_this.dropDownDIV.style.display = 'none';
						_this.clickDiv(this);
						_this.showAndhideSelects(true);
					};
					this.arrayDivs.push(div_child2);
					$a(this.dropDownDIV,div_child2);
				}
			}
		}
	}
	this.dropDownDIV.style.display = 'block';
	if (isBrowser.IE){
		var cc = parseInt(getStyle(this.input,'width'))+4;
		this.dropDownDIV.style.width = cc-2;
		// this.dropDownDIV.style.marginLeft = '-'+cc;
		if (getStyle(this.input,'height')=='auto'){
			this.dropDownDIV.style.marginTop = '0px';
		}else{
			this.dropDownDIV.style.marginTop = getStyle(this.input,'height');
		}
	}
	if(this.autoSelectFirst){
		if (this.position+1>this.arrayDivs.length-1){
			return;
		}
		this.last = this.position;
		if(this.last>=0){
			this.arrayDivs[this.last].className = 'out';
		}
		this.position ++;
		this.arrayDivs[this.position].className = 'in';
	}
};

autoCompleteDrop.prototype.showAndhideSelects = function (bol)
{
	var selects = document.getElementsByTagName('select');
	if (isBrowser.IE){
		var i = selects.length;
		while (i--) selects[i].style.visibility = bol ? 'visible' : 'hidden';
	}
};
autoCompleteDrop.prototype.request = function(text, elementId){
	var _this = this;
	var xhrCallBack = function (r){
		_this.getData(r);
	};
	if (_this.options.processData){
		this.showAndhideSelects(false);
		xhrCallBack(_this.options.processData(text));
	}else{
		if (_this.processKeywords) {
			text = encodeURIComponent(text);
		}
		$.ajax( {
			url: DOMAIN,
			data: { 
				'seccion': _this.options.section, 'accion': this.options.action,
				'keywords': text, 'dependsOn': elementId, 'other_params':_this.options.extra_params, 'ajax_request': 1 
			},
			success: function(obj) {
				xhrCallBack(obj);
			}
		} );
		this.showAndhideSelects(false);
	}
};
autoCompleteDrop.prototype.clickDiv = function(div_child){
	if (div_child.autoCompleteObj.options.autoInsert)
		this.input.value = stripTags(div_child.innerHTML);
	if (typeof div_child.autoCompleteObj.options.dropDownClick == 'function'){
		div_child.autoCompleteObj.options.dropDownClick(div_child.itemId,div_child.itemValue);
	}
};
autoCompleteDrop.prototype.getSelectedOption = function(){
	var divs = this.getDiv().childNodes;
	var selectedOption = "";
	for(i=0,size=divs.length;i<size;i++){
		if (divs[i].className == 'in') {
			selectedOption = stripTags(divs[i].innerHTML);
			break;
		}
	}
	return selectedOption;
};
/* TERMINA AUTOCOMPLETE.JS */

/* INICIA SELECTOR.JS */
var Selector = function(opt){
	var _this = this;
	this.opt = opt;
	this.id = opt.input_id;
	this.itemsBox = $$(opt.id);
	addClass(this.itemsBox,'selector');
	if (opt.overflowy){
		this.itemsBox.style.overflowY = 'scroll';
	}
	if (opt.autoInsert){
		$$(opt.input_id).onkeyup = function(e){
			var key = getPressedKey(e);
			if(key==13&&trim(this.value)!=''){
			
				if (typeof _this.opt.afterInsert == 'function') 
					_this.opt.afterInsert(this.id,this.value);
			
				if (_this.opt.split){
					var items = new Array();
					if (_this.opt.separator){
						items = this.value.split(_this.opt.separator);
					}else{
						items = this.value.split(',');
					}
					for (var i=0; i<items.length; i++){
						x = trim(items[i]);
						if (x!=''){
							_this.add(x,x);	
						}
					}
				}else{
					_this.add(this.value,this.value);
				}
				this.value = '';
			}
		};
	}
	this.arr = new Array();
	this.insert = function(){
		var value = $$(this.opt.input_id).value;
		if(trim(value)=='') return;
		if(this.opt.split){
			var items = new Array();
			if(this.opt.separator){
				items = value.split(_this.opt.separator);
			}else{
				items = value.split(',');
			}
			for(var i=0; i<items.length; i++){
				x = trim(items[i]);
				if(x!=''){
					this.add(x,x);	
				}
			}
		}else{
			this.add(value,value);
		}
		$$(this.opt.input_id).value = '';
	};
	this.add = function(id,value){
	
		if (this.opt.onlyValues){
			id = value;
		}
		
		if (typeof this.opt.beforeInsert == 'function'){
			if (!this.opt.beforeInsert(id,value)){
				return false;
			}
		}
		
		if (!this.opt.repeat){
			for (i in this.arr){
				if (this.arr[i]['id']==id){
					return false;
				}
			}
		}
		
		div = $c('div');
		div.className = 'item';
		div.activeFlag = true;
		div.id = 'item'+id+this.id;
		div.onmouseover = function(){
			if (!this.activeFlag)
				return;
			if (this.selector.selItem==this.itemId) 
				this.className='item_selected';
			else
				this.className='item_hover';
		};
		div.onmouseout = function(){
			if (!this.activeFlag)
				return;
			if (this.selector.selItem==this.itemId)
				this.className='item_selected wline'; 
			else
				this.className='item';
		};
		div.itemId = id;
		div.itemValue = value; 
		div.selector = this;
		if (typeof this.opt.clickItem == 'function'){
			div.onclick = function(){
				if (!this.activeFlag)
					return;
				this.className = 'item_selected';
				oldItem = false;
				if ($$('item'+this.selector.selItem+this.selector.id)&&this.selector.selItem!=this.itemId){
					$$('item'+this.selector.selItem+this.selector.id).className = 'item';
					oldItem = $$('item'+this.selector.selItem+this.selector.id).itemId;
				}
				this.selector.selItem = this.itemId;
				this.selector.opt.clickItem(this.itemId,this.itemValue,oldItem,this.selector.opt.extra_params);
			};
		}
		
		text = $c('span');
		text.innerHTML = value;
		
		del = $c('a');
		del.className = 'x';
		del.innerHTML = 'x';
		del.selector = this;
		del.idItem = id;
		del.onclick = function(){
			if (this.selector.selItem==this.idItem)
				this.selector.selItem=false;
			this.selector.remove(this.idItem);
		};
		del.href = "javascript:void(0);";
		div.appendChild(del);
		div.appendChild(text);
		
		this.itemsBox.appendChild(div);
		this.arr.push({ 'id':id,'value':value });
		this.setHiddenValues();
		this.itemsBox.style.top = '-1000px';
		
		if (typeof this.opt.onAdd == 'function'){
			this.opt.onAdd(id,value);
		}
	};
	this.remove = function(id){
		$$('item'+id+this.id).activeFlag = false;
		$$('item'+id+this.id).className = 'item_selected ritem';
		var index = -1;
		for(var i=0; i<this.arr.length; i++){
		   	if(this.arr[i]['id'] == id){
		    	index = i;
		    	break;
		    }
		}
		if (index==-1){
			alert('Error: no se encontró el elemento.');
			return;
		}
		if (typeof this.opt.confirmDelete == 'function'){
			if (!this.opt.confirmDelete(this.arr[index]['id'],this.arr[index]['value'])){
				$$('item'+id+this.id).className = 'item_selected';
				$$('item'+id+this.id).activeFlag = true;
				return;
			}
		}
		tmpId = id;
		tmpValue = this.arr[index]['value'];
		removeNode('item'+id+this.id);
		oldItem = this.selItem;
		if (this.selItem==id)
			this.selItem = false;
		// this.arr.remove(index);/* ELIMINAR Array.prototype.remove */
		/* ESTAS LINEAS SUSTITUYEN this.arr.remove */
		var restArr = this.arr.slice((index + 1) || this.arr.length);
		this.arr.length = index < 0 ? this.arr.length + index : index;
		this.arr.push.apply(this.arr, restArr);
		/** ************************************** */
		this.setHiddenValues();
		if (typeof this.opt.clickDeleteItem == 'function'){
			this.opt.clickDeleteItem(tmpId,tmpValue,oldItem);	
		}
	};
	this.getData = function(){
		var tmp = new Array();
		for (var i=0;i<this.arr.length;i++){
			tmp.push(this.arr[i]);
		} 
		return tmp;
	};
	this.getDataObj = function(){
		var tmp = new Object();
		for (var i=0;i<this.arr.length;i++){
			tmp[i] = this.arr[i];
		} 
		return tmp;
	};
	this.setData = function(arr){
		for(var i=0; i<arr.length; i++){
		   	this.add(arr[i]['id'],arr[i]['value']);
		}
	};
	this.setDataObj = function(obj){
		for(var i in obj){
		   	this.add(obj[i]['id'],obj[i]['value']);
		}
	};
	this.getDataStr = function(){
		var tmp = new Array();
		for (var i=0;i<this.arr.length;i++){
			tmp.push(this.arr[i]['value']);
		} 
		return tmp.join(', ');
	};
	this.selectItem = function(idItem){
	   	if(this.selItem != idItem){
	   		if (div = $$('item'+idItem+this.id)){
	   			div.className = 'item_selected';
	   			oldItem = false;
	   			if ($$('item'+this.selItem+this.id)&&this.selItem){
					$$('item'+this.selItem+this.id).className = 'item';
					oldItem = $$('item'+this.selItem+this.id).itemId;
				}
				this.selItem = idItem;
				if (typeof this.opt.clickItem == 'function') 
					this.opt.clickItem(div.itemId,div.itemValue,oldItem);
	   		}else{
	   			alert('Error: elemento no encontrado');
	   		}
	    }
	};
	this.getSelected = function(){
		for(var i=0; i<this.arr.length; i++){
		   	if(this.arr[i]['id'] == this.selItem){
		    	break;
		    }
		}
		return this.arr[i];
	};
	this.reset = function(){
		while(this.arr.length>0){
			removeNode('item'+this.arr[this.arr.length-1]['id']+this.id);
		   	// this.arr.remove(this.arr.length-1); /* ELIMINAR
			// Array.prototype.remove */
		   	/* ESTAS LINEAS SUSTITUYEN this.arr.remove */
			var restArr = this.arr.slice(this.arr.length);
			this.arr.length = (this.arr.length-1) < 0 ? this.arr.length + this.arr.length-1 : this.arr.length-1;
			this.arr.push.apply(this.arr, restArr);
			/** ************************************** */
		}
		this.arr = null;
		this.arr = new Array();
	};
	this.setHiddenValues = function(){
		if (!$$(this.opt.hidden)){
			return;
		}
		var tmp = new Array();
		for(var i=0; i<this.arr.length; i++){
			tmp.push(this.arr[i]['id']);
		}
		$$(this.opt.hidden).value = tmp.join(',');
	};

	if (opt.autocomplete){
		this.autoComp = new autoCompleteDrop({
			input_id : opt.input_id,
			section : opt.section,
			action : opt.action,
			autoInsert : opt.acAutoInsert,
			processData : opt.processAcData,
			processKeywords : opt.processKeywords,
			selector : _this,
			min_length : opt.min_length,
			extra_params : opt.extra_params,
			dropDownClick : function(id,value){
				this.selector.add(id,value);
				$$(this.input_id).value = '';
				$$(this.input_id).focus();
			}
		});
	}
};
/* TERMINA SELECTOR.JS */

/* EMPIEZA WINDOW.BETA.CLASS.JS */

var max_z_index_for_windows = 21;

// Comienzo de la Clase Window

function Window (window_id,options)
{
	
	var obj = new Object();
	
	// Id de la ventana
	obj.atributos = {top: 0, right: 0, bottom: 0, left: 0};
	    	    
	// Parametros
	obj.window_id = window_id;	 
	obj.is_textarea = options.is_textarea || false;
	obj.is_editor = options.is_editor || false;		
	obj.mensaje = options.mensaje || null;
	obj.html = options.html || null;
	obj.width = options.width || 320;
	obj.height = options.height || 240;
	obj.min_width = options.min_width || 160;
	obj.closable = options.closable || false;
	obj.draggable = options.draggable || false;
	obj.resizable = options.resizable || false;
	obj.toogle = options.toogle || false;
	obj.disable_screen = options.disable_screen || false;
	obj.class_name = options.class_name || 'window';	  
	obj.title = options.title || 'Ventana Personalizada';
	obj.append = options.append || false;	
	obj.onAfterClose= options.on_after_close || false;
	obj.onAfterHide = options.on_after_hide || false;
	obj.includeFooter = options.include_footer || false;
	obj.cssHeader = options.css_header || false;
	obj.cssWindowBody = options.css_window_body || false;
	addClass (obj.append,'insidediv');	
	obj.container = $$(options.container);
	
	// Funcion principal
    obj.createWindow = function ()
    {    this.ishided = true;
    	if(!document.getElementById(obj.window_id))
    	{    	
    		// Div para contener toda la ventana
			var total_win = document.createElement("div");
			total_win.className = "total_window";
			total_win.setAttribute("id", this.window_id + "_total_window");
			total_win.style.minWidth = this.min_width + "px";
			this.total_win = total_win;
						
			// Div para contener el cuerpo y el pie, sirve para ser
			// mostrada/escondida por los botones
			var body_and_footer = document.createElement("div");
			body_and_footer.className = "body_and_footer";
			body_and_footer.setAttribute("id", this.window_id + "_body_and_footer");
			this.body_and_footer = body_and_footer;
						
			// Atributos de la ventana
			var win = document.createElement("div");
			win.setAttribute("id", this.window_id);
			win.setAttribute("name", 'window_class_x');
			win.className = this.class_name;
			win.style.backgroundColor = 'transparent';			
			win.style.position = "absolute";
			win.style.left = this.atributos.left;
			win.style.top = this.atributos.top;
			// Instancia principal de la ventana
			this.win = win;
			
			obj.hideWindow();
			
			array_of_window_class[actual_posicion_array_of_window_class]=this.win;	
			actual_posicion_array_of_window_class++;		
			
			// Definir z index
			this.setZIndex(max_z_index_for_windows);
			
			// Definir ancho y altura
			this.setSize(this.width, this.height);
			
			if(navigator.userAgent.indexOf("MSIE")>=0) 
	    	{
	    		win.style.width = this.width;
	    		win.style.height = this.width;	    		
	    	}
			
			// Centrar la ventana
			obj.Center();
						
			// Crear Window Header
			this.CrearHeader();
			// Crear Window Body
			this.CrearBody();
			if (this.includeFooter) {
				// Crear Window Footer
				this.CrearFooter();
			}
			
			this.total_win.appendChild(body_and_footer);			
			win.appendChild(total_win);
			
			obj.container.appendChild(win);
			 
			// Agregar elemento a la ventana
			if (this.append)
			{
				this.appendToWindow(this.append);
			}				 
			
			// Hacer Draggable la Ventana
			if (this.draggable)
			{
				// var draggable = new ygDD(this.win_header.id);
				Drag.init(this.win_header,this.total_win.parentNode);
			}	
			
			if(this.resizable)
			{
				Resizable(this.win_esquina_footer.id, this.win.id,this.win_body.id);
			}						
			
			// hideSelect(this.win);
			hideOpposedSelects(this);			
			obj.aumentarZindex();			
		}
		else
		{
			// Cerrable o escondible solamente
			if(this.toogle)
			{
				try
				{
					// Tomando la ventana que ya habia sido creada
					var current_window = $$(this.window_id); 
					hide(current_window);
					// Disable Screen again
					if (this.disable_screen)
					{	
						DisableScreen(this.class_name, 'overlay_modal', current_window);
					}
					obj.aumentarZindex();
					obj.Center();					
				}
				catch(e){}
			}
		}
		if(isBrowser.IE6)
			obj.FixSelectsIE6();
		
    };
    
    obj.FixSelectsIE6 = function ()
    { 
    	var selects = this.append.getElementsByTagName('select');
    	var i = selects.length; while(i--)
    	{
    		selects[i].windowObject = this;
    	} 	 
    };
    // Funcion para crear cabecera
	obj.CrearHeader = function()
	{
		// Div para la cabecera
		var win_header = document.createElement('div');
		win_header.setAttribute('id',this.window_id + "_header");
		win_header.className = this.cssHeader || 'window_header gradiente';
		this.win_header = win_header;
    	addEvent(win_header,'mousedown',function(event){obj.aumentarZindex(event);},false);
    	// Titulo de la ventana
		var title = document.createElement('div');
		title.setAttribute('id',this.window_id + "_title");
		title.className = 'window_title';
		span_title = document.createElement('span');
		span_title.className = 'span_title';
		span_title.innerHTML = this.title;
						
		title.appendChild(span_title);	
		
		this.span_title = span_title;		
							
		// Botones
		var botones_cabecera = document.createElement('ul');
		botones_cabecera.className = 'window_header_buttons';
		botones_cabecera.style.width = "35px";
										
		// Validando si es cerrable o no
		if (this.closable)
		{
			var boton_cerrar = document.createElement('li');
			boton_cerrar.setAttribute('id',this.window_id + "_close_button");
			boton_cerrar.className = 'window_close_button';
		    addEvent(boton_cerrar,'click',function(event){obj.DestruirVentana(event);},false);			
			botones_cabecera.appendChild(boton_cerrar);
		}
		
		// Boton para maximizar
		var boton_maximizar = document.createElement('li');
		boton_maximizar.className = 'window_maximize_button';
		boton_maximizar.setAttribute('id',this.window_id + "_max_button");
		botones_cabecera.appendChild(boton_maximizar);	
	    addEvent(boton_maximizar,'click',function(event){obj.Maximizar(event);},false);			
		// Boton para minimizar
		var boton_minimizar = document.createElement('li');
		boton_minimizar.className = 'window_minimize_button';
		boton_minimizar.setAttribute('id',this.window_id + "_min_button");
		botones_cabecera.appendChild(boton_minimizar);
		addEvent(boton_minimizar,'click',function(event){obj.Minimizar(event);},false);			
		// Agregando elementos
		win_header.appendChild(title);
		win_header.appendChild(botones_cabecera);
		
		this.total_win.appendChild(win_header);			
	}; 
	
	obj.CrearBody = function()
	{			
		// Div para el cuerpo
		var win_body = document.createElement('div');
		win_body.setAttribute('id',this.window_id + "_body");
		win_body.className = this.cssWindowBody || 'window_body';
		
		// Arreglando falla de IE
		if(navigator.userAgent.indexOf("MSIE")>=0) 
	    {
			win_body.style.width = (this.width - 6) + "px";	    
		}	
	    else
	    {
			win_body.style.width = this.width + "px";
	    }
	    
		win_body.style.minWidth = this.min_width + "px";
		this.win_body = win_body;
		
		// Validar si el mensaje viene vacio, para mostrarlo o no
		if(this.mensaje)
		{
			var div_message = document.createElement('div');
			div_message.className = 'message_div';
			div_message.innerHTML = "<span>" + this.mensaje + "</span>";
			win_body.appendChild(div_message);				
		}
			
		// Validar si la ventana solo contendar un area de texto
		if(this.is_textarea && !this.append)
		{
			// Agregar editor a la ventana
			if(this.is_editor)
			{
				// Aqui va el editor
			}
			else
			{
				var div_textarea = document.createElement('div');
				div_textarea.className = 'textarea_div';
				this.div_textarea = div_textarea;
							    					
				var textarea = document.createElement('textarea');
				textarea.setAttribute('class','custom_textarea');
				textarea.setAttribute('id',this.window_id + '_custom_textarea');
				this.textarea = textarea;	
				
				// Agregar simple textarea
				div_textarea.appendChild(textarea);
				win_body.appendChild(div_textarea);							
			}		
		}
		
		if(this.html && !this.is_textarea)
		{
			win_body.innerHTML += this.html;
		}		
		addEvent(win_body,'click',function(event){obj.aumentarZindex(event);},false);		
		this.win_body = win_body;
				
		// Disable Screen
		if (this.disable_screen)
		{	
			DisableScreen(this.class_name, 'overlay_modal', this.win);
		}
					
		this.body_and_footer.appendChild(win_body);
		
		// var by ram
	};
	
	// Div para el pie de ventana
	obj.CrearFooter = function()
	{
		var win_footer = document.createElement('div');
		win_footer.setAttribute('id',this.window_id + "_footer");
		win_footer.className = 'window_footer';
		this.win_footer = win_footer;
				
		var win_esquina_footer = document.createElement('div');
		win_esquina_footer.setAttribute('id',this.window_id + "_esquina_footer");
		win_esquina_footer.className = 'window_esquina_footer';
		this.win_esquina_footer = win_esquina_footer;	
				
		win_footer.appendChild(win_esquina_footer);			
						
		this.body_and_footer.appendChild(win_footer);
	}; 		    
	
	// Funcion para definir los atributos de tamanio de la ventana
	obj.setSize = function(width, height) 
	{    
		width = parseFloat(width);
		height = parseFloat(height);
		
		// Validar si los tamanios son menores que los definidos como menores
		if (width < this.min_width)
		{
			width = this.min_width;
		}
		
		if (height < this.min_height)
		{
		    height = this.min_height;
		}
		
		this.width = width;
		this.height = height;

		// Aplicando tamaño
		this.win.style.width = width + "px";
		this.win.style.height = height + "px";
	};
	
	// Colocando ventana en esta posicion
	obj.SetLocation = function(top, left)
	{				
		this.win.style.top = top + 'px';
		this.win.style.left = left + 'px';
	};		
	
	// Definir z index
	obj.setZIndex = function(zindex) 
	{
		this.win.style.zIndex = zindex;
	};
	
	// Centrar ventana
	obj.Center = function(top, left) {
		// Tomando valores de ventana
		var window_scroll = GetWindowScroll();
		
		var page_size = GetPageSize();
		
		var topOffset = scrollTop();
		
		if (!top) {
			top = (page_size.window_height - (this.height)) / 2;
		}
		// top += window_scroll.top;
		
		if (!left) {
			// left = (page_size.window_width - (this.width)) / 2;
			// left = (page_size.window_width - (this.width)) / 2 - 340;
			left = (page_size.window_width - (this.width)) / 2;
		}
		left += window_scroll.left; 
		// top += topOffset;
				
		// Asignando Posicion
		this.SetLocation(top, left);
	}; 
	
	// Destruir totalmente la ventana
	obj.DestruirVentana = function(event){
		if (this.win.parentNode==null)
			return;
		this.ishided = true;
		// Definir si destruiremos la ventana o solo la esconderemos
		if(this.toogle)
		{
			this.win.style.display = "none";			
		}
		else
		{
			this.win.parentNode.removeChild(this.win);
		}
			
		// Metodo para habilitar pantalla
		if (this.disable_screen)
		{
			EnableScreen();
		}
		EnableScreen();
			
		if(navigator.userAgent.indexOf("MSIE 6.0")>=0) 
		{
			var do_it = true;
		
			for(var i=0;i<array_of_window_class.length;++i)
			{
				if(this.win.id != array_of_window_class[i].id)
				{
					if(array_of_window_class[i].style.display == "block")
					{
						do_it = false;
					}
				}
			}
				
			if(do_it)
			{		
				showSelect(this.win);	
			}
			else
			{
				var mayor_z_index = 0;
				var elemento_con_mayor_z;
				
				for(var i=0;i<array_of_window_class.length;++i)
				{
					if(this.win.id != array_of_window_class[i].id && array_of_window_class[i].style.display == "block")
					{
						if(array_of_window_class[i].style.zIndex > mayor_z_index)
						{
							mayor_z_index = array_of_window_class[i].style.zIndex;
							elemento_con_mayor_z = array_of_window_class[i];
						}
					}
				}		
					
			}
		}
		if(obj.onAfterClose)
		{
			obj.onAfterClose();
			obj.habilitarPantalla();
		}
		showAllSelects();
	};
	
	// Minimizar , ocultar cuerpo y pie
	obj.Minimizar = function(event)
	{
		this.body_and_footer.style.display="none";
	};
	
	// Maximizar , mostrar cuerpo y pie
	obj.Maximizar = function(event)
	{
		this.body_and_footer.style.display="block";
	};
	
	// Aumentar z Index
	obj.aumentarZindex = function(event)
	{
		this.win.style.zIndex = max_z_index_for_windows + 1;
		max_z_index_for_windows = parseInt(this.win.style.zIndex);
		// if(this.ishided)hideOpposedSelects(this);
	};
	
	obj.appendToWindow = function(element)
	{
		this.win_body.appendChild(element);
	};
	
	// Mostrar Ventana
	obj.showWindow = function()
	{
		obj.ishided = false;
		obj.aumentarZindex();
		obj.Center();		
		
		if(navigator.userAgent.indexOf("MSIE 6.0")>=0) 
		{	
			var do_it = true;		
											
			for(var i=0;i<array_of_window_class.length;++i)
			{
				if(this.win.id != array_of_window_class[i].id)
				{
					if(array_of_window_class[i].style.display == "block")
					{
						do_it = false;
					}
				}
			}	
			
			if(do_it)
			{
				hideOpposedSelects(this);
							
			}
		}
		
		this.win.style.display = "block";
		this.deshabilitarPantalla();
	};
	
	// Ocultar Ventana
	obj.hideWindow = function(id)
	{
		if(navigator.userAgent.indexOf("MSIE 6.0")>=0) 
		{
			var do_it = true;
		/*
		 * for(var i=0;i<array_of_window_class.length;++i) { if(this.win.id !=
		 * array_of_window_class[i].id) { if(this.win.id !=
		 * array_of_window_class[i].id) {
		 * if(array_of_window_class[i].style.display == "block") { do_it =
		 * false; } } } }
		 */
			if(do_it)
			{		
				obj.ishided = false;showSelect(this.win);	
			}
		}
		
		this.win.style.display = "none";
		this.habilitarPantalla();
		
		if(obj.onAfterHide)
		{
			obj.onAfterHide();
		}	
		showAllSelects();
		obj.ishided = true;
	};
	
	// Habilitar Pantalla
	obj.habilitarPantalla = function()
	{
		EnableScreen();	
	};
	
	// Deshabilitar Pantalla
	obj.deshabilitarPantalla = function()
	{
		obj.aumentarZindex();
		DisableScreen(this.class_name, 'overlay_modal', this.win);
	};
	
	// Deshabilitar Pantalla
	obj.cambiarTitulo = function(titulo)
	{
		this.span_title.innerHTML = titulo;
	};			
		
	// Crear ventana
    obj.createWindow();	
        
    return obj;
} 

var array_of_window_class = new Array();
var actual_posicion_array_of_window_class = 0;
// Fin de la Clase

/* TERMINA WINDOW.BETA.CLASS.JS */

/* EMPIEZA WINDOW.BETA.UTILITIES.JS */

// Tomar atributos de la ventana
function GetWindowScroll(parent) 
{
	var T, L, W, H;
	parent = parent || document.body;              
	if (parent != document.body) 
	{
		T = parent.scrollTop;
		L = parent.scrollLeft;
		W = parent.scrollWidth;
		H = parent.scrollHeight;
	} 
	else 
	{
		var w = window;
		with (w.document) 
		{
			if (w.document.documentElement && documentElement.scrollTop) 
			{
				T = documentElement.scrollTop;
				L = documentElement.scrollLeft;
			} 
			else if (w.document.body) 
			{
				T = body.scrollTop;
				L = body.scrollLeft;
			}
			if (w.innerWidth) 
			{
				W = w.innerWidth;
				H = w.innerHeight;
			} 
			else if (w.document.documentElement && documentElement.clientWidth) 
			{
				W = documentElement.clientWidth;
				H = documentElement.clientHeight;
			} 
			else 
			{
				W = body.offsetWidth;
				H = body.offsetHeight;
			}
		}
	}
	return { top: T, left: L, width: W, height: H };
} 

// GetPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez

function GetPageSize(parent)
{
	parent = parent || document.body;              
	var window_width, window_height;
	var page_height, page_width;
	
	if (parent != document.body) 
	{
		window_width = parent.getWidth();
		window_height = parent.getHeight();                                
		page_width = parent.scrollWidth;
		page_height = parent.scrollHeight;                                
	} 
	else 
	{
		var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) 
		{  
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} 
		else if (document.body.scrollHeight > document.body.offsetHeight)
		{ 
			// all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} 
		else 
		{ 
			// Explorer Mac...would also work in Explorer 6 Strict, Mozilla and
			// Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		if (self.innerHeight) 
		{  
			// all except Explorer
			window_width = self.innerWidth;
			window_height = self.innerHeight;
		} 
		else if (document.documentElement && document.documentElement.clientHeight) 
		{ 
			// Explorer 6 Strict Mode
			window_width = document.documentElement.clientWidth;
			window_height = document.documentElement.clientHeight;
		} 
		else if (document.body) 
		{ 
			// other Explorers
			window_width = document.body.clientWidth;
			window_height = document.body.clientHeight;
		}  
		
		// for small pages with total height less then height of the viewport
		if (yScroll < window_height)
		{
			page_height = window_height;
		} 
		else 
		{ 
			page_height = yScroll;
		}

		// for small pages with total width less then width of the viewport
		if (xScroll < window_width)
		{  
			page_width = window_width;
		} 
		else 
		{
			page_width = xScroll;
		}
	} 
            
	return {page_width: page_width ,page_height: page_height , window_width: window_width, window_height: window_height};
}

// Deshabilitar pantalla
function DisableScreen(className, overlayId, contentId) 
{
 	// Iniciar estilos para deshabilitar pantalla
	lightBox(overlayId, className);
	
	var objBody = document.body;
	
	// Objetos
	var obj_overlay = document.getElementById(overlayId);
	
	// Tomar los tamanios de atributos de pagina
	var pageSize = GetPageSize();
	
	// IE fix
	if(navigator.appVersion.indexOf("MSIE 6.0") != -1)
	{
		obj_overlay.style.backgroundColor ='transparent';
	}
	
	// Estilos
	obj_overlay.style.height = (pageSize.page_height + 'px');
	obj_overlay.style.width = (pageSize.window_width + 'px');
	obj_overlay.style.overflow = 'hidden';
	obj_overlay.style.display = 'block';
}

// Habilitar pantalla
function EnableScreen(id) 
{
	id = id || 'overlay_modal';
	
	var obj_overlay =  document.getElementById(id);
	
	if (obj_overlay) 
	{
		// Esconder overlay
		obj_overlay.style.display = 'none';
		// Removiendo overlay
		// obj_overlay.parentNode.removeChild(obj_overlay);
	}
}

// Estilos para deshabilitar pantalla
function lightBox(id, className) 
{
	// Already done, just update zIndex
	var element_id = document.getElementById(id);
	
	if (element_id) 
	{
		// element_id.style.zIndex = Windows.maxZIndex + 10;
		element_id.style.zIndex = 10;
	}
	// create overlay div and hardcode some functional styles (aesthetic styles
	// are in CSS file)
	else 
	{
		var objBody = document.body;
		
		var obj_overlay = document.createElement('div');
		obj_overlay.setAttribute('id',id);
		obj_overlay.className = "overlay_" + className;
		
		obj_overlay.style.display = 'none';
		obj_overlay.style.position = 'absolute';
		obj_overlay.style.top = '0';
		obj_overlay.style.left = '0';
		obj_overlay.style.zIndex = 10;
		obj_overlay.style.width = '100%';
		
		objBody.insertBefore(obj_overlay, objBody.firstChild);
	}
}

function hideSelect(element) 
{
	if(navigator.userAgent.indexOf("MSIE 6.0")>=0) 
	{
		var all_selects = document.body.getElementsByTagName('select');
		var window_selects = element.getElementsByTagName('select');
		
		for(var i in all_selects)
		{
			if(typeof all_selects[i] == "object")
			{
				all_selects[i].style.visibility = 'hidden';
			}
			// alert('ocultar');
		}
		
		for(var i in window_selects)
		{
			if(typeof window_selects[i] == "object")
			{
				window_selects[i].style.visibility = 'visible';
			}
		}				
	}		
}

function showSelect(element) 
{
	if(navigator.userAgent.indexOf("MSIE 6.0")>=0) 
	{
		var all_selects = document.body.getElementsByTagName('select');
		var window_selects = element.getElementsByTagName('select');
		
		for(var i in all_selects)
		{
			// alert(typeof all_selects[i]);
			if((typeof all_selects[i]).toLowerCase() == "object")
			{
				all_selects[i].style.visibility = 'visible';
				all_selects[i].style.display = 'block';
			}
		}
		
		for(var i in window_selects)
		{
			if((typeof window_selects[i]).toLowerCase() == "object")
			{
				window_selects[i].style.visibility = 'visible';
				all_selects[i].style.display = 'block';
			}
		}				
	}		
}

function showAllSelects()
{
	
	if(navigator.userAgent.indexOf("MSIE 6.0")>=0)
	{
		var selects = document.getElementsByTagName('select');
		var i = selects.length;while(i--)
		{	
			try
			{
				selects[i].style.visibility = 'visible';
				selects[i].style.display = 'block';
			}catch(e)
			{}
		}

	}
}

function hideOpposedSelects(object)
{
	var selects = document.getElementsByTagName('select');
	if(isBrowser.IE6)
	{
		var i = selects.length; while(i--)
		{
			if(selects[i].windowObject != object) 
			{
				selects[i].style.visibility = 'hidden';
				selects[i].style.display = 'none';
			}
		}
	}
	
}

/* TERMINA WINDOW.BETA.UTILITIES.JS */

/* EMPIEZA dragAndDrop.js */

var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y);
		else if (o.yMapper)	ny = o.yMapper(x);

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};

/* TERMINA dragAndDrop.js */

/* EMPIEZA Resizable.beta.class.js */

// Clase para aplicar resize a un div especificado
function Resizable(div,objetivo,objetivo2)
{
	var obj = new Object();
	
	// Tomando id del handler y los targets
	obj.div = document.getElementById(div);
	obj.objetivo = document.getElementById(objetivo);
	obj.objetivo2 = document.getElementById(objetivo2);
		
	// Definiendo el navegador, si es IE o no
    if(navigator.userAgent.indexOf("MSIE")>=0 || navigator.userAgent.indexOf("Opera")>=0) 
    {
    	obj.navegador = 0;
    }	
    // Otros
    else 
    {
    	obj.navegador = 1;
    }
    
    // Inicializando posicion
    obj.posicion = 0;
         
    obj.comienzoResize = function(event)
    {         
		obj.objetivo.style.zIndex = max_z_index_for_windows + 1;
		max_z_index_for_windows = parseInt(obj.objetivo.style.zIndex);
      	           
         // Verifico el navegador para agarrar distintos metodos
        if(obj.navegador==0)
         {
            // Aplicando los eventos
            obj.objetivo.attachEvent("onmousemove", obj.enMov);
            obj.objetivo.attachEvent("onmouseup", obj.finMov);
            
            obj.objetivo2.attachEvent("onmousemove", obj.enMov);
            obj.objetivo2.attachEvent("onmouseup", obj.finMov);
            
            obj.div.attachEvent("onmousemove", obj.enMov);
            obj.div.attachEvent("onmouseup", obj.finMov); 
        }
        if(obj.navegador==1)
        {   
            // Aplicando los eventos
           	obj.objetivo.addEventListener("mousemove", obj.enMov, true);
            obj.objetivo.addEventListener("mouseup", obj.finMov, true);  
            
            obj.objetivo2.addEventListener("mousemove", obj.enMov, true);
            obj.objetivo2.addEventListener("mouseup", obj.finMov, true);  
                        
            obj.div.addEventListener("mousemove", obj.enMov, true);
            obj.div.addEventListener("mouseup", obj.finMov, true);  
         }
        
        // Tomando posicion inicial del elemento
        obj.elComienzoX=parseInt(obj.objetivo.style.left);
        obj.elComienzoY=parseInt(obj.objetivo.style.top);
        obj.elAncho=parseInt(obj.objetivo.style.width);
        obj.elAltura=parseInt(obj.objetivo.style.height);   
    };
       
    obj.enMov = function(event)
    {             
		obj.objetivo.style.zIndex = max_z_index_for_windows + 1;
		max_z_index_for_windows = parseInt(obj.objetivo.style.zIndex);   	
    		
        var xActual, yActual;
        
        if(obj.navegador==0)
        {   
        	// Tomar cursor en X y Y
            xActual=window.event.clientX;
            yActual=window.event.clientY;
        } 
        if(obj.navegador==1)
        {
        	// Tomar cursor en X y Y
            xActual=event.clientX;
            yActual=event.clientY;
        }        
       
       	// Aplicando formula para determinar los nuevos atributos de anchura y
		// altura
        var newWidht = obj.elAncho-((obj.elComienzoX+obj.elAncho)-xActual);     
        var newHeight = obj.elAltura-((obj.elComienzoY+obj.elAltura)-yActual);

		// Aplicando nuevos atributos para los 2 objetivos marcados
        obj.objetivo.style.width=(obj.elAncho-((obj.elComienzoX+obj.elAncho)-xActual)+4.5) + "px";
        obj.objetivo.style.height=(obj.elAltura-((obj.elComienzoY+obj.elAltura)-yActual)) + "px"; 
                      
        obj.objetivo2.style.width=(obj.elAncho-((obj.elComienzoX+obj.elAncho)-xActual)-1.1) + "px";
        obj.objetivo2.style.height=(obj.elAltura-((obj.elComienzoY+obj.elAltura)-yActual)-40) + "px";         
    };
       
    obj.finMov = function(event)
    {    
    	// Metodos para detener la ejecucion de los eventos
        if(obj.navegador==0)
        {   
            obj.objetivo.detachEvent("onmousemove", obj.enMov);
            obj.objetivo.detachEvent("onmouseup", obj.finMov);           
           
            obj.objetivo2.detachEvent("onmousemove", obj.enMov);
            obj.objetivo2.detachEvent("onmouseup", obj.finMov); 
                       
            obj.div.detachEvent("onmousemove", obj.enMov);
            obj.div.detachEvent("onmouseup", obj.finMov);
            
        }
        if(obj.navegador==1)
        {
            obj.objetivo.removeEventListener("mousemove", obj.enMov, true);
            obj.objetivo.removeEventListener("mouseup", obj.finMov, true);
            
            obj.objetivo2.removeEventListener("mousemove", obj.enMov, true);
            obj.objetivo2.removeEventListener("mouseup", obj.finMov, true);
                        
            obj.div.removeEventListener("mousemove", obj.enMov, true);
            obj.div.removeEventListener("mouseup", obj.finMov, true);            
        }
    };
     
    // Agregando eventos
    if(obj.navegador==0)
    {
		obj.div.attachEvent
		(
			'onmousedown',
			function(event)
			{
				obj.comienzoResize(event, obj.objetivo.id);
			}
		); 
    }
    else
    {
		obj.div.addEventListener
		(
			'mousedown',
			function(event)
			{
				obj.comienzoResize(event, obj.objetivo.id);
			},
			false
		);
    }  		       
}  

/* TERMINA Resizable.beta.class.js */

/* COMMENTS */
function sendComment(){
	if (rmv = $$('ajax_message')){
		rmv.parentNode.removeChild(rmv);
	}
	if (editor){
		txt = editor.getHTML();
	}else{
		txt = $$('txt_comment').value;
	}
	if (txt.length > 2200){
		alert('Se excedió la longitud máxima permitida del comentario. Por favor reduce el tamaño.');
		return;
	}
	params = {'item_id':ITEM_ID,'text':txt,'page':PAGE_NUM};
	disable('btnSendComment');
	$$('sendCommentMessage').innerHTML = 'Enviando...';
	ajaxRequest(CURRENT_SECTION, 'addComment', params, displayNewComment);
}

function displayNewComment(arr){
	if (arr['status']){
		$('#commentsHeading').css('display','block');
		$$('new_comment_area').innerHTML += arr['html'].replace(/\\/g,'');
		$$('txt_comment').value = '';
		if (editor)
			editor.clear();
		if (rmv = $$('message_to_remove'))
			rmv.parentNode.removeChild(rmv);
		if(UPDATE_COMMENTS)
			lastCommentDate = arr.date;
	}else alert(arr['html']);
	enable('btnSendComment');
	$$('sendCommentMessage').innerHTML = '&nbsp;';
}

function displayReplyComment(arr){
	if (arr['status']){
		$$('msg_replys_'+arr['parent']).innerHTML += arr['html'].replace(/\\/g,'');
		$$('answer_'+arr['parent']+'_comment').innerHTML = '';
		$$('answer_'+arr['parent']+'_comment').value = '';
		toggleDivAnswer(arr['parent']);
		if(UPDATE_COMMENTS)
			lastCommentDate = arr.date;
	}else alert(arr['html']);
}

function replyComment(idComment){
	if (rmv = $$('ajax_message')){
		rmv.parentNode.removeChild(rmv);
	}
	txt = $$('answer_'+idComment+'_comment').value;
	if (txt.length > 2200){
		alert('Se excedió la longitud máxima permitida del comentario. Por favor reduce el tamaño.');
		return;
	}
	params = {'item_id':ITEM_ID,'text':txt,'page':PAGE_NUM,'parent':idComment};
	ajaxRequest(CURRENT_SECTION, 'addComment', params, displayReplyComment);
}

function toggleDivAnswer(comment_id){
	var div_answer = $$('answer_'+comment_id+'_area');
	
	if(div_answer){
		div_answer.style.display=(div_answer.style.display=="none")?'block':'none';
	}
}
function showComment(comment_id){
	$$("comment_hided_" + comment_id + "_id").style.display="none";
	$$("comment_" + comment_id + "_id").style.display="block";
	if (typeof fixCommentBorders == 'function'){
		fixCommentBorders();
	}
}

function votarComment(idComment,tipo){
	ajaxRequest(CURRENT_SECTION, tipo=='mas'? 'addVoteComment': 'subVoteComment',  { 'item_id':ITEM_ID,'comment_id':idComment }, displayVoteComments);					
}

function votarCommentAdmin(idComment,tipo){
	ajaxRequest(CURRENT_SECTION, tipo=='mas'? 'addVoteComment' : 'subVoteComment',  { 'item_id':ITEM_ID,'comment_id':idComment }, displayVoteComments);					
}		

function displayVoteComments(arr){
	if (arr['status']){
		var mainComent = $('#main_comment_'+arr['id'])[0] ? '#main_comment_'+arr['id'] : '#comment_'+arr['id']+'_id';
		var voteBtnId = mainComent+' .btn_vote_'+(arr.add?'up':'down');
		
		$(voteBtnId).fadeOut('slow',function(){$(this).addClass('active').fadeIn();});
		setTimeout('removeActiveVoteButton("'+voteBtnId+'")', 5000);
		$('#votes_'+arr['id']+'_span').html(arr['votes']);
		if(!isNaN(arr['votes'])) {
			$('#votes_'+arr['id']+'_span').parent().removeClass('text').addClass('number');
		} else {
			$('#votes_'+arr['id']+'_span').parent().removeClass('number').addClass('text');
		}
		if (arr['featured']) {
			$(mainComent).addClass('featured');
		} else {
			$(mainComent).removeClass('featured');
		}
	} else {
		alert(arr['html']);
	}			
}		

function removeActiveVoteButton(voteBtnId){
	$(voteBtnId).fadeOut('slow',function(){$(this).removeClass('active').fadeIn();});
}

function moderarComment(idComment){
	ajaxRequest(CURRENT_SECTION, 'moderateComment',  { 'item_id':ITEM_ID,'comment_id':idComment }, displayModerarMessage);
}

function displayModerarMessage(arr){
	if (arr['status']){
		var voteObj = $$('votes_' +arr['id']+'_span');
		voteObj.innerHTML =arr['votes'];
		openNode("comment_hided_" + arr['id']+ "_id");
		/* closeNode("comment_" + arr['id']+ "_id"); */
	}else{
		alert(arr['html']);
	}			
}		

function deleteComment(idComment){
	if (rmv = $$('comment_to_remove')){
		rmv.parentNode.removeChild(rmv);
	}
	
	if (confirm('Realmente desea eliminar este comentario?')){
		commentObj = $$('comment_'+idComment+'_id');
		commentObj.innerHTML = '<div class="comment_deleting">Eliminando comentario. Por favor espere...</div>';
		waitFlag = true;
		ajaxRequest(CURRENT_SECTION,'deleteComment',{ 'item_id':ITEM_ID,'comment_id':idComment },displayDeletedMessage);
	}
}

function displayDeletedMessage(arr){
	if (arr['status']){
		commentObj = $$('comment_'+arr['id']+'_id');
		commentObj.innerHTML = '<div class="comment_deleted">'+arr['html']+'</div>';
		commentObj.id = 'comment_to_remove';
	}else{
		alert(arr['html']);
	}
}

if ($$('txt_comment')){
	if (editorFlag){
		var editor;
		windowOnloadAdd(function (){
			editor = new textEditor
				(
					{
						textArea_id		: 'txt_comment',
						buttons			: 'minimum'
					}
				);
			editor.start();
		});
	}
}

function sortAscendent(){
	ajaxRequest(CURRENT_SECTION, 'show_comments', '1', refreshComments);
}

function sortDescendent(){
	ajaxRequest(CURRENT_SECTION, 'show_comments', '2', refreshComments);
}

function refreshComments(html){
	$$('comments_area').innerHTML = html;
}

/* Add to my games js */

function addToMyGames(check,filter_id){
	if(check==1){
		if($$('div_add_favorites_'+filter_id))
			$$('div_add_favorites_'+filter_id).innerHTML = "<a href='javascript:removeFromMyGames(1,"+filter_id+");' class='favColWishDisabled width137 height16 block cgray f10 tright nounderline'>Quitar de tus Favoritos &nbsp;&nbsp;</a>";
	}else if(check==2){
		if($$('div_add_collection_'+filter_id))
			$$('div_add_collection_'+filter_id).innerHTML = "<a href='javascript:removeFromMyGames(2,"+filter_id+");' class='favColWishDisabled width137 height16 block cgray f10 tright nounderline'>Quitar de tu Colecci&oacute;n &nbsp;&nbsp;</a>";
		if($$('div_add_wishlist_'+filter_id))
			$$('div_add_wishlist_'+filter_id).innerHTML = "<a id='add_wishlist_"+filter_id+"' href='javascript:addToMyGames(3,"+filter_id+");' class='favColWishEnabled width137 height16 block cwhite f10 tright nounderline'>Agregar a tu Wishlist &nbsp;&nbsp;&nbsp;&nbsp;</a>";
	}else if(check==3){
		if($$('div_add_collection_'+filter_id))
			$$('div_add_collection_'+filter_id).innerHTML = "<a id='add_collection_"+filter_id+"' href='javascript:addToMyGames(2,"+filter_id+");' class='favColWishEnabled width137 height16 block cwhite f10 tright nounderline'>Agregar a tu Colecci&oacute;n &nbsp;&nbsp;</a>";	
		if($$('div_add_wishlist_'+filter_id))
			$$('div_add_wishlist_'+filter_id).innerHTML = "<a href='javascript:removeFromMyGames(3,"+filter_id+");' class='favColWishDisabled width137 height16 block cgray f10 tright nounderline'>Quitar de tu Wishlist &nbsp;&nbsp;&nbsp;&nbsp;</a>";
	}
	ajaxRequest(GAMES,'add_to_my_games',{'check':check,'filter_id':filter_id},resultAddToMyGames);
}

function resultAddToMyGames(arr){
	if(arr.status){
		// $$('msg_mygames').innerHTML=arr.html;
	}else{
		// $$('msg_mygames').innerHTML=arr.html;
	}
}	

function removeFromMyGames(check,filter_id){
	if(check==1){
		if($$('div_add_favorites_'+filter_id))
			$$('div_add_favorites_'+filter_id).innerHTML = "<a href='javascript:addToMyGames(1,"+filter_id+");' class='favColWishEnabled width137 height16 block cwhite f10 tright nounderline'>Agregar a tus Favoritos &nbsp;&nbsp;</a>";
	}else if(check==2){
		if($$('div_add_collection_'+filter_id))
			$$('div_add_collection_'+filter_id).innerHTML = "<a href='javascript:addToMyGames(2,"+filter_id+");' class='favColWishEnabled width137 height16 block cwhite f10 tright nounderline'>Agregar a tu Colecci&oacute;n &nbsp;&nbsp;</a>";
	}else if(check==3){
		if($$('div_add_wishlist_'+filter_id))
			$$('div_add_wishlist_'+filter_id).innerHTML = "<a href='javascript:addToMyGames(3,"+filter_id+");' class='favColWishEnabled width137 height16 block cwhite f10 tright nounderline'>Agregar a tu Wishlist &nbsp;&nbsp;&nbsp;&nbsp;</a>";
	}
	ajaxRequest(GAMES,'remove_from_my_games',{'check':check,'filter_id':filter_id},resultRemoveFromMyGames);
}

function resultRemoveFromMyGames(arr){
	
}

function sendFriendRequestComments(idFriend){
	tmpFriendId = idFriend;
	ajaxRequest(MEMBERS,'sendFriendRequest',idFriend,displayFriendRequestCommentsResult);
}

function displayFriendRequestCommentsResult(html){
	alert(html);
}



function remName(linkObj, idContainer){
	switch(idContainer){
			case 'search':
				if(linkObj.value=='Buscar...'){
					linkObj.value='';
					linkObj.style.color='black';
				}else if(linkObj.value==''){
					linkObj.value='Buscar...';
					linkObj.style.color='gray';
				}else{
					linkObj.value=linkObj.value;
					linkObj.style.color='black';
				}
				break;
				
			case 'email':
				if(linkObj.value=='email'){
					linkObj.value='';
					linkObj.style.color='black';
				}else if(linkObj.value==''){
					linkObj.value='email';
					linkObj.style.color='gray';
				}else{
					linkObj.value=linkObj.value;
					linkObj.style.color='black';
				}
				break;
		}		
	}
	
	function chkName(linkObj, idContainer){
		switch(idContainer){
			case 'search':
				if(linkObj.value==''){
					linkObj.value='Buscar...';
					linkObj.style.color='gray';
				}else{
					linkObj.value=linkObj.value;
				}
			break;
			case 'email':
				if(linkObj.value==''){
					linkObj.value='email';
					linkObj.style.color='gray';
				}else{
					linkObj.value=linkObj.value;
				}
			break;
		}
	}
	
	/* PUBLICIDAD */
	
	function onloadIframe(idIframe,string){
		windowOnloadAdd(function(){
			var id = setInterval(function(){
					if ($$(idIframe)){
						if($$(idIframe).contentWindow){
							if($$(idIframe).contentWindow.document){
								if($$(idIframe).contentWindow.document.body){
									if (!isBrowser.IE)
										$$(idIframe).contentWindow.document.open();
									$$(idIframe).contentWindow.document.write(string);
									if (!isBrowser.IE)
										$$(idIframe).contentWindow.document.close();
									clearInterval(id);
								}
							}
						}
					}else{
						clearInterval(id);
					}
				}
			,1);
		});
	}
	
	function leaderboard(url){
		if ($$('banner')){
			iframe = $c('iframe');
			iframe.src = url;
			iframe.style.backgroundColor = 'transparent';
			iframe.style.border = 'none';
			iframe.style.width = '100%';
			iframe.style.height = '90px';
			iframe.frameBorder = 'no';
			$$('banner').appendChild(iframe);
		}else{
			windowOnloadAdd(function(){
					iframe = $c('iframe');
					iframe.src = url;
					iframe.style.backgroundColor = 'transparent';
					iframe.style.border = 'none';
					iframe.style.width = '100%';
					iframe.style.height = '90px';
					iframe.frameBorder = 'no';
					$$('banner').appendChild(iframe);
				}
			);
		}
	}
	
	function adbox(url){
		if ($$('adbox')){
			iframe = $c('iframe');
			iframe.src = url;
			iframe.style.backgroundColor = 'transparent';
			iframe.style.border = 'none';
			iframe.style.width = '300px';
			iframe.style.height = '250px';
			iframe.frameBorder = 'no';
			$$('adbox').appendChild(iframe);
		}else{
			windowOnloadAdd(function(){
					if ($$('adbox')){
						iframe = $c('iframe');
						iframe.src = url;
						iframe.style.backgroundColor = 'transparent';
						iframe.style.border = 'none';
						iframe.style.width = '300px';
						iframe.style.height = '250px';
						iframe.frameBorder = 'no';
						$$('adbox').appendChild(iframe);
					}
				}
			);
		}
	}
	/**
	 * Objeto controlador para la caja de Enviar Mensaje Privado
	 * @author Mario de Jesus Merlos Cruz <mario.merlos@buscacorp.com>
	 */
	function PrivateMssg() {
		var This = this;
		var ToUserId = null;
		var ToNickname = null;
		var html = null;
		var pmWin = null;
		function __formEnable() {
			$('.members_privateMssg .boton').each( function() {
				$(this).removeAttr( 'disabled' );
			} );
			$('#msgSubject').removeAttr( 'disabled' );
			$('#msgBody').removeAttr( 'disabled' );
		}
		function __formDisable() {
			$('.members_privateMssg .boton').each( function() {
				$(this).attr( { 'disabled': 'disabled' } );
			} );
			$('#msgSubject').attr( { 'disabled': 'disabled' } );
			$('#msgBody').attr( { 'disabled': 'disabled' } );
		}
		function __sendMessage() {
			try {
				var subj = $.trim( $('#msgSubject').val() );
				if ( subj.length > 60 ) {
					alert('Se excedió la longitud máxima permitida del Asunto. Por favor reduce el tamaño.');
					__formEnable();
					return false;
				}
				var mssg = $.trim( $('#msgBody').val() );
				if ( mssg == '' ) {
					alert('Por favor escriba un mensaje');
					__formEnable();
					return false;
				}
				if ( mssg.length > 5000 ) {
					alert('Se excedió la longitud máxima permitida del mensaje. Por favor reduce el tamaño.');
					__formEnable();
					return false;
				}
				$('#msgStatus').html('Enviando mensaje...');
				ajaxRequest( MEMBERS,'sendMembersMessage', {
						'message':mssg, 'subject': subj, 'user': ToUserId
					}, function( obj ) {
						__formEnable();
						if (!obj.status) {
							$( '#msgStatus' ).html( obj.message );
							return;
						}
						if ( pmWin ) {
							__close();
						}
					} );
			} catch( e ) {
				cl( 'PrivateMssg > __sendMessage >> ' + e.message );
			}
		}
		/**
		 * Funcion para el boton Cancelar. Cierra la ventana y limpia el contenido.
		 */
		this._cancel = function() {
			var subj = $('#msgSubject').val();
			var mssg = $('#msgBody').val();
			if ( ( $.trim( subj ) != '' ) || ( $.trim( mssg ) != '' ) ) {
				if ( confirm( '¿Perderá la información del mensaje, esta seguro que desea cancelar?' ) ) {
					__close();
				}
			} else {
				__close();
			}
		};
		function __close() {
			pmWin.close();
			html = null;
		};
		this._send = function() {
			__formDisable();
			__sendMessage();
		};
		function __initEditor() {
			if ( $$( 'msgBody' ) ) {
				var buttons = ['b','i','u','ul','ol','url','img','video','emoticon'];
				makeEd('msgBody',{'buttons':buttons});
			}
		}
		function __getHTML() {
			try {
				if ( ( html == null ) || ( html == false ) ) {
					var container = $c('div');
					$(container)
						.addClass('members_privateMssg')
						.append('<h3>Enviar Mensaje a <span>'+ToNickname+'</span></h3>')
						.append('<label class="privateMssg_subjectL">Asunto:</label>')
						.append('<input id="msgSubject" class="privateMssg_subject bcl bcl_0_60" type="text" name="subject" maxlength="60" />')
						.append('<span>Máx. <span id="count_msgSubject">60</span> caracteres</span>')
						.append('<label class="privateMssg_txtaL">Mensaje:</label>')
						.append('<textarea id="msgBody" class="privateMssg_txta bcl bcl_0_5000"></textarea>')
						.append('<span>Máx. <span id="count_msgBody">5000</span> caracteres</span>')
						.append('<p id="msgStatus"></p>')
						.append('<input type="button" onclick="pmObj._cancel();" value="Cancelar" class="boton privateMssg_cancel" />')
						.append('<input type="button" onclick="pmObj._send();" value="Enviar Mensaje" class="boton privateMssg_send"/>');
					html = container;
				}
			} catch( e ) {
				cl( 'PrivateMssg > __getHTML >> ' + e.message );
			}
		}
		function __init() {
			try {
				__getHTML();
				if ( ( html != null ) && ( html != undefined ) ) {
					if ( $$( 'tiptip_holder') ) {
						if ( $('#tiptip_holder').css('display') == 'block' ) {
							$('#tiptip_holder').hide();
						}
					}
					pmWin = new ModalWindow({
						id: 'privateMssgWindow',
						content: html,
						width: 554,
						height: 453,
						className: 'privateMssgWindow',
						modal: true
					});
					pmWin.show();
					__initEditor();
					initializeCharLimiters();
				} else {
					alert( 'Error al crear la ventana, intente mas tarde.' );
				}
			} catch( e ) {
				cl( 'privateMssg > __init >> ' + e.message );
			}
		}
		function __checkValues( to_user_id, to_nickname ) {
			try {
				if ( isNaN( to_user_id ) || ( $.trim( to_nickname ) == '' ) ) {
					return false;
				} else {
					ToUserId = to_user_id;
					ToNickname = to_nickname;
					return true;
				}
			} catch( e ) {
				cl( 'privateMssg > __checkValues >> ' + e.message );
			}
		}
		this.getWindow = function( to_user_id, to_nickname ){
			try {
				if ( __checkValues( to_user_id, to_nickname ) ) {
					__init();
				} else {
					alert( 'Error de parametros' );
				}
			} catch( e ) {
				cl( 'privateMssg > getWindow >> ' + e.message );
			}
		};
	}
	var pmObj = null;
	function showMessageForm( to_user_id, to_nickname ){
		if ( pmObj == null ) {
			pmObj = new PrivateMssg();
		}
		pmObj.getWindow( to_user_id, to_nickname );
	}

	
/* INICIA PERMISSIONS.JS */

var Permissions = function(opt){

	var _this = this;
	this.opt = opt;
	this.id = opt.id;
	this.width = opt.width;
	this.height = opt.height;
	this.container = opt.container;
	
	this.arr = new Array();

	this.add = function(plugin,data){
				
		principal_div = $c('div');
		principal_div.activeFlag = true;
		principal_div.id = plugin;
		principal_div.style.display = 'none';
		
		for(var type in data){
			if(typeof data[type]=='object'){
				
				div = $c('div');
				div.className = 'permissionDiv'; 
				div.name = type;
				div.style.width = this.width+'px';
				div.style.height = this.height+'px';
				div.id = plugin+'_'+type;
				
				label = $c('div');
				label.className = 'permissionLabel';
				label.innerHTML = data[type].label;
				
				checkbox = $c('input');
				checkbox.type = 'checkbox';
				checkbox.name = 'access['+plugin+']['+type+']';
				checkbox.id = plugin+'_'+type+'_checkbox';
				checkbox.checked = (data[type].value==1)?true:false;
				checkbox.value = 1;
				
				$a(div,label);
				$a(div,$c('br'));
				$a(div,checkbox);
				
				$a(principal_div,div);
			}
		}
		
		$a($$(this.container),principal_div);
		
		return principal_div;
	};
	
	this.reset = function(){
		$$(this.container).innerHTML = '';
	};
	
};

/* TERMINA PERMISSIONS.JS */

/* INICIA VENTANA INVITACION */

var winInviteFriends = null;
var inviteSection = null, inviteItemId = null;
function mostrarVentanaInvitaciones(section, item_id){
	if(winInviteFriends == null){
		invite_SetupWindow();
		inviteSection = section;
		inviteItemId = item_id;
	}
	winInviteFriends.showWindow();
}

function invite_SetupWindow(){
	var html = '<div id="invite_people" class="invite_people">' +
					'<div class="img_cnt">' +
						'<img id="img_msn" src="'+TEMPLATES_URL+'images/logo_msn.jpg" onclick="invite_ShowContactForm(\'msn\')">' +
						'<img id="img_yahoo" class="brdr" src="'+TEMPLATES_URL+'images/logo_yahoo.jpg" onclick="invite_ShowContactForm(\'yahoo\')">' +
					'</div>' +
					'<div id="mailDiv">' +
						'<div id="headerMail"></div>' +
						'<div class="form_search">' + 
							'<div> Email:<span id="mail_advert"></span></div>' +
							'<input class="custom_invite_input" type="text" id="userMail" onkeyup="invite_ValidateForm();" /><br />' +
							'<div> Contrase&ntilde;a:</div>' +
							'<input class="custom_invite_input" type="password" id="memberPwd" onkeyup="invite_ValidateForm();" /><br />' +
				 			'<div id="invite_confirm" style="color:red;font-weight:bold;"></div>' +
							'<div id="cont_list"></div>' +
							'<input id="searchCont" type="button" class="boton" value="Buscar Contactos" onclick=""/>' +
							'<input id="userDomain" type="hidden"/>' +
						'</div>' +
					'</div>' +
				'</div>';
	winInviteFriends = Window('win_page',
		{
			title:			'Invitar a tus Amigos',
			width:			400,
			height:			500,
			closable:		true,
			toogle:			true,
			draggable:		true,
			disable_screen:	false,
			resizable:		false,
			container:		'window_container_invite',
			html:			html
		}
	);
	openNode('invite_people');
	closeNode('mailDiv');
	disable('searchCont');
}

function invite_ValidateForm(){
	if ((getValue('userMail')=='')||(getValue('memberPwd')==''))
		disable('searchCont');
	else
		enable('searchCont');
}

function invite_ShowContactForm(mail){
	openNode('mailDiv');
	var headerMail = (mail=='msn')?'MSN':'Yahoo';
	getObject('headerMail').innerHTML = 'Invitar a mis contactos de <b>'+headerMail+'</b>';
	getObject('searchCont').mail = mail;
	getObject('searchCont').onclick = function (){invite_SearchContacts(this.mail);};
	
	if((mail=='msn')||(mail=='outlook')){
		getObject('mail_advert').innerHTML = '';
		openNode('mail_advert');
		getObject('userDomain').value = 'msn';
		getObject('img_msn').src = TEMPLATES_URL+'/images/logo_msn.jpg';
		getObject('img_yahoo').src = TEMPLATES_URL+'/images/logo_yahoo_bw.jpg';
	}else {
		if(mail=='yahoo'){
			getObject('mail_advert').innerHTML = ' * Escriba solo el nombre de usuario';
			openNode('mail_advert');
			getObject('userDomain').value = 'yahoo';
			getObject('img_msn').src = TEMPLATES_URL+'/images/logo_msn_bw.jpg';
			getObject('img_yahoo').src = TEMPLATES_URL+'/images/logo_yahoo.jpg';
		}
	}
}

function invite_SearchContacts(mail){
	email = trim(getValue('userMail'));
	pwd = getValue('memberPwd');
	domain = getValue('userDomain');
	
	getObject('invite_confirm').innerHTML = 'Buscando contactos...';
	params = {'email':email,'password':pwd,'domain':domain};
	ajaxRequest(MEMBERS,'searchMembersContacts',params,invite_DisplayContacts);
}

function invite_DisplayContacts(contacts){
	if(contacts['anyContacts']){
		$$('cont_list').innerHTML = contacts['html'];
		$$('invite_confirm').innerHTML = '';
		closeNode('searchCont');
		openNode('cont_list');
	}else{
		$$('invite_confirm').innerHTML = 'No se encontraron contactos';
		$$('cont_list').innerHTML = '';
	}
}

function invite_DisplayInvite(message){
	$$('invite_confirm').innerHTML = message;
	openNode('searchCont');
}

function invite_SubmitForm(){
	$$('form_section').value = inviteSection;
	$$('form_item_id').value = inviteItemId;
	$$('form_user_email').value = getValue('userMail');
	$$('invite_confirm').innerHTML = 'Enviando invitaciones...';
	closeNode('cont_list');
	return true;
}

/* TERMINA VENTANA INVITACION */

function getEmbed(obj){
	var embed = '<embed width="430" height="310" flashvars="origSize=true&imagePath='+obj.image+'&videoPath='+obj.flv+'&autoStart=false';
	if (obj.subs!='')
		embed += '&amp;subs='+obj.subs;
	embed += '&amp;volAudio=40&amp;xmlFile='+obj.xml+'&amp;videoTitle='+obj.title+'&amp;embedURL='+obj.link+'&amp;embedPlayer='+EMBED_PLAYER;
	embed += '" allowscriptaccess="always" allowFullScreen="true" quality="high" name="mymovie" style="" src="'+EMBED_PLAYER+'" type="application/x-shockwave-flash" />';
	return embed;
}

function getIframe(obj2){
	var iframe = '<iframe width="100%" height="400px" frameborder="0" src="'+obj2.link2+'" style="overflow: hidden;"></iframe>';
	return iframe;
}

function cloneObject(what){
	for(i in what){
		if(typeof what[i] == 'object'){
			this[i] = new cloneObject(what[i]);
		}else this[i] = what[i];
	}
}

/* RETWEET */
function retweet(title,url,t_btn,c_btn,user_name){
	var params = { 'title':title,'url':url,'t_btn':t_btn,'c_btn':c_btn,'user_name':user_name };
	ajaxRequest(MEMBERS,'customRetweet',params,retweetDone);
}
function retweetDone(arr){
	if(arr.status){
		var t_count = $$(arr.c_btn);
		show(t_count);
		var current = parseInt(t_count.innerHTML);
		current = (isNaN(current)) ? 0 : current;
		t_count.innerHTML = current+1;
		$$(arr.t_btn).innerHTML = 'retweet';
	}
}
/* END: RETWEET */

function loadFileInHead(filename, filetype){
	if (filetype=="js"){
		var fileref=document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", filename);
	}
	else if (filetype=="css"){
		var fileref=document.createElement("link");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", filename);
	}
	if (typeof fileref!="undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref);
}

/* Devuelve las dimensiones de la pagina */
function getWindowData(){
    var widthViewport,heightViewport,xScroll,yScroll,widthTotal,heightTotal;
    if (typeof window.innerWidth != 'undefined'){
        widthViewport= window.innerWidth-17;
        heightViewport= window.innerHeight-17;
    }else if(typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth !='undefined' && document.documentElement.clientWidth != 0){
        widthViewport=document.documentElement.clientWidth;
        heightViewport=document.documentElement.clientHeight;
    }else{
        widthViewport= document.getElementsByTagName('body')[0].clientWidth;
        heightViewport=document.getElementsByTagName('body')[0].clientHeight;
    }
    xScroll=self.pageXOffset || (document.documentElement.scrollLeft+document.body.scrollLeft);
    yScroll=self.pageYOffset || (document.documentElement.scrollTop+document.body.scrollTop);
    widthTotal=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth,widthViewport);
    heightTotal=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,heightViewport);
    return [widthViewport,heightViewport,xScroll,yScroll,widthTotal,heightTotal];
}

/* EDITOR */
function pressEscHandler(evt,action,params){
	var tecla = evt.which || evt.keyCode || evt.DOM_VK_ESCAPE;
    if(tecla == 27){
    	if((typeof action != 'undefined') && (typeof params != 'undefined')){
    		try{eval(action+'('+params+')');}catch(e){};
    	}
    }
}
function getEmoticonsPanel(){
	var emoticons =
	{
		':mellow:':'mellow.gif',
		':ohmy:':'ohmy.gif',
		':wink:':'wink.gif',
		':huh:':'huh.gif',
		':laugh:':'laugh.gif',
		':smile:':'smile.gif',
		':sleep:':'sleep.gif',
		':dry:':'dry.gif',
		':hail:':'hail.gif',
		':wub:':'wub.gif',
		':mad:':'mad.gif',
		':sad:':'sad.gif',
		':blink:':'blink.gif',
		':nonono:':'nonono.gif',
		':dunce:':'dunce.gif',
		':dribble:':'dribble.gif',
		':zipped:':'zipped.gif',
		':cry:':'cry.gif',
		':ill:':'ill.gif',
		':licklips:':'licklips.gif',
		':kicking:':'kicking.gif',
		':shiny:':'shiny.gif',
		':tongue:':'tongue.gif',
		':alien:':'alien.gif',
		':bananin:':'bananin.gif',
		':bananin2:':'bananinbailarin.gif',
		':bananin3:':'bananinrulero.gif'
	};
	this.emoticons = emoticons;
	var html = '<ul>';
	var i = 1;
	for(x in emoticons) {
		html += '<li><div unselectable="on" class="emoticon"><img unselectable="on" onMouseOver="this.style.borderColor=\'gray\'" onMouseOut="this.style.borderColor=\'white\'" style="max-width:52px;max-height:32px;border: 2px solid #FFFFFF" title="'+x+'" onclick="insertEmoticon(\''+elementId+'\',\''+x+'\');" src="/js/editor/img/emoticons/'+ emoticons[x] +'" style="cursor:pointer;"></div></li>';
		if ((i)%10 == 0) {
			html += '</ul><ul>';
		}
		i++;
	}
	html += '</ul>';
	return html;
}
function putColor(colorCode,elId){
	var selText = '';
	el = $$(elId);
	if (el.setSelectionRange){
		var sTop = el.scrollTop;
		selText = el.value.substring(el.selectionStart,el.selectionEnd);
	}else{
		selText = document.selection.createRange().text;
	}
	colorCode = colorCode.replace('#','') 
	var newText = '[color='+colorCode+']'+selText+'[/color]';
	var ini = el.selectionStart;
	var textInsert = newText.length;
	if (newText != '') {
		if (el.setSelectionRange){
			el.value = el.value.substring(0,el.selectionStart) + newText + el.value.substring(el.selectionEnd,el.value.length);
			goToLineText(elId, ini, textInsert,8);
			el.scrollTop = sTop;
		}else{
			document.selection.createRange().text = newText;
			if (selText=='') {
				el.value += newText;
			}
		}
	}
	hide($$('color_palette_wrapper'));
	el.focus();
}
function insertEmoticon(elId,emotiCode){
	var selText = '';
	el = $$(elId);
	if (el.setSelectionRange){
		var sTop = el.scrollTop;
		selText = el.value.substring(el.selectionStart,el.selectionEnd);
	}else{
		selText = document.selection.createRange().text;
	}
	var ini = el.selectionStart;
	var textInsert = emotiCode.length;	
	if (emotiCode != '') {
		if (el.setSelectionRange){
			el.value = el.value.substring(0,el.selectionStart) + emotiCode + el.value.substring(el.selectionEnd,el.value.length);
			el.scrollTop = sTop;
		}else{
			document.selection.createRange().text = emotiCode;
			if (selText=='') {
				el.value += emotiCode;
			}
		}
		goToLineText(elId, ini, textInsert, 0);		
		hide($$('popup_emoticons_menu'));
		el.focus();
	}
}

function getSizesPanel(elementId){
	var sizes = new Array( '10', '12' , '17', '20' );
	html = '<table unselectable="on">';
	var i;
	for (i=0;i<sizes.length;i++) {
		html += '  <tr unselectable="on">';
		html += '   <td unselectable="on" style="text-align:center;"><div id="size'+i+'" onClick="insertSize(\''+elementId+'\', \''+sizes[i]+'\');" onMouseOut="$$(\'size'+i+'\').style.border = \'1px solid transparent\';" onMouseOver="$$(\'size'+i+'\').style.border = \'1px solid #000000\';" class="bgwhite fcgray2 fbold f12" style="width:23px;border:1px solid transparent;">'+sizes[i]+'</div></td>';
		html += '  </tr>';
	}
	html += '</table>';
	return html;
}
function insertSize(elId,size){
	var selText = '';
	el = $$(elId);
	if (el.setSelectionRange){
		var sTop = el.scrollTop;
		selText = el.value.substring(el.selectionStart,el.selectionEnd);
	}else{
		selText = document.selection.createRange().text;
	}
	var newText = '[size='+size+']'+selText+'[/size]';
	var ini = el.selectionStart;
	var textInsert = newText.length;
	if (size != '') {
		if (el.setSelectionRange){
			el.value = el.value.substring(0,el.selectionStart) + newText + el.value.substring(el.selectionEnd,el.value.length);
			el.scrollTop = sTop;
		}else{
			document.selection.createRange().text = newText;
			if (selText=='') {
				el.value += newText;
			}
		}
		goToLineText(elId, ini, textInsert, 7);			
		hide($$('popup_sizes_menu'));
		el.focus();
	}
}
var elementId = '';
function Galleries() {
	var cache = {};
	var urlAjaxGalleries = '/index.php?seccion=galerias&accion=getGalleriesByUser&ajax_request=1';
	var urlAjaxGallery = '/index.php?seccion=galerias&accion=getGalleryById&ajax_request=1';
	var el;
	var gallery = false;
	var gallery_container = jQuery('<div id="galleriesContainer" />');
	var limitGalleries = 4;
	var limitPictures = 5;
	var actGallery = null;
	var titles = {};
	this.constructor.pages = {};
	this.constructor.pagesGallery = {};
	this.constructor.divs = {};
	this.constructor.admin = 0;
	this.constructor.totalPics = {};
	this.constructor.total = {};
	function createDivGallery(gallery_id, src, name) {
		if($('.title_picture_item')){
			$('.title_picture_item').remove();
		}		
		var newDiv = jQuery('<div id="gallery_' + gallery_id + '" class="gallery_item galleriesBack"/>');
		var interDiv = jQuery('<div class="gallery_item_inter" style="height: 68px;overflow: hidden;" />');
		var link = jQuery('<a />');
		link.css({
			cursor : 'pointer'
		});
		link.click(function(evt) {
			evt.preventDefault();
			Galleries.pagesGallery [gallery_id] = 1;
			loadGallery(gallery_id);
		});
		link.html('<img src="' + src + '" title="Da click aquí para abrir esta galería" style = "margin: 0;"/>');
		newDiv.html(interDiv.html(link));
		newDiv.append('<span style="display: block;padding-top: 12px;">' + name + '</span>');
		return newDiv;
	}
	function createDivPictures(picture_id, src) {
		var newDiv = jQuery('<div id="picture_' + picture_id + '" class="picture_item" style="margin: 5px 1px;overflow:hidden;border: 4px solid transparent;width: 80px;height: 68px;" />');
		var link = jQuery('<img src="' + src + '" title="Da click aquí para agregar esta imagen" style="height: auto;margin:0;" />');
		link.css({
			cursor : 'pointer'
		});
		link.click(function(evt) {
			evt.preventDefault();
			if($('.select_img_item'))
				$('.select_img_item').removeClass('select_img_item');
			newDiv.addClass('select_img_item');
			$('#galleriesContainer').height('170px');
			if($('.title_picture_item')){
				$('.title_picture_item').remove();
			}
			var newDivTitle = jQuery('<div id="title_picture_' + picture_id + '" class="title_picture_item"/>');
			var inputTitle = jQuery('<input id="input_title_' + picture_id + '" class="title_title_item clickOff" type = "text" value = "Editar pie de foto ..." onfocus = "activaEditTitle(' + picture_id + ',2);" onblur = "activaEditTitle(' + picture_id + ',1);"/>');
			var inputSend = jQuery('<input id="input_send_' + picture_id + '" class="boton boton_insert_title" type = "buttom" value = "Insertar" title = "Insertar Imagen"/>');
			gallery_container.append(newDivTitle.html(inputTitle));
			gallery_container.append(newDivTitle.append(inputSend));
			$$('input_send_'+picture_id).onclick = function (){
				var title = $$('input_title_' + picture_id).value;
				if( title == 'Editar pie de foto ...')
					title = '';
				edTag(el, 'addPicture', link.attr('src').replace('_thumb',''), title);
				$$('input_title_' + picture_id).value = '';
			};
		});
		newDiv.html(link);
		return newDiv;
	}
	function loadGallery(gallery_id) {
		Galleries.divs[el.id].fadeTo('fast', .4);
		actGallery = gallery_id;
		jQuery('#titleGalleries').html('<span> &#62; </span>' + titles[gallery_id]);
		jQuery('#titleGalleries').fadeIn();
		jQuery('#msg').html('Selecciona una imagen para insertarla.');
		jQuery.post(urlAjaxGallery, {
			page : Galleries.pagesGallery[gallery_id],
			gallery_id : gallery_id,
			admin : Galleries.admin
		}, function(json) {
			_(json);
		});
		function _(json) {
			Galleries.divs[el.id].fadeTo('fast', 1);
			gallery = false;
			Galleries.divs[el.id].html('');
			var total = 0;
			for (i in json) {
				Galleries.divs[el.id].append(createDivPictures(json[i].id, json[i].src));
				++total;
			}
			Galleries.totalPics[el.id] = total;
		}
	}
	function _loadGalleries() {
		actGallery = null;
		Galleries.divs[el.id].fadeTo('fast', .4);
		Galleries.divs[el.id].css({marginLeft: '24px'});
		if (!cache[urlAjaxGalleries + Galleries.pages[el.id]]) {
			jQuery.post(urlAjaxGalleries, {
				page : Galleries.pages[el.id],
				admin : Galleries.admin
			}, function(json) {
				_(json);
				cache[urlAjaxGalleries + Galleries.pages[el.id]] = json;
			});
		} else {
			_(cache[urlAjaxGalleries + Galleries.pages[el.id]]);
		}
		function _(json) {
			Galleries.divs[el.id].fadeTo('fast', 1);
			jQuery('#titleGalleries').fadeOut();
			jQuery('#msg').html('Selecciona un álbum para continuar');
			gallery = true;
			Galleries.divs[el.id].html('');
			Galleries.total[el.id] = json.total;
			for (i in json.items) {
				Galleries.divs[el.id].append(createDivGallery(json.items[i].id, json.items[i].src, json.items [i].title));
				if (!titles[json.items[i].id]) {
					titles[json.items[i].id] = json.items [i].title;
				}
			}
		}
	}
	function _back() {
		var url,page;
		if (gallery == true) {
			url = urlAjaxGalleries;
			if (Galleries.pages[el.id] - 1 < 1) {
				return false;
			}
			--Galleries.pages[el.id];
			_loadGalleries();
		} else {
			url = urlAjaxGallery;
			if (Galleries.pagesGallery [actGallery] - 1 < 1) {
				return false;
			}
			if (actGallery) {
				--Galleries.pagesGallery [actGallery];
				Galleries.divs[el.id].animate({marginLeft : (parseInt(Galleries.divs[el.id].css('marginLeft')) + 450) + 'px'});
			}
		}
	}
	function _next() {
		if (gallery == true) {
			url = urlAjaxGalleries;
			if (Galleries.pages[el.id] + 1 > Math.ceil(Galleries.total [el.id] / limitGalleries)) {
				return false;
			}
			++Galleries.pages[el.id];
			_loadGalleries();
		} else {
			url = urlAjaxGallery;
			if (Galleries.pagesGallery [actGallery] + 1 > Math.ceil(Galleries.totalPics [el.id] / limitPictures)) {
				return false;
			}
			if (actGallery) {
				++Galleries.pagesGallery [actGallery];
				Galleries.divs[el.id].animate({marginLeft : (parseInt(Galleries.divs[el.id].css('marginLeft')) - 450) + 'px'});
			}
		}
	}
	this.init = function(ele) {
		if($$('imgUploadContainer')){
			$$('imgUploadContainer').style.display = 'none';
			$('#imgUploadContainer').slideUp('fast');
		}			
		el = ele;
		// cl(Galleries.divs);
		if (!Galleries.divs[el.id]) {
			Galleries.pages[el.id] = 1;
			Galleries.divs[el.id] = jQuery('<div id="galleriesFor' + el.id + '"  class="galleriesForUser"></div>');

			gallery_container.toggle('fast');
			var back = jQuery('<a id="backGalleries">&laquo;<span></span></a>'); back.css({position: 'absolute', cursor : 'pointer', left : 0});
			var next = jQuery('<a id="nextGalleries">&raquo;<span></span</a>'); next.css({position: 'absolute', cursor : 'pointer', right : 0});
			back.click(function(e) {
				e.preventDefault();
				_back();
			});
			next.click(function(e) {
				e.preventDefault();
				_next();
			});
			gallery_container.append(back);
			gallery_container.append('<h3 id="galleriesLink">Mis álbumes</h3><h5 id="titleGalleries" style="display: none;"></h5>');
			gallery_container.append ('<h4 id="msg"></h4>');
			gallery_container.append(Galleries.divs[el.id]);
			gallery_container.append(next);
			jQuery(gallery_container).insertBefore(el);
			_loadGalleries();
			jQuery('#galleriesLink').click(function(e){
				//GalleriesObj.init(el);
				gallery_container.height('135px');
				_loadGalleries();
			});
		} else {
			if (Galleries.divs[el.id].is(':visible')) {
				Galleries.divs[el.id].html('');
				/*if (gallery == false) {
					_loadGalleries();
				} else {*/
					gallery_container.height('135px');
					gallery_container.toggle('fast');
				//}
			} else {
				gallery_container.toggle('fast');
				_loadGalleries();
			}
		}
	};
}


function ImgUpload() {
	var el;
	var img_container = jQuery('<div id="imgUploadContainer" />');
	this.constructor.divs = {};
	this.init = function(ele) {
		if($('#galleriesContainer')){
			$('#galleriesContainer').slideUp('fast');
		}
		el = ele;
		img_container.height('90px');
		if (!ImgUpload.divs[el.id]) {
			ImgUpload.divs[el.id] = jQuery('<div id="ImgUploadFor' + el.id + '"  class="selectImgUploadForUser"></div>');
			img_container.toggle('fast');
			var divCont = $c('div');
			divCont.className = 'contImgImputUp';
			
			var forCont = $c('form');
			forCont.method = 'post';
			forCont.enctype = 'multipart/form-data';
			forCont.target = 'iframeImgUpload';
			forCont.id = 'formImgUpload';
			forCont.action = DOMAIN+GALLERY+'/img_upload/';
			
			var inputFileUp = $c('input');
			inputFileUp.type = 'file';
			inputFileUp.id = 'imgImputUp';
			inputFileUp.name = 'imginput_upload';
			forCont.appendChild (inputFileUp);
			
			var inputDomainUp = $c('input');
			inputDomainUp.name = 'domain_referer';
			inputDomainUp.value = DOMAIN_NAME;
			inputDomainUp.type = 'hidden';
			forCont.appendChild (inputDomainUp);
			
			var inputContentImgUp = $c('input');
			inputContentImgUp.name = 'name_content_img';
			inputContentImgUp.value = el.id;
			inputContentImgUp.type = 'hidden';
			forCont.appendChild (inputContentImgUp);			
		
			var inputIframeRequestUp = $c('input');
			inputIframeRequestUp.name = 'iframe_request';
			inputIframeRequestUp.value = 1;
			inputIframeRequestUp.type = 'hidden';
			forCont.appendChild (inputIframeRequestUp);
					
			var botonSubmitUp = $c('a');
			botonSubmitUp.className = 'boton';
			botonSubmitUp.id = 'imgButtonUp';
			botonSubmitUp.innerHTML = 'Subir Imagen';
			forCont.appendChild (botonSubmitUp);
			
			var contentImgUp = $c('div');
			contentImgUp.style.display = 'none';	
			contentImgUp.id = 'contentImgUp';	
			var imgLodingUp = $c('img');
			imgLodingUp.id = 'imgLodingUp';
			imgLodingUp.src = DOMAIN+'app/templates/default/images/loading.gif';
			imgLodingUp.style.marginTop = '30px';
			
			var spanLodingUp = $c('span');
			spanLodingUp.style.marginTop = '7px';
			spanLodingUp.id = 'spanLodingUp';
			spanLodingUp.style.fontStyle = 'italic';
			spanLodingUp.style.marginLeft = '15px';
			spanLodingUp.style.display = 'block';
			spanLodingUp.innerHTML = 'Subiendo imagen ...';
			contentImgUp.appendChild(imgLodingUp);
			contentImgUp.appendChild(spanLodingUp);			
			
			img_container.append ('<iframe name="iframeImgUpload" style="display:none;"></iframe>');
			divCont.appendChild(forCont);
			
			img_container.append(divCont);
			img_container.append(contentImgUp);
			jQuery(img_container).insertBefore(el);
			try {
				$('#imgImputUp').change( function(event) {
					$$('formImgUpload').submit();
					$('.contImgImputUp').fadeOut('fast', function (){
						$('#contentImgUp').fadeIn('fast');
					});
				});
			} catch(e) {
				cl('byAjax._setEvent >> '+e.message);
			}
		} else {
			if (ImgUpload.divs[el.id].is(':visible')) {
					img_container.height('300px');
					img_container.toggle('fast');
			} else {
				img_container.toggle('fast');
			}
		}
	};
}
function uploadImgComplete(obj){
	var imgContAll = $c('div');
	imgContAll.className = 'contentUploadComp';
	imgContAll.id = 'contentUploadComp';
	
	var divCont = $c('div');
	var imgA = $c('img');
	imgA.src = obj.file_small;
	imgA.title = 'Foto a insertar';
	divCont.appendChild (imgA);
	divCont.style.height= '70px';
	divCont.style.width= '90px';
	divCont.style.display= 'inline-block';
	divCont.style.overflow= 'hidden';
	divCont.style.margin= '10px';
	
	
	var divContRigth = $c('div');
	var inputImg = $c('input');
	inputImg.type = 'text';
	inputImg.id = 'insertInCont';
	inputImg.style.width= '345px';
	inputImg.style.display= 'block';
	inputImg.style.marginBottom= '10px';
	inputImg.value = 'Editar pie de foto ...';
	inputImg.style.color =  '#DBDBDB';
	inputImg.style.fontStyle = 'italic';		
	
	inputImg.onfocus = function (){
		inputImg.value = '';
		inputImg.style.color =  '';
		inputImg.style.fontStyle = 'normal';		
	}
	inputImg.onblur = function (){
		if(inputImg.value == 'Editar pie de foto ...' || inputImg.value == ''){
			inputImg.value = 'Editar pie de foto ...';
			inputImg.style.color =  '#DBDBDB';
			inputImg.style.fontStyle = 'italic';		
		}
	}
	
	var spanSend = $c('span');
	spanSend.className = 'boton';
	spanSend.id = 'spanInsCont';
	spanSend.innerHTML = 'Insertar';
	
	spanSend.onclick = function(){
		var paramsImg = {
				'url': obj.file_medium, 
				'title': inputImg.value
		}
		edTag($$(obj.name_content_img),'img',paramsImg);
		$('#contentUploadComp').remove();
		$('.contImgImputUp').fadeIn('normal');
	}
	
	var cancelSend = $c('span');
	cancelSend.className = 'boton';
	cancelSend.id = 'cancelCont';
	cancelSend.innerHTML = 'Cancelar';
	cancelSend.style.marginLeft= '210px';
	cancelSend.style.display= 'inline-block';
	cancelSend.style.marginRight= '15px';
	
	cancelSend.onclick = function(){
		$('#contentUploadComp').remove();
		$('.contImgImputUp').fadeIn('fast');
	}	
	divContRigth.appendChild (inputImg);
	divContRigth.appendChild (cancelSend);
	divContRigth.appendChild (spanSend);
	
	divContRigth.style.display= 'inline-block';
	divContRigth.style.width= '362px';
	divContRigth.style.marginTop= '10px';
	divContRigth.style.verticalAlign= 'top';	
	
	imgContAll.appendChild(divCont);
	imgContAll.appendChild(divContRigth);
	$('#contentImgUp').fadeOut('fast', function (){
		$$('imgUploadContainer').appendChild (imgContAll);
	});
}
function edTag(el, tag, param){
	el.focus();
	var title = arguments[3] || '';
	var flagHere = true;
	var cant = 0;
	var selText = '';
	var newText = '';
	if (el.setSelectionRange){
		var sTop = el.scrollTop;
		selText = el.value.substring(el.selectionStart,el.selectionEnd);
	}else{
		selText = document.selection.createRange().text;
	}
	switch(tag){
		case 'addPicture':
			if(param) {
				if (title!= '')
					title = 'title="'+title+'"';
				else
					title = '';
				newText = '[img '+title+']' + param + '[/img]';
			}
		break;
		case 'uploadImg':
			if($('#'+el.id).height() == 270)
				$('#'+el.id).animate({height: '222px'});
			else
				$('#'+el.id).animate({height: '270px'});
			ImgUploadObj.init(el);
			return false;
			break;		
		case 'galleries':
			if($('#'+el.id).height() == 270)
				$('#'+el.id).animate({height: '222px'});
			else
				$('#'+el.id).animate({height: '270px'});
			GalleriesObj.init(el);
			return false;
			break;
		case 'video':
		case 'youtube':
			if(typeof param != 'undefined' && param!='') {
				var url = param;
				if(url != null){
					newText = '['+tag+']'+url+'[/'+tag+']';
				}
			} else {
				if (selText!=''){
					if(selText.substring(0,7)=='http://'){
						newText = '['+tag+']'+selText+'[/'+tag+']';
					}else{
						var url = prompt('Ingrese el URL', 'Ingrese el URL');
						if(url != null){
							newText = selText+' ['+tag+']'+url+'[/'+tag+']';
						}
					}
				}else{
					var url = prompt('Ingrese el URL', 'Ingrese el URL');
					if(url != null){
						newText = '['+tag+']'+url+'[/'+tag+']';
					}
				}
			}
			break;
		case 'url':
			if (selText!=''){
				if(selText.substring(0,7)=='http://'){
					newText = '[url='+selText+']'+selText+'[/url]';
				}else{
					var url = prompt('Ingrese el URL', 'Ingrese el URL');
					if(url != null){
						newText = '[url='+url+']'+selText+'[/url]';
					}
				}
			}else{
				var url = prompt('Ingrese el URL', 'Ingrese el URL');
				if(url != null){
					newText = '[url='+url+']'+url+'[/url]';
				}
			}
			cant = 6;
			break;
		case 'img':
			if(param!=null) {
				var url = param['url'];
				if(param['title'] == 'Editar pie de foto ...'){
					param['title'] = '';
				}				
				var title = trim(param['title']);
				if ((url != null) && (title != '')) {
					newText = '\n['+tag+' title="'+param['title']+'"]'+url+'[/'+tag+']\n';
				} else if (url != null) {
					newText = '\n['+tag+']'+url+'[/'+tag+']\n';
				}
			} else {
				if (selText!=''){
					if(selText.substring(0,7)=='http://' || selText.substring(0,8)=='https://' || selText.substring(0,6)=='ftp://'){
						newText = '[img]'+selText+'[/img]';
					}else{
						var url = prompt('Ingrese el URL', 'Ingrese el URL');
						if(url != null){
							newText = selText+' [img]'+url+'[/img]';
						}
					}
				}else{
					var url = prompt('Ingrese el URL', 'Ingrese el URL');
					if(url != null){
						newText = '[img]'+url+'[/img]';
					}
				}
			}
			break;
		case 'min':
			var tAreaSc = document.getElementById(elementId);
			var tAreaMax = document.getElementById('txtAreaMax');
			tAreaSc.innerHTML = '';
			tAreaSc.value = '';
			tAreaSc.value = tAreaMax.value;
			tAreaSc.innerHTML = tAreaMax.value;
			var content = document.getElementById ('containerMax');
			document.body.removeChild(content);
			elementId = (typeof(content) == 'undefined') ? '' : elementId;
			document.body.style.overflow = 'auto';
		break;
		case 'max':
			elementId = el.id;
			var gWinData = getWindowData();
			var widthForTArea = gWinData[0]-14;
			var heightForTArea = gWinData[1]-35;
			if (document.documentMode) { widthForTArea-=17; heightForTArea-=17; };
			
			var tAreaMax = document.createElement('textarea');
			tAreaMax.id = 'txtAreaMax';
			tAreaMax.style.marginTop = '0px';
			tAreaMax.style.marginLeft = '0px';
			tAreaMax.style.padding = '3px';
			tAreaMax.style.border = '1px inset white';
			tAreaMax.style.width = widthForTArea+'px';
			tAreaMax.style.height = heightForTArea+'px';
			tAreaMax.innerHTML = el.value;
			
			var container = document.createElement('div');
			container.id = 'containerMax';
			container.style.position = 'fixed';
			container.style.top = '0px';
			container.style.left = '0px';
			container.style.bottom = '0px';
			container.style.padding = '10px 12px';
			container.style.width = gWinData[0]+'px';
			container.style.height = gWinData[1]+'px';
			container.style.backgroundColor = '#DEDEDE';
			container.style.textAlign = 'left';
			container.appendChild(tAreaMax);
			
			var buttonsMax = $('#buttons_editor_'+el.id).attr('value').split(',');
			buttonsMax[$.inArray('max', buttonsMax)] = 'min';
			
			var control = document.getElementById('containerMax');
			if (control!=null)
				document.body.removeChild(control);
			
			document.body.appendChild(container);
			makeEd(tAreaMax.id,{'buttons':buttonsMax},true);
			document.body.style.overflow = 'hidden';
			
			var actionEsc = 'edTag';
			var paramsEsc = 'document.getElementById(\'txtAreaMax\'),\'min\'';
			addEvent (document, 'keydown', function(e) { pressEscHandler(e, actionEsc, paramsEsc); });
			addEvent (window, 'resize', function(e){ resizeElement(e, 'containerMax', 'txtAreaMax'); });
		break;
		case 'color':
			if ($$('color_palette_wrapper')){
				if($$('color_palette_wrapper').style.display == 'none'){
					$$('color_palette_wrapper').style.display = 'block';
				} else {
					$$('color_palette_wrapper').style.display = 'none';
				}
			}			
			setTimeout(function (){
					if($$('color_palette_wrapper').style.display != 'none'){
						$('html').click(function(e){
							if (! $(e.target).is('#color'))
								$$('color_palette_wrapper').style.display = 'none';
						});	
					}
			 }, 1000);			
			return;
		break;
		case 'size':
			if ($$('popup_sizes_menu')){
				if($$('popup_sizes_menu').style.display == 'none'){
					$$('popup_sizes_menu').style.display = 'block';
				}else {
					$$('popup_sizes_menu').style.display = 'none';
				}
			}
			setTimeout(function (){
				if($$('popup_sizes_menu').style.display != 'none'){
					$('html').click(function(e){
						if (! $(e.target).is('#size'))
							$$('popup_sizes_menu').style.display = 'none';
					});	
				}
			}, 500);			
			return;
			break;
		case 'emoticon':
			if ($$('popup_emoticons_menu')){
				if($$('popup_emoticons_menu').style.display == 'none'){
					$$('popup_emoticons_menu').style.display = 'block';
					if($$('popup_emoticons_menu').style.display != 'none'){
						$('html').click(function(e){
							if (! $(e.target).is('#emoticons'))
								$$('popup_emoticons_menu').style.display = 'none';
						});						
					}					
					return;
				} else {
					$$('popup_emoticons_menu').style.display = 'none';
					return;
				}
			}
			setTimeout(function (){
					if($$('popup_emoticons_menu').style.display != 'none'){
						$('html').click(function(e){
							if (! $(e.target).is('#emoticons, #popup_emoticons_menu *'))
								$$('popup_emoticons_menu').style.display = 'none';
						});	
					}
			 }, 1000);		
			elementId = el.id;
			var emoticPanel = this.getEmoticonsPanel();
			var newNode = document.createElement('div');
			newNode.id = 'popup_emoticons_menu';
			newNode.unselectable = 'on';
			newNode.className = 'popup-emoticons';
			//newNode.style.marginLeft = ($$('emoticons').offsetLeft - 5) + 'px';
			newNode.innerHTML = emoticPanel;
			insertAfter(newNode, $$('emoticons'));
			break;
		case 'ul':
			newText = selText.replace(/^\n+|\n+$/g,'');
			newText = newText.replace(/\n/g, '[/li][li]') ;
			newText = newText.replace(/(\[li\]\[\/li\])/g, '') ;
			newText = '[ul][li]'+newText;
			newText = newText+'[/li][/ul]';
			cant = 10;
			break;
		case 'ol':
			newText = selText.replace(/^\n+|\n+$/g,'');
			newText = newText.replace(/\n/g, '[/li][li]') ;
			newText = newText.replace(/(\[li\]\[\/li\])/g, '') ;
			newText = '[ol][li]'+newText;
			newText = newText+'[/li][/ol]';
			cant = 10;
			// newText = newText.replace(/(\]\[)/g, ']\n[');
			break;
		case 'sidebar':
			newText = '[sidebar][header][/header]'+selText+'[/sidebar]';
			var ini = el.selectionStart;
			var textInsert = newText.length;
			cant = 10;	
			break;
		case 'juego':
			if (selText!=''){
				newText = '[juego]'+selText+'[/juego]';
			} else {
				var juego = prompt('Ingrese el nombre del juego', 'Ingrese el nombre del juego');
				if(juego != null){
					newText = '[juego]'+juego+'[/juego]';
				}
			}
			break;
		default:
			cant = '[/'+tag+']';
			cant = cant.length;
			if (param){
				newText = '['+tag+'='+param+']'+selText+'[/'+tag+']';
			}else{
				newText = '['+tag+']'+selText+'[/'+tag+']';
			}
			break;
	}
	var ini = el.selectionStart;
	var textInsert = newText.length;
	if (newText != '') {
		if (el.setSelectionRange){
			el.value = el.value.substring(0,el.selectionStart) + newText + el.value.substring(el.selectionEnd,el.value.length);
			el.scrollTop = sTop;
		}else{
			document.selection.createRange().text = newText;
			if (selText=='') {
				el.value += newText;
			}
		}
	}
	// el.focus();
	if (el.setSelectionRange) {
		// el.focus();
		el.setSelectionRange((el.selectionStart + newText.length ), (el.selectionStart + newText.length));
	} else if (el.createTextRange) {
		var range = el.createTextRange();
		range.collapse(true);
		range.move('character', (el.selectionStart + newText.length));
		range.select();
	}
	if(flagHere)
		goToLineText(el.id, ini, textInsert, cant);		
	el.focus();
	return false;
}
function makeEd(name,settings,noCss){
	if($$('editor_'+name)) { return; }
	var editor = $$(name);
	var ul = $c('ul');
	ul.id = 'editor_'+name;
	if (!noCss){
		var css = $c('style');
		css.type = 'text/css';
		var styles = '.edHdr { height: 24px; margin: 0; padding: 0; list-style: none; }';
		styles += '.edHdr a, .edHdr a:link { float: left; margin: 3px 3px 3px 0px; outline: none; background-image: url(/libs/templates/images/iconos.png); width: 26px; height: 24px; background-repeat: no-repeat;}';
	}
	ul.className = 'edHdr';
	ul.innerHTML = '';
	if (typeof settings != 'undefined'){
		if(settings.buttons){
			for (tag in settings.buttons){
				switch(settings.buttons[tag]){
					case '|':
						if (!noCss) styles += '.edHdr .edSep { float: left; width: 1px; height: 24px; margin-right:2px; margin-top:3px;}';
						ul.innerHTML += '<li><div class="edSep"></div></li>';
						break;
					case 'b':
						if (!noCss) {
							styles += '.edHdr a.edB { background-position: 0 0; }';
							styles += '.edHdr a.edB:active { background-position: 0 -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'b\');return false;" class="edB" title="Bold"></a></li>';
						break;
					case 'i':
						if (!noCss) {
							styles += '.edHdr a.edI { background-position: -28px 0; }';
							styles += '.edHdr a.edI:active { background-position: -28px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'i\');return false;" class="edI" title="Italic"></a></li>';
						break;
					case 'u':
						if (!noCss) {
							styles += '.edHdr a.edU { background-position: -56px 0; }';
							styles += '.edHdr a.edU:active { background-position: -56px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'u\');return false;" class="edU" title="Underline"></a></li>';
						break;
					case 'center':
						if (!noCss) {
							styles += '.edHdr a.edC { background-position: -169px 0; }';
							styles += '.edHdr a.edC:active { background-position: -169px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'center\');return false;" class="edC" title="Texto centrado"></a></li>';
						break;
					case 'youtube':
						if (!noCss) {
							styles += '.edHdr a.edYT { background-image: url(/libs/templates/images/bbcodes.png); background-position: 0 -80px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'youtube\');return false;" class="edYT" title="Video de Youtube"></a></li>';
						break;
					case 'video':
						if (!noCss) {
							styles += '.edHdr a.edLU { background-position: -364px 0; }';
							styles += '.edHdr a.edLU:active { background-position: -364px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'video\');return false;" class="edLU" title="Video"></a></li>';
						break;
					case 'img':
						if (!noCss) {
							styles += '.edHdr a.edIMG { background-position: -499px 0; }';
							styles += '.edHdr a.edIMG:active { background-position: -499px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'img\');return false;" class="edIMG" title="Agregar una imagen desde una url"></a></li>';
						break;
					case 'url':
						if (!noCss) {
							styles += '.edHdr a.edURL { background-position: -308px 0; }';
							styles += '.edHdr a.edURL:active { background-position: -308px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'url\');return false;" class="edURL" title="Insertar URL"></a></li>';
						break;
					case 'juego':
						if (!noCss) {
							styles += '.edHdr a.edGame {background-color:#EFEFEF;background-image: url(/libs/templates/images/bbcodes.png); background-position: 5px -236px;' +
							'border:1px solid #B5B5B5;height:22px;border-radius:3px;-moz-border-radius:3px;}' +
							'.edHdr a.edGame:active {background-color:#CECECE;border-color:#8C8C8C;}';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'juego\');return false;" class="edGame" title="Insertar Enlace a Juego"></a></li>';
						break;
					case 'min':
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'min\');return false;" class="edMin" title="Minimizar Editor"></a></li>';
						break;
					case 'max':
						if (!noCss) styles += '.edHdr a.edMax, .edHdr a.edMin {background-color:#EFEFEF;background-image: url(/libs/templates/images/bbcodes.png);' +
						'border:1px solid #b5b5b5;height:22px;width:24px;border-radius:3px;-moz-border-radius:3px;}' +
						'.edHdr a.edMax {  background-position: 4px -269px; }' +
						'.edHdr a.edMin {  background-position: 4px -254px; }' +
						'.edHdr a.edMax:active, .edHdr a.edMin:active {background-color:#CECECE;border-color:#8C8C8C;}';
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'max\');return false;" class="edMax" title="Maximizar Editor"></a></li>';
						break;
					case 'color':
						var htmlA = '<li>'+
						'<div id="color" onclick="edTag($$(\''+name+'\'),\'color\');" class="color_picker" title="Insertar Color"></div>';
						var domain = window.location;
						var protocol = domain.protocol;
						var host = isBrowser.IE || isBrowser.SF ? domain.host : domain.hostname;
						var pathname = domain.pathname;
						var URL = protocol + '//' + host + pathname;
						if (!/js\/editor\//.test(URL))
							URL = DOMAIN + 'js/editor/';
						this.URL = URL;
						var imagesPath = URL + 'img/';			
						var primary_colors = [ '#000000', '#A0522D', '#556B2F', '#006400', '#483D8B', '#000080', '#4B0082', '#2F4F4F', '#8B0000', '#FF8C00', '#808000', '#008000', '#008080', '#0000FF', '#708090',
								'#696969', '#FF0000', '#F4A460', '#9ACD32', '#2E8B57', '#48D1CC', '#4169E1', '#800080', '#808080', '#FF00FF', '#FFA500', '#FFFF00', '#00FF00', '#00FFFF', '#00BFFF', '#9932CC', '#C0C0C0',
								'#FFC0CB', '#F5DEB3', '#FFFACD', '#98FB98', '#AFEEEE', '#ADD8E6', '#DDA0DD', '#FFFFFF' ];
						htmlA = htmlA +  '<div id = "color_palette_wrapper" unselectable="on" class = "forecolor_editor" style="margin-left: 275px;margin-top: 27px;position: absolute;display:none;">';
						var html = '<table unselectable="on" id="color_palette' + '"cellspacing="0" cellpadding="0" border="0"><tbody>';
						var count = 0;
						for ( var i = 0; i < 5; i++) {
							html += '<tr>';
							for ( var j = 0; j < 8; j++) {
								html += '<td unselectable="on" class="cell_forecolor_editor">' + '<div onClick="putColor(\''+primary_colors[count]+'\',\''+name+'\')" unselectable="on" style="background-color:' + primary_colors[count]
										+ ';height: 15px; width: 10px; cursor:pointer;" ><img width="7" height="15" src="' + imagesPath + 'transparentpixel.gif" unselectable="on" />&nbsp;</div>' + '</td>';
								count++;
							}
							html += '</tr>';
						}
						html += '</tbody></table>';
						htmlA = htmlA + html;
						htmlA =htmlA + '</div>';
						htmlA= htmlA + '</li>';
						ul.innerHTML += htmlA;
						break;
					case 'emoticon':
						if (!noCss) {
							styles += '.edHdr div.edEmotic { float: left; margin: 3px 3px 3px 0px; outline: none; background-image: url(/libs/templates/images/iconos.png); height: 24px; background-repeat: no-repeat; background-position: -393px 0; width:39px; }';
						}
						ul.innerHTML += '<li><div id="emoticons" onclick="edTag($$(\''+name+'\'),\'emoticon\');return false;" class="edEmotic" title="Insertar Emoticon"></div></li>';
						break;
					case 'size':
						if (!noCss) {
							styles += '.edHdr div.edSize { float: left; margin: 3px 3px 3px 0px; outline: none; background-image: url(/libs/templates/images/iconos.png); height: 24px; background-repeat: no-repeat; background-position: -225px 0; width:39px; }';
						}
						var htmlA = '<li>'+
											'<div id="size" onclick="edTag($$(\''+name+'\'),\'size\');return false;" class="edSize" title="Tamaño de letra"></div>';
						var sizePanel = this.getSizesPanel(name);
						htmlA += '<div id = "popup_sizes_menu" unselectable="on" class = "popup-sizes" style = "margin-left:233px;border:1px solid #DBDCE0;display: none;">';
						htmlA +=sizePanel;
						htmlA += '</div>';
						htmlA += '</li>';
						ul.innerHTML += htmlA;
						cant = 7;
						break;
					case 'ul':
						if (!noCss) {
							styles += '.edHdr a.edUL { background-position: -84px 0; }';
							styles += '.edHdr a.edUL:active { background-position: -84px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'ul\');return false;" class="edUL" title="Viñetas"></a></li>';
						break;
					case 'ol':
						if (!noCss) {
							styles += '.edHdr a.edOL { background-position: -112px 0; }';
							styles += '.edHdr a.edOL:active { background-position: -112px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'ol\');return false;" class="edOL" title="Numeración"></a></li>';
						break;
					case 'left':
						if (!noCss) {
							styles += '.edHdr a.edL { background-position: -141px 0; }';
							styles += '.edHdr a.edL:active { background-position: -141px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'left\');return false;" class="edL" title="Alineación Izquierda"></a></li>';
						break;
					case 'right':
						if (!noCss) {
							styles += '.edHdr a.edR { background-position: -197px 0; }';
							styles += '.edHdr a.edR:active { background-position: -197px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'right\');return false;" class="edR" title="Alineación Derecha"></a></li>';
						break;
					case 'video':
						if (!noCss) {
							styles += '.edHdr a.edVideo { background-position: -364px 0; }';
							styles += '.edHdr a.edVideo:active { background-position: -364px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'video\');return false;" class="edVideo" title="Insertar Video"></a></li>';
						break;
					case 'sidebar':
						if (!noCss) {
							styles += '.edHdr a.edSidebar { background-position: -470px 0; }';
							styles += '.edHdr a.edSidebar:active { background-position: -470px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'sidebar\');return false;" class="edSidebar" title="Sidebar"></a></li>';
						break;
					case 'uploadImg' :
						if (!noCss) {
							styles += '.edHdr a.edUploadImg { background-position: -336px 0; }';
							styles += '.edHdr a.edUploadImg:active { background-position: -336px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\'' + name + '\'),\'uploadImg\'); return false;" class="edUploadImg" title="Da click aquí para subir imágenes desde tu pc"></a></li>';
						break;
					case 'galleries' :
						if (!noCss) {
							styles += '.edHdr a.edGalleries { background-position: -528px 0; }';
							styles += '.edHdr a.edGalleries:active { background-position: -528px -28px; }';
						}
						ul.innerHTML += '<li><a href="#" onclick="edTag($$(\'' + name + '\'),\'galleries\'); return false;" class="edGalleries" id = "edGalleries" title="Da click aquí para seleccionar una imagen desde tus galerías"></a></li>';
						break;
				}
			}
		}
		if (settings.maxLength){
			maxLength(editor,settings.maxLength);
		}
	}else{
		ul.innerHTML = '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'b\');return false;" class="edB" title="Bold"></a></li>';
		ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'i\');return false;" class="edI" title="Italic"></a></li>';
		ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'u\');return false;" class="edU" title="Underline"></a></li>';
		ul.innerHTML += '<li><span class="edSep"></span></li>';
		ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'center\');return false;" class="edC" title="Texto centrado"></a></li>';
		ul.innerHTML += '<li><span class="edSep"></span></li>';
		ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'video\');return false;" class="edLU" title="Videos"></a></li>';
		ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'img\');return false;" class="edIMG" title="Insertar Imágen"></a></li>';
		ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'url\');return false;" class="edURL" title="Insertar URL"></a></li>';
		ul.innerHTML += '<li><a href="#" onclick="edTag($$(\''+name+'\'),\'sidebar\');return false;" class="edSidebar" title="Sidebar"></a></li>';
		var settings = {};
		settings.buttons = ['b','i','u','|','center','|','video','img','url','sidebar'];
	}
	if (!noCss) {
		if (css.styleSheet) css.styleSheet.cssText = styles;
		else css.appendChild(document.createTextNode(styles));
		document.getElementsByTagName("head")[0].appendChild(css);
	}
	editor.parentNode.insertBefore(ul,editor);
	if (settings.buttons) var buttonsHiddenInput = $('<input>').attr({'id':'buttons_editor_'+name,'type':'hidden','value':settings.buttons.join()});
	else var buttonsHiddenInput = $('<input>').attr({'id':'buttons_editor_'+name,'type':'hidden','value':'b,i,u,|,center,|,video,img,url,sidebar'});
	$(ul).after(buttonsHiddenInput);
}
function resizeElement(evt,elId,elId2){
    if( $$(elId) && $$(elId2) ){
    	var gWinData = getWindowData();
    	var widthForTArea = gWinData[0]-14;
		var heightForTArea = gWinData[1]-35;
		if (document.documentMode) { widthForTArea-=17; heightForTArea-=18; };
	    $$(elId).style.width = gWinData[0]+'px';
	    $$(elId).style.height = gWinData[1]+'px';
	    $$(elId2).style.width = widthForTArea+'px';
	    $$(elId2).style.height = heightForTArea+'px';
    }
}
function insertEdText(el,text){
	if (text != '') {
		if (el.setSelectionRange){
			el.value = el.value.substring(0,el.selectionEnd) + text + el.value.substring(el.selectionEnd,el.value.length);
		}else{
			el.focus();
			selText = document.selection.createRange().text;
			document.selection.createRange().text = selText+text;
		}
	}
	return false;
}
function maxLength(el,length){
	el.maxLength = length;
	el.onKeyDown = function(){
		if (this.length==this.maxLength)
			return false;
		else
			return true;
	};
}
function fbLogin(){
	var height = 360;
	var width = 500;
	var w,h;
	if (document.all){
	   	w = document.body.clientWidth;
	   	h = document.body.clientHeight;
	}else if (document.layers){
	   	w = window.innerWidth;
	   	h = window.innerHeight;
	}else{
		w = screen.availWidth;
		h = screen.availHeight;
	}
	var top = (h-height)/2;
	var left = (w-width)/2;
	var title = isBrowser.IE ? '_blank':'Conexión LevelUp';
	window.open(FB_AUTH,title,'width='+width+',height='+height+',top='+top+',left='+left+',resizable=no');
}
var fbLoginWin = null;
function retFbLogin(obj){
	var error = '';
	var cancel = false;
	var settings = {
		width: 'auto',
		height: 'auto',
		modal: true,
		id: 'fbLoginWindow',
		className: 'fbLoginWin'
	};
	switch(obj.status){
		case -3:
			cancel = true;
			break;
		case -2:
			settings.title = 'Error';
			settings.content = '<div class="fbDiv">Error al intentar acceder a la base de datos (Acción: Update).</div>';
			break;
		case -1:
			settings.title = 'Error';
			settings.content = '<div class="fbDiv">Error al intentar acceder a la base de datos (Acción: Add).</div>';
			break;
		case 0:
			settings.title = 'Error';
			settings.content = '<div class="fbDiv">Error al intentar conectarse a Facebook.</div>';
			break;
		case 1:
			settings.title = 'Selecciona un Nickname';
			settings.content = '<div class="fbDiv tleft">' + 
			'	<p style="margin-bottom:20px;">Haz accesado a '+SITE_NAME+', solo te falta escoger un nickname.</p>' + 
			'	<br/>' + 
			'	<p style="text-align:center;">' + 
			'		<label for="fbNickname"><strong>Nickname</strong></label> &nbsp; ' + 
			'		<input type="text" style="border:1px solid #DBDCE0;padding:3px;" id="fbNickname"> &nbsp; ' + 
			'		<input type="button" value="Verificar" class="boton" id="btnFbNick" onclick="checkFbNickname()"/>' + 
			'	</p>' + 
			'	<p id="fbMessage" style="text-align:center;font-size:12px;margin:5px;" class="center f12 m5"></p>' + 
			'	<p style="text-align:center;margin:10px">' + 
			'		<input id="btnFbNickAceptar" type="button" value="Aceptar" class="boton" onclick="saveFbNickname('+obj.id+')"/></p>' + 
			'	</div>';
      settings.content += '<input type="hidden" id="user_hash" value="'+obj.hash+'" />';
			break;
		case 2:
			settings.title = 'Ya existe una cuenta registrada con tu correo';
			settings.content =
				'<div class="fbDiv">' + 
				'	<p>¿Deseas asociar tu cuenta de LevelUp registrada con el email <strong>'+obj.email+'</strong> a tu cuenta de Facebook?</p>' + 
				'	<br/><br/>' + 
				'	<p><input type="button" class="boton" value="Aceptar" id="fbAccBtn" onclick="assocFbAccount('+obj.id+',\''+obj.facebook_token+'\');"> &nbsp; <input type="button" class="boton" value="Cancelar" onclick="fbLoginWin.close();" id="fbCanBtn"></p>' + 
				'</div>';
			break;
		case 3:
			window.location.href = window.location.href;
			return;
		default:
			settings.title = 'Error';
			settings.content = '<div class="fbDiv">Error desconocido. </div>';
			break;
	}
	if ( fbLoginWin != null ) {
		fbLoginWin.close();
		fbLoginWin.destroy();
		fbLoginWin = null;
	}
	if (cancel) return;
	fbLoginWin = new ModalWindow(settings);
	fbLoginWin.show();
}
function checkFbNickname(opt){
	if (trim($$('fbNickname').value)==''){
		$$('fbMessage').innerHTML = 'Escriba un nickname';
		return;
	}
	$$('fbMessage').innerHTML = 'Verificando...';
	disable('btnFbNick');
	ajaxRequest(MEMBERS,'chkNick',{ 'json':true, 'nickname':$$('fbNickname').value } ,function(obj){ $$('fbMessage').innerHTML = obj.status ? 'Nick disponible' : 'Nick no disponible'; enable('btnFbNick'); });
}
function saveFbNickname(id){
	if (trim($$('fbNickname').value)==''){
		$$('fbMessage').innerHTML = 'Escriba un nickname';
		return;
	}
	$$('fbMessage').innerHTML = 'Guardando...';
	disable('btnFbNick');
	disable('btnFbNickAceptar');
	ajaxRequest(MEMBERS,'saveNickname',{ 'nickname':$$('fbNickname').value, 'idMember':id, 'hash':$$('user_hash').value, 'facebook':true },
		function(obj){
			$$('fbMessage').innerHTML = obj.message;
			if (obj.status) {
				$$('btnFbNickAceptar').onclick = function(){
					fbLoginWin.close();
					fbLoginWin.destroy();
					window.location.reload();
				};
				$$('btnFbNickAceptar').value = "Cerrar";
			}
			enable('btnFbNick');
			enable('btnFbNickAceptar');
		}
	);
}
function assocFbAccount(idMember, facebook_token){
	disable('fbAccBtn','fbCanBtn');
	var params = {
		'id':idMember,
		'facebook_token':facebook_token
	}
	ajaxRequest(MEMBERS,'assocFbAccount',params,doneFbAssoc);
}
var fbMsgWindow = null;
function doneFbAssoc(obj){
	if (obj.status){
		window.location.href = window.location.href;
		return;
	}
	var settings = {
		width: 'auto',
		height: 'auto',
		modal: false,
		id: 'fbLoginMessage',
		className: 'fbLoginWin'
	};
	settings.title = 'LevelUp';
	settings.html = '<div class="fbDiv">'+obj.message+'</div>';
	if ( fbMsgWindow != null){
		fbMsgWindow.destroy();
		fbMsgWindow.close();
		fbMsgWindow = null;
	}
	fbMsgWindow = new ModelWindow(settings);
	fbMsgWindow.show();
}
var loginWindowObj = null;
function loginWindow(regFlag){
	var settings = {
			width:			500,
			closable:		true,
			disable_screen:	true,
			resizable:		false,
			container: 		'pmwc'
		};
	settings.html = '<div class="tleft p10">';
	if (regFlag){
		settings.title = 'Registro Exitoso';
		settings.html += '<p class="cred fbold f16">¡Bienvenido a LevelUp!</p>';
		settings.html += '<p class="f12 p10">Ahora solo tienes que activar tu cuenta siguiendo las indicaciones en el correo que te acabamos de enviar.</p>';
		settings.html += '<p class="f12 p10">Si ya verificaste tu cuenta, solo introduce tu email y contraseña para ingresar a LevelUp.</p>';
	}else{
		settings.title = 'Entra a LevelUp';
		settings.html += '<p class="cred fbold f16">¿Tienes Cuenta? ¡Entra Ya!</p><br>';
	}
	
	var reg = (regFlag) ? 'Login' : '';
	settings.html += '<iframe scrolling="no" frameBorder="0" id="loginRegisterIframe" src="'+LOGINSERVER+MEMBERS+'/secureLoginForm/loginRegisterWindow/'+urlencode(urlencode(window.location.href))+'/" allowtransparency="true"></iframe>';
	if(FB_AUTH!=''){
		settings.html += '<p class="cred fbold f16">¿Tienes Cuenta en Facebook?</p>';
		if (regFlag){
			settings.html += '<p class="f12 p10">Recuerda que puedes enlazar tu cuenta de LevelUp con Facebook.</p>';
		}else{
			settings.html += '<br>';
		}
		settings.html += '<div class="mt5 mb10 center"><img src="/libs/templates/images/fb-button.jpg" style="cursor:pointer;" onclick="fbLogin();loginWindowObj.DestruirVentana();loginWindowObj=null;"></div>';
	}
	settings.html += '</div>';
	if (loginWindowObj!=null){
		loginWindowObj.DestruirVentana();
		loginWindowObj = null;
	}
	loginWindowObj = new Window('loginWindow',settings);
	scroll(0,150);
	loginWindowObj.showWindow();
}
function doLogin(regFlag){
	var reg = (regFlag) ? 'Login' : '';
	if (trim($$('LWemail' + reg).value) == '') {
		$$('LWmsg').innerHTML = 'Introduce un email válido';
		return;
	}
	if (trim($$('LWpassword' + reg).value) == '') {
		$$('LWmsg').innerHTML = 'El campo contraseña no debe estar vacío';
		return;
	}
	$$('LWmsg').innerHTML = 'Enviando información...';
	disable('LWloginBtn', 'LWregBtn');
	$$('loginForm').submit();
}
function redirectWindow(obj){
	if(obj.redirect){
		if(parent==window)
			window.location.href = obj.redirect;
		else
			parent.location.href = obj.redirect;
	}
}
function doRegister() {
	if ( trim( $$('mail').value ) == '' ) {
		$$('LWmsgReg').innerHTML = 'Introduce un email válido';
		return;
	}
	if ( trim( $$('pass').value ) == '' ) {
		$$('LWmsgReg').innerHTML = 'El campo contraseña no debe estar vacío';
		return;
	}
	if ( trim( $$('pass').value ) != trim( $$('rpass').value ) ) {
		$$('LWmsgReg').innerHTML = 'Las contraseñas no coinciden';
		return;
	}
	$$('LWmsgReg').innerHTML = 'Enviando información...';
	disable('LWloginBtn','LWregBtn');
	$$('registerForm').submit();
}
function in_array(needle, haystack, argStrict){
	var key = '', strict = !!argStrict;
	if(strict){
		for(key in haystack){
			if(haystack[key] === needle){
				return true;
			}
		}
	} else {
		for(key in haystack){
			if(haystack[key] == needle){
				return true;
			}
		}
	}
	return false;
}
if(typeof(Array.indexOf)=='undefined'){
	Array.prototype.indexOf = function(obj){
		for(var i=0; i<this.length; i++){
			if(this[i]==obj){
				return i;
			}
		}
		return -1;
	};
}
function disableScreen(){
	var div = $('<div></div>').css({
		'background-color' : 'black',
		'height': '100%',// $('body').height()+'px',
		'width': '100%',
		'position': 'fixed',
		'padding': '0',
		'margin': '0',
		'left': '0',
		'top' : '0',
		'z-index': '10',
		'opacity': '0.8'
	}).attr('id','screenDisabler');
	$('body').children().first().before(div);
}
function enableScreen(){
	$.remove('#screenDisabler');
}
function fwkTextArea(params) {
	var element = $(params.clase);
	var char_limit = params.char_limit;
	var regex_toRemove = new RegExp(params.regex_toRemove);
	
	element.bind('keypress', function(){
		if (this.value.length > char_limit ) {
			this.value = this.value.substring(0, char_limit);
		}
	});
	element.bind('keyup', function(){
		this.value = this.value.replace(regex_toRemove,"");
	});
}
function collect() {
  var ret = {};
  var len = arguments.length;
  for (var i=0; i<len; i++) {
    for (p in arguments[i]) {
      if (arguments[i].hasOwnProperty(p)) {
        ret[p] = arguments[i][p];
      }
    }
  }
  return ret;
}

/**
 * sliderSlipH()
 * 
 * Funcion configurable para un slideshow horizontal. Representa una mejora de
 * la funcion slideShowSlip de static.js, para un posible reemplazo.
 * 
 * @author Mario de Jesus Merlos Cruz.
 * @param object
 *            params Trae los datos necesarios para la configuracion del slider
 */
function sliderSlipH(params) {
	var currentPosition = params.currentPosition || 1;
	var slideWidth = params.slideWidth || 275;
	var ajaxFunction = params.ajaxFunction;
	var extraParams = params.extraParams || null;
	var numImgsAjax = params.numImgsAjax || 1;
	var plugin = params.plugin;
	var id = params.slide_id;
	var slides = $('.slide' + id);
	var numberOfSlides = params.total || slides.length;
	var control = $('.control' + id);
	var slideInner = 'slideInner' + id;
	var rightControl = 'rightControl' + id;
	var leftControl = 'leftControl' + id;
	var upAndDown = params.upAndDown || false;
	var rightControlEl = ( upAndDown ) ? $('.' + rightControl) : $('#' + rightControl);
	var leftControlEl = ( upAndDown ) ? $('.' + leftControl) : $('#' + leftControl);
	
	$('#' + 'slider' + id).css("width", slideWidth + 'px');
	$('#' + 'container' + id).css("width", slideWidth + 'px');
	slides.css("width", slideWidth + 'px');
	slides.wrapAll('<div id="'+slideInner+'"></div>');
	$('#' + slideInner).css( "width", (slideWidth * numberOfSlides) );
	
	var tempHight = $('#' + 'slider' + id).height();
	var ajaxImages = $c('div');
	ajaxImages.id = 'tempAjaxImgs';
	$(ajaxImages).css( { "width": slideWidth + 'px', 'height': tempHight + 'px' } ).addClass('slide');
	
	manageControls(currentPosition);
	
	control.each(function() {
		$(this).bind('click', function() {
			var band = ( upAndDown ) ? $(this).hasClass( rightControl ) : ( $(this).attr('id') == rightControl );
			if ( band ) {
				if(currentPosition < numberOfSlides) {
					currentPosition++;
				} else { return false; }
				if ( !$$( id + (currentPosition) ) ) {
					$(ajaxImages).appendTo('#'+slideInner);
					showAjaxImgBig('#tempAjaxImgs' , numImgsAjax);
				}
				slide('#'+slideInner);
				if ( !$$( id + (currentPosition) ) ) {
					var param = { 'page' : currentPosition, 'user_id' : params.user_id };
					var paramFinal = collect(param, extraParams);
					ajaxRequest(plugin, ajaxFunction, paramFinal, function(obj) {
						if (!obj.status) { return false; }
						$('#'+slideInner).append(obj.template);
						$('#'+id+currentPosition).css("width", slideWidth + 'px');
						$('#'+id+currentPosition).hide();
						setTimeout(function(){ $('#tempAjaxImgs').remove(); },50);
						setTimeout(function(){ $('#'+id+currentPosition).show(); },50);
						setTimeout(function(){ imgProportions(); },200);
						if ( params.callback ) {
							eval( params.callback );
						}
					});
				}
			} else {
				if (currentPosition>1) {
					currentPosition--;
				} else { return false; }
				slide('#'+slideInner);
			}
			manageControls(currentPosition);
			setActivePosition(currentPosition);
		});
	});
	function manageControls(position){
		if(position==1){leftControlEl.fadeTo("fast",0.4);}else{leftControlEl.fadeTo("fast",1);}
		if(position==numberOfSlides){rightControlEl.fadeTo("fast",0.4);}else{rightControlEl.fadeTo("fast",1);}
	}
	function slide(id) {
		$(id).animate({'marginLeft' : slideWidth*(-(currentPosition-1))},500);
	}
	function setActivePosition(pos) {
		$('#slideInner'+id).find( 'div.activePage' ).removeClass('activePage');
		$('#'+id+pos).addClass('activePage');
	}
}
function imgProportions () {
	var images = $('.resize_Img');
	images.each( function() {
		var img = $(this);
		var imgWidht = img.width();
		var imgHeight = img.height();
		var conteiner = $(this).parent();
		var conteinerWidth = conteiner.width();
		var conteinerHeight = conteiner.height();
		var slideH, slideV;
		
		if ( ( imgWidht > conteinerWidth ) && ( imgHeight > conteinerHeight ) ) {
			slideH = imgWidht - conteinerWidth;
			slideV = imgHeight - conteinerHeight;
			if ( slideH > slideV ) {
				img.height( conteiner.height() );
				slideH = (img.width() - conteiner.width()) / 2;
				img.css({'margin-left' : '-' + ( slideH ) + 'px' });
			} else {
				img.width( conteiner.width() );
				slideV = (img.height() - conteiner.height()) / 2;
				img.css({'margin-top' : '-' + ( slideV ) + 'px' });
			}
		} else if ( imgWidht > conteinerWidth ) {
			slideH = (imgWidht - conteinerWidth) / 2;
			img.css({'margin-left' : '-' + ( slideH ) + 'px' });
			img.height( conteiner.height() );
			
		} else if ( imgHeight > conteinerHeight ) {
			slideV = (imgHeight - conteinerHeight) / 2;
			img.css({'margin-top' : '-' + ( slideV ) + 'px' });
			img.width( conteiner.width() );
		}
	});
}
function showAjaxImgBig( parent, quantity ) {
	showCenterImg( 'loading.gif', parent, quantity );
}
function showLoadingSImg( parent, quantity ) {
	showCenterImg( 'loading_small.gif', parent, quantity );
}
function showCenterImg( img_name, parent, quantity ) {
	quantity = (!isNaN(quantity) > 0 ) ? quantity : 1;
		var divider = quantity + 1;
		var i;
		for (i=0; i<quantity; i++) {
			var img = $c('img');
			$(img).attr({
				src     : '/app/templates/default/images/' + img_name
			});
			$(img).addClass('img_temp');
			var leftPos = ( ( $(parent).width() ) / divider ) - 11;
			var aux = leftPos*i;
			$(img).css({
				display : 'none',
				position : 'absolute',
				'left' : leftPos + aux,
				'top' : ( ( $(parent).height() ) / 2 ) - 11,
				'z-index' : 99
			});
			$(parent).append(img);
			$(img).show();
		}
}
function removeImgTemp( parent ) {
	$(parent).children('.img_temp').remove();
}
/**
 * Crea eventos del elementos
 * 
 * @param element
 * @param event
 * @return
 */
function fireEvent(element, event) {
	if (document.createEventObject) {
		// dispatch for IE
		var evt = document.createEventObject();
		return element.fireEvent('on' + event, evt);
	} else {
		// dispatch for firefox + others
		var evt = document.createEvent("HTMLEvents");
		evt.initEvent(event, true, true); // event type,bubbling,cancelable
		evt.keyCode = 65;
		evt.charCode = 65;
		var ret = !element.dispatchEvent(evt);
		return ret;
	}
}

function twitterConfirmationMessage(){
	$('body').append($('<div id="screenOverlay"></div>').css({'width':$(document).width(),'height':$(document).height()}));
  $('#screenOverlay').click(function(){
	  closeLoginWindow();
  });
  if($('#loginWindow').length == 0){
    $('body').append($('<div id="loginWindow"></div>').html(
			'<div class="closeBtnCtn"><a class="closeBtn" href="#" onclick="closeLoginWindow();return false;" title="Cerrar">Cerrar</a></div>' +
			'<h3><span>'+SITE_FULL_NAME+'</span></h3>' +
			'<div class="center mtop20 mbottom20">' +
			'	<p class="f16 fbold mbottom">Tu cuenta de '+SITE_NAME+' y Twitter han sido sincronizadas</p>' +
			'	<p class="f13 mbottom20">Ahora puedes actualizar el estatus de tu perfil desde '+SITE_NAME+' o Twitter</p>' +
			'	<input class="sBtn" type="button" value="Continuar" onclick="closeLoginWindow();return false;" />' +
			'</div>' +
			''
		));
  }
	$('#loginWindow').css({'display': 'block'});
  $(window).resize(function(){
		$('#screenOverlay').css({'width':$(document).width(),'height':$(document).height()});
	});
}
var Ads_originalBkgColor = '';
$(document).ready(function(){
	Ads_originalBkgColor = $('body').css('backgroundColor');
});
function changeAds(){
	if(typeof Ads_change_ads == 'undefined') return;
	if(!Ads_change_ads) return;
	
	var platformId = (typeof idPlatform != 'undefined') ? idPlatform : 0;
	var gameId = (typeof idGame != 'undefined') ? idGame : 0;
	var url = DOMAIN + 'no-cache/adsnetwork.php?type=refresh&platform='+platformId+'&game='+gameId+'&rand='+Math.floor(Math.random()*1000);
	
	$.ajax({
		url: url,
		dataType: 'json',
		success: function(data) {
			doneChangeAds(data);
		}
	});
	setTimeout("changeAds()",Ads_timeout);
}
function doneChangeAds(obj){
	if(obj.status){
		if(obj.leaderboard)
			$$('iframeLeaderBoard').src = obj.leaderboard;
		if(obj.adbox && $('iframeAdBox'))
			$$('iframeAdBox').src = obj.adbox;
		if(obj.background_pic || obj.background_url){
			if(obj.background_url)
				document.body.style.backgroundImage = "url("+obj.background_url+")";
			else
				document.body.style.backgroundImage = "url("+obj.background_pic+")";
			document.body.style.backgroundRepeat = 'no-repeat';
			document.body.style.backgroundAttachment = 'fixed';
			document.body.style.backgroundPosition = 'center top';
		} else {
			document.body.style.backgroundImage = "none";
			document.body.style.backgroundRepeat = 'repeat-x';
			document.body.style.backgroundAttachment = 'fixed';
			document.body.style.backgroundPosition = 'left top';
			document.body.style.backgroundColor = Ads_originalBkgColor;
		}
		if(obj.background_color)
			document.body.style.backgroundColor = obj.background_color;
		else document.body.style.backgroundColor = Ads_originalBkgColor;
		if(obj.background_link){
			Ads_background_link = obj.background_link;
		} else Ads_background_link = '';
		if(obj.hidden_html){
			var hiddenDiv = $c('div');
			hiddenDiv.innerHTML = obj.hidden_html;
			hiddenDiv.style.display = 'none';
			document.body.appendChild(hiddenDiv);
		}
	} else {
		Ads_change_ads = false;
	}
}

var waitFlagNick = false;
var waitFlagEmail = false;

function checkEmail(){
	if (waitFlagEmail){
		alert('Por favor, espere a terminar la última acción.');
		return;
	}
	
	waitFlagEmail = true;
	var params = {'email':$$('mail').value};	
	if(params.email==''){
		waitFlagEmail = false;
		alert('Escriba un correo válido');
		return false;
	}
	messageDiv = $$('confirmation_message_email');
	messageDiv.innerHTML = 'Verificando...';
	
	ajaxRequest(MEMBERS,'chk_email',params,displayEmailConfirmation);
}

function displayEmailConfirmation(html){
	$$('confirmation_message_email').innerHTML = html;
	waitFlagEmail = false;
}

function checkForm(){
	email = $$('mail').value;
	if ($$('mail')){
		if (trim(getValue('mail'))==''){
			alert('Escriba un email válido');
			return false;
		}
	}
	
	if(!validateEmail(email)){
		alert('Escriba un correo v&aacute;lido');
		return false;
	}
	
	if ($$('pass')){
		if (trim(getValue('pass'))==''||trim(getValue('rpass'))==''){
			alert('Complete ambos campos de contraseña');
			return false;
		}
		
		if (getValue('pass')!=getValue('rpass')){
			alert('Verifique que las contraseñas sean iguales');
			return false;
		}
	}
	
	form = $$('register_form');
	form.submit();
	return true;
}

/**
 * Crea un objeto de ventana modal (Se coloca sobre todo)
 * 
 * @param Object
 *            options Opciones para la configuración de la ventana
 * @author Juan Elías López <juanelias@buscacorp.com>
 */
var ModalWindow = function(options){
	var _this = this;
	var id = null;
	var content = null;
	var windowDiv = null;
	var contentDiv = null;
	var title = null;
	var width = null;
	var height = null;
	var className = null;
	var showing = false;
	var modal = false;
	var modalDiv = null;
	var destroyOnClose = false;
	var beforeClose = null;
	
	this.show = show;
	this.close = close;
	this.resizeBrowser = resizeBrowser;
	this.destroy = destroy;
	this.closeAndDestroy = closeAndDestroy;
	initialize(options);
	
	return _this;
	
	function initialize(options){
		id = options.id;
		content = options.content;
		title = options.title;
		width = options.width;
		height = options.height;
		modal = options.modal || false;
		className = options.className;
		destroyOnClose = options.destroyOnClose || false;
		beforeClose = options.beforeClose || null;
		
		windowDiv = createWindow();
		if(modal){
			modalDiv = $('<div></div>')
				.addClass('modalWindowOverlay')
				.css('display','none')
				.width($('body').width())
				.height($('body').height());
			$('body').append(modalDiv);
		}
		$('body').append(windowDiv);
		
		$(window).resize(function(){
			_this.resizeBrowser();
		});
	}
	
	function createWindow(){
		var windowDiv = $('<div></div>')
			.attr({ 'id':id })
			.addClass('modalWindow')
			.width(width)
			.height(height)
			.css( { 'display':'none','position':'fixed','z-index':'2000' });
		if(className!='')
			windowDiv.addClass(className);
		
		var closeButton = $('<a></a>').attr({'href':'#','title':'Cerrar'}).addClass('modalWindowCloseBtn').html('Cerrar')
		.click(function(){ closeButtonAction(); return false; });
		windowDiv.append(closeButton);
		
		var contentHeight = '100%';
		if(title!=null){
			windowDiv.append($('<p></p>').addClass('title').append( $('<span></span>').html(title)).css('height','15%'));
			contentHeight = '85%';
		}
		
		contentDiv = $('<div></div>').addClass('modalWindowContent').html(content).css('height',contentHeight);
		windowDiv.append(contentDiv);
		return windowDiv;
	}
	
	function show(){
		if(showing) return;
		var topOffset = Math.floor($(window).height()/2) - Math.floor(windowDiv.outerHeight()/2);
		var leftOffset = Math.floor($(window).width()/2) - Math.floor(windowDiv.outerWidth()/2);
		windowDiv.css( { 'top':topOffset, 'left':leftOffset } );
		if(modalDiv) {
			modalDiv.css('display','block');
		}
		windowDiv.fadeIn(400);
		showing = true;
	}
	
	function close(){
		if(!showing) return;
		if(modalDiv){
			modalDiv.css('display','none');
		}
		windowDiv.fadeOut(400);
		showing = false;
	}
	
	function resizeBrowser(){
		if(showing){
			var topOffset = Math.floor($(window).height()/2) - Math.floor(windowDiv.outerHeight()/2);
			var leftOffset = Math.floor($(window).width()/2) - Math.floor(windowDiv.outerWidth()/2);
			windowDiv.css( { 'top':topOffset, 'left':leftOffset } );
			if(modal){
				modalDiv.width($('body').width()).height($('body').height());
			}
		}
	}
	
	function destroy(){
		if(modal) modalDiv.remove();
		windowDiv.remove();
		delete _this;
	}
	
	function closeAndDestroy(){
		if(!showing) return;
		if(modalDiv) modalDiv.fadeOut(400);
		windowDiv.fadeOut(400, function(){ _this.destroy(); });
	}
	
	function closeButtonAction(){
		if(typeof beforeClose == 'function'){
			var beforeCloseResult = beforeClose();
			if (beforeCloseResult === false) {
				return;
			}
		}
		if(destroyOnClose) {
			closeAndDestroy();
		} else {
			close();
		}
	}
}
function activaEditTitle(picture_id, verif){
	if(verif == '1'){
		if($$('input_title_' + picture_id).value == 'Editar pie de foto ...' || $$('input_title_' + picture_id).value  == ''){
			$('#input_title_' + picture_id).addClass('clickOff');
			$('#input_title_' + picture_id).removeClass('clickOn');
			$('#input_title_' + picture_id).val('Editar pie de foto ...');
		}
	}else{
		if($$('input_title_' + picture_id).value == 'Editar pie de foto ...' || $$('input_title_' + picture_id).value  == ''){
			$('#input_title_' + picture_id).removeClass('clickOff');
			$('#input_title_' + picture_id).addClass('clickOn');
			$('#input_title_' + picture_id).val('');
		}
	}
}
function closeAllOptions (){
	if($$('imgUploadContainer')){
		$$('imgUploadContainer').innerHTML = '';
		$('#imgUploadContainer').remove();
		ImgUploadObj = null;
		var ImgUploadObj = new ImgUpload();
	}			
	if($$('galleriesContainer')){
		$$('galleriesContainer').innerHTML = '';
		$('#galleriesContainer').remove();
		GalleriesObj = null;
		var GalleriesObj = new Galleries();
	}	
}
function goToLineText(idElement, ini, textInsert, cantElement){
	var el = $$(idElement);
	el.setSelectionRange(ini,(ini+textInsert));
	setTimeout(function (){
		el.setSelectionRange(((ini+textInsert)-cantElement),((ini+textInsert)-cantElement));
	}, 500);
}
function getLoginCookies(){
	var emailCookie = getCookie('loginLUP[email]');
	var passwordCookie = getCookie('loginLUP[password]');
	var facebookCookie = getCookie('loginLUP[facebook]');
	var loginCookies = {};
	if (emailCookie) {
		loginCookies.eUpload = emailCookie;
	}
	if (passwordCookie) {
		loginCookies.pUpload = passwordCookie;
	}
	if (facebookCookie) {
		loginCookies.fUpload = facebookCookie;
	}
	return loginCookies;
}
function editarEventoTool(el){
	var id = $('.eventBox div >  input').val();
	var arr = {
		keepAlive : true,
		content : $('.eventBox #tooltip_edit'+id).html()
	};
	$('.eventBox #tooltip_edit'+id).remove();
	return arr;
}

/* ****************************************************/
/* Registra callbacks globales para las llamadas ajax */
/* ****************************************************/
jQuery(document).ready(function() {
	function _addTr(table, number) {
		var tr = jQuery('<tr />');
		tr.attr('bgcolor',number % 2 ? '#F0F0F0' : '#F5F5F5');
		table.append(tr);
		return tr;
	}
	function _addTd(tr,data) {
		var td = jQuery('<td />');
		td.html(data);
		tr.append(td);
		return td;
	}
	if (typeof ADMIN != 'undefined') {
		$('#div_queryData table tbody').ajaxComplete(function(e,xhr,settings) {
			var _table = jQuery(this);
			if(xhr.readyState == 4 && xhr.status == 200) {
				try {
					var json = jQuery.parseJSON(xhr.responseText);
					if (json.queries) {
						var totRows = _table.find('tr').length;
						var rowInfo = _addTr(_table, 0);
						var _tdInfo = _addTd(rowInfo, '<strong>' + settings.url + '</strong>');
						jQuery(json.queries).each(function(){
							_tdInfo.attr('colspan', 15);
							var row = _addTr(_table, ++totRows);
							var time = (this.end_time - this.ini_time) * 1000;
							time = time.toString().substring(0, 6);
							_addTd(row,totRows);
							_addTd(row,this.query);
							_addTd(row,time + 'ms');
							_addTd(row, this.error_info);
							jQuery(this.debug).each(function(){
								_addTd(row, this[0]);
								_addTd(row, this[1]);
								_addTd(row, this[2]);
							});
						});
					}
				} catch(e){}
			}
		});
	}
});
