/* 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 */

document.write('<style type="text/css">.tabber,.tabberInterior{display:none;}<\/style>');
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);
}

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 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 getAjaxArray(arr,arrNum){

	applyXmlFnc(arr);
	
	return arr.toXml('obj');
}

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 MultiSelector( list_target, max ){

	// Where to write the list
	this.list_target = list_target;
	// How many elements?
	this.count = 0;
	// How many elements?
	this.id = 0;
	// Is there a maximum?
	this.max = ( max )? max : -1;  
	
	//Add a new file input element
	
	this.addElement = function( element ){

		// Make sure it's a file input element
		if( element.tagName == 'INPUT' && element.type == 'file' ){

			// Element name -- what number am I?
			element.name = 'file_' + this.id++;

			// Add reference to this object
			element.multi_selector = this;

			// What to do when a file is selected
			element.onchange = function(){

				// New file input
				var new_element = document.createElement( 'input' );
				new_element.type = 'file';

				// Add new element
				this.parentNode.insertBefore( new_element, this );

				// Apply 'update' to element
				this.multi_selector.addElement( new_element );

				// Update list
				this.multi_selector.addListRow( this );

				// Hide this: we can't use display:none because Safari doesn't like it
				this.style.position = 'absolute';
				this.style.left = '-1000px';

			};
			// If we've reached maximum number, disable input element
			if( this.max != -1 && this.count >= this.max ){
				element.disabled = true;
			};

			// File element counter
			this.count++;
			// Most recent element
			this.current_element = element;
			
		} else {
			// This can only be applied to file input elements!
			alert( 'Error: not a file input element' );
		};

	};

	
	// Add a new row to the list of files
	
	this.addListRow = function( element ){

		// Row div
		var new_row = document.createElement( 'div' );

		// Delete button
		var new_row_button = document.createElement( 'input' );
		new_row_button.type = 'button';
		new_row_button.value = 'Delete';

		// References
		new_row.element = element;

		// Delete function
		new_row_button.onclick= function(){

			// Remove element from form
			this.parentNode.element.parentNode.removeChild( this.parentNode.element );

			// Remove this row from the list
			this.parentNode.parentNode.removeChild( this.parentNode );

			// Decrement counter
			this.parentNode.element.multi_selector.count--;

			// Re-enable input element (if it's disabled)
			this.parentNode.element.multi_selector.current_element.disabled = false;

			// Appease Safari
			//    without it Safari wants to reload the browser window
			//    which nixes your already queued uploads
			return false;
		};

		// Set row value
		new_row.innerHTML = element.value;

		// Add button
		new_row.appendChild( new_row_button );

		// Add it to the list
		this.list_target.appendChild( new_row );
		
	};

};

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;
}

Array.prototype.toXml = function(t){
    var s = new Array(), i, l = this.length, v;
    var t2 = (t.charAt(t.length-1)=='s')?t.substring(0,t.length-1):t;
   
    for(i=0;i<l;i++){
        v = this[i];
        switch (typeof v) {
            case 'undefined':
            case 'function':
            case 'unknown':break;
            case 'object':if(v!=null){s.push(v.toXml(t2));}break;
            case 'string':v = v.toXml();
            default:s.push('<'+t2+'>'+v+'');
        }
    }
    if(s.length>1)return '<'+t+'>'+s.join('')+'';
    return s;
};

function applyXmlFnc(elem){
	elem.toXml = function(t){
	    var sa = new Array(''), se = new Array('');
	    if(!t) t=this._tagName||'object';
	   
	    for(var i in this){               
	        if (this.hasOwnProperty(i) && i.charAt(0)!='_') {
	            var v = this[i];
	            switch (typeof v){
	                case 'undefined':
	                case 'function':
	                case 'unknown':break;
	                case 'object':if(v!=null){se.push(v.toXml(i));}break;
	                case 'string':v = v.toXml();
	                default: sa.push(' '+i+'="'+v+'"');
	            }
	        }
	    }
	    var s = se.join('');
	    return '<'+t+sa.join('')+((s!='')?'>'+s+'':'/>');
	};
}

String.prototype.toXml = function(){
	var str = this.replace(/&/g,'&amp;').
    replace(/</g,'&lt;').replace(/>/g,'&gt;').
    replace(/'/g,'&apos;').replace(/"/g,'&quot;').
	replace(/\+/g,'&#43;');

	str = str.replace(/\n/g,'');
	str = str.replace(/\s/g,' ').replace(/ ,/g,' ');
	
	return str;
};


//var resize_max_width = 480; // you can change this number, this is the max width in pixels for posted images
var resize_border_1 = '1px solid';
var resize_border_2 = '2px solid';
var resize_image_title = '';
function resize_go()
{
	return;
}
function resize_img_loaded(resize_obj,maxWidth)
{
	return;
}
function resize_refresh_tables()
{
}
function resize_make_pop(resize_ref,maxWidth)
{
}

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.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';
			opt.element.insertBefore(div, opt.element.childNodes[0]);
			opt.element.blockerDiv = div;
		}
	}else{
		if (!opt.element.divdisabled)
			return;
		opt.element.divdisabled = false;
		removeEl(opt.element.blockerDiv);
		opt.element.divdisabled = false;
	}
}
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)
{	
	var pluginRef = DOMAIN + '?'+SECTION  + '=' + section + '&'+ ACTION + '=' + action +'&ajax_request=1';
	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){
					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");
     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])
		{
			var obj = [];
			if (params)
				obj = params;
			obj.item_id = item_id;
			obj.page = x;
			ajaxRequest
			(
				section,
				action,
				obj,
				yF
			);
		}
		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);
	}
}


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 (console)
		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");
	addEvent
	(
		this.input,
		'keyup',
		function(e){
			_this.onKeyUp(e);
		}
	);
	addEvent
	(
		window,
		'click',
		function(e){
			if (!/autocomplete/.test(getTarget(e).className)&&!/acNoHide/.test(getTarget(e).className)) {
				hide(_this.dropDownDIV);
			}
		}
	);
	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';
		div.style.width = getStyle(this.input,'width');
		//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'));
	hide(div);
	insertAfter(div,this.input);
};

autoCompleteDrop.prototype.getDiv =  function ()
{
	return this.dropDownDIV;
};

autoCompleteDrop.prototype.onKeyUp =  function (e){
	var text = getTarget(e).value;
	var key = getPressedKey(e);
	var _this =  this;
	if(!/(38|40|13|27)/.test(key)){
		if (this.input.value != ''){
			var xhrCallBack = function (r){
				_this.getData(r);
			};
			if (_this.options.processData){
				this.showAndhideSelects(false);
				xhrCallBack(_this.options.processData(text));
			}else{
				ajaxRequest(_this.options.section,_this.options.action,{'keywords': text},xhrCallBack,false);
				this.showAndhideSelects(false);
			}
		}else{
			hide(this.dropDownDIV);
			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;
			hide(this.dropDownDIV);
			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);
			hide(this.dropDownDIV);
			this.showAndhideSelects(true); 
		}
	}
};

autoCompleteDrop.prototype.getData = function (obj){
	var _this = this;
	this.dropDownDIV.innerHTML='';
	x = obj.data;
	var j = x.length;
	if (typeof obj.data != 'object' || j <= 0){
		hide(this.dropDownDIV);
		return;
	}
	this.lengthList = x.length;
	this.position = -1;
	this.last = 0;  
	this.arrayDivs = new Array();
	this.arrayItems = new Array();
	for(iz in x){
		var div_child = $c('div');
		div_child.className = 'out';
		div_child.onmouseover = function(){ this.className='min' };
		div_child.onmouseout = function(){ this.className='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{
			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(){
			hide(_this.dropDownDIV);
			_this.clickDiv(this);
			_this.showAndhideSelects(true);
		};
		this.arrayDivs.push(div_child);
		$a(this.dropDownDIV,div_child);
	}
	show(this.dropDownDIV);
	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){
	var _this = this;
	var xhrCallBack = function (r){
		_this.getData(r);
	};
	if (_this.options.processData){
		this.showAndhideSelects(false);
		xhrCallBack(_this.options.processData(text));
	}else{
		ajaxRequest(this.options.section,this.options.action,{'keywords': text},xhrCallBack,false);
		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 PLAYBOY.JS */

function Tabber(opt){
	this.opt = opt;
	this.opt.prefix = opt.prefix||'';
	var childs = $(opt.div).childNodes;
	var first = true;
	var indexTabs = 0;
	
	for (var i=0; i<childs.length;i++){
		if (childs[i].tagName=='UL'||childs[i].tagName=='DIV'){
			if (childs[i].tagName=='UL'){
				var index = 0;
				var tabs = childs[i].childNodes;
				for (var t=0; t<tabs.length;t++){
					if (tabs[t].tagName=='LI'){
						tabs[t].tabber = this;
						
						if (isBrowser.IE){
							tabs[t].childNodes[0].href = 'javascript:void(0);';
							tabs[t].childNodes[0].id = this.opt.prefix+'tl'+index;
						}else{
							links = tabs[t].getElementsByTagName('a');
							links[0].href = 'javascript:void(0);';
							links[0].id = this.opt.prefix+'tl'+index;
						}	
						tabs[t].idTab = index;
						tabs[t].onclick = function(){
							if (this.tabber.currTab!=this.idTab){
								$(this.tabber.opt.prefix+'tl'+this.tabber.currTab).className = 'tbi';
								$(this.tabber.opt.prefix+'tb'+this.tabber.currTab).className = 'tabi';
								$(this.tabber.opt.prefix+'tl'+this.idTab).className = '';
								$(this.tabber.opt.prefix+'tb'+this.idTab).className = 'taba';
								this.tabber.currTab = this.idTab;
							}
						}
						index++;
					}
				}
			}else{
				childs[i].id = this.opt.prefix+'tb'+indexTabs;
				if (childs[i].className==''){
					childs[i].className = first?this.opt.prefix+'taba':'tabi';
				}
				first = false;
				indexTabs++;
			}
		}
		this.currTab = 0;
	}
}

/* TERMINA PLAYBOY.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.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);
			}
		}
		
		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);
		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);
		}
		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,
				selector	:	_this,
				dropDownClick: function(id,value){
					this.selector.add(id,value);
					$(this.input_id).value = '';
					$(this.input_id).focus();
				}
		});
	}
}

/* TERMINA SELECTOR.JS */

/* INICIA SLIDER.JS */

var Slider  = function (options)
{
	this.options = options;
	this.currentPage = 1;
	this.cache = new Array();   
    this.init();
    this.morePages = true;
};
Slider.prototype.init =  function ()
{
	var _this = this;
	var cont = this.options.element;
	var childNodes = cont.childNodes;
	var sliderLeft;
	var sliderRight;
	var galleryRefresh;
	var previus = true;
	if(this.options.left_clicker)
	{
		sliderLeft = this.options.left_clicker;
		sliderRight = this.options.right_clicker;
		galleryRefresh = this.options.refresh_div;
	}
	else
		for(var x in childNodes)
		{
			if(/slider_left/.test(childNodes[x].className))
				sliderLeft = childNodes[x].getElementsByTagName('a')[0];
			else 
				if(/slider_right/.test(childNodes[x].className))
				{
					sliderRight = childNodes[x].getElementsByTagName('a')[0];
					previus = false;
				}
			else 
				if(typeof sliderLeft == 'object' && typeof childNodes[x] == 'object' && previus)
					if(childNodes[x].tagName)
						galleryRefresh = childNodes[x];
		}
	_this.galleryRegresh = galleryRefresh;
	_this.sliderLeft = sliderLeft;
	addEvent
	(
		_this.sliderLeft,
		'click',
		function ()
		{
			_this.goSlide(false);
		}
	);
	_this.sliderRight = sliderRight;
	addEvent
	(
		_this.sliderRight,
		'click',
		function ()
		{
			_this.goSlide(true);
		}
	);
	this.cache.push({'html': _this.galleryRegresh.innerHTML,'more':'1','status':'1'});
};
Slider.prototype.goSlide = function (isIncrement)
{
	
	var _this = this;
	var ableToAjax = true;
	if(isIncrement && _this.morePages)
	{
		_this.currentPage ++;
	}
	else if(!isIncrement)
	{
		if(_this.currentPage>1)
		{
			_this.morePages = true;
			_this.currentPage --;
		}
		else ableToAjax = false;
	}

	if(ableToAjax && _this.morePages)
	{
		if(!_this.cache[_this.currentPage-1])
		{
			ajaxRequest
			(
				_this.options.section,
				_this.options.action,
				{
					'item_id'	: _this.options.item_id,
					'section'	: _this.options.section,
					'page'		: _this.currentPage
				},
				function (obj)
				{
					_this.cache.push(obj);
					_this.refreshContent(obj);
				}
			);
		} 
		else
			_this.refreshContent(_this.cache[_this.currentPage-1]);
	}
};

Slider.prototype.refreshContent = function (obj)
{
	if (obj['status'])
	{
		this.galleryRegresh.innerHTML = obj['html'];
		if(obj['more'] != '1')
			this.morePages = false;
	}
};

/* TERMINA SLIDER.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;
	
	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();
			// 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 = 'window_header bgskin btopskin 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 = '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 = (page_size.window_height - (this.height)) / 2 - 50;
		}
		//top += window_scroll.top;
		
		if (!left)
		{
			//left = (page_size.window_width - (this.width)) / 2;
			left = (page_size.window_width - (this.width)) / 2 - 340;
		}
		left += window_scroll.left; 
		top += topOffset;
				
		// Asignando Posicion
		
		this.SetLocation(top, left);
	}; 
	
	// Destruir totalmente la ventana
	obj.DestruirVentana = function(event)
	{	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();		
		}
			
		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";	
	}
	
	// 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 */

/* AGREGANDO ESTILO DE VENTANA*/

document.write('<link href="/app/templates/default/css/window_styles.css" type="text/css" rel="stylesheet"/>');

/**/


/* COMMENTS */

function sendComment(){
	if (rmv = $('ajax_message')){
		rmv.parentNode.removeChild(rmv);
	}
	if (editor){
		txt = editor.getHTML();
	}else{
		txt = $('txt_comment').value;
	}
	params = {'item_id':ITEM_ID,'text':txt,'page':PAGE_NUM};
	disable('btnSendComment');
	$('sendCommentMessage').innerHTML = 'Enviando...';
	ajaxRequest(CURRENT_SECTION, 'add_comment', params, displayNewComment);
}

function displayNewComment(arr){
	if (arr['status']){
		$('new_comment_area').innerHTML += arr['html'].replace(/\\/g,'');
		$('txt_comment').value = '';
		if (editor)
			editor.clear();
		if (rmv = $('message_to_remove'))
			rmv.parentNode.removeChild(rmv);
	}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']);
	}else alert(arr['html']);
}

function replyComment(idComment){
	if (rmv = $('ajax_message')){
		rmv.parentNode.removeChild(rmv);
	}
	txt = $('answer_'+idComment+'_comment').value;
	
	params = {'item_id':ITEM_ID,'text':txt,'page':PAGE_NUM,'parent':idComment};
	ajaxRequest(CURRENT_SECTION, 'add_comment', 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";
}

function votarComment(idComment,tipo){
	ajaxRequest(CURRENT_SECTION, tipo=='mas'? 'add_vote_comment': 'sub_vote_comment',  { 'item_id':ITEM_ID,'comment_id':idComment }, displayVoteComments);					
}


function votarCommentAdmin(idComment,tipo){		 	
	ajaxRequest(CURRENT_SECTION, tipo=='mas'? 'add_vote_comment' : 'sub_vote_comment',  { 'item_id':ITEM_ID,'comment_id':idComment }, displayVoteComments);					
}		

function displayVoteComments(arr){
	
	if (arr['status']){
		var voteObj = $('votes_'+arr['id']+'_span');
		if(parseInt(arr['votes'])>=0){
			voteObj.innerHTML ='+' + arr['votes'];
		}else{
			voteObj.innerHTML =arr['votes'];
		}
	}else{
		alert(arr['html']);
	}			
}		

function moderarComment(idComment){
	ajaxRequest(CURRENT_SECTION, 'moderate_comment',  { '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,'delete_comment',{ '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 = "<span style='color:#9F1815;'>Este Juego Est&aacute; en tus <b>Favoritos</b></span>";
	}else if(check==2){
		if($('div_add_collection_'+filter_id))
			$('div_add_collection_'+filter_id).innerHTML = "<span style='color:#9F1815;'>Este Juego Est&aacute; en tu <b>Coleccion</b></span>";
		if($('div_add_wishlist_'+filter_id))
			$('div_add_wishlist_'+filter_id).innerHTML = "<a id='add_wishlist_"+filter_id+"' href='javascript:addToMyGames(3,"+filter_id+");'>+ Agregar a tu <b>Wishlist</b></a>";
	}else{
		if($('div_add_collection_'+filter_id))
			$('div_add_collection_'+filter_id).innerHTML = "<a id='add_collection_"+filter_id+"' href='javascript:addToMyGames(2,"+filter_id+");'>+ Agregar a tu <b>Coleccion</b></a>";	
		if($('div_add_wishlist_'+filter_id))
			$('div_add_wishlist_'+filter_id).innerHTML = "<span style='color:#9F1815;'>Este Juego Est&aacute; en tu <b>Wishlist</b></span>";
	}
	
	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 sendFriendRequestComments(idFriend){
	tmpFriendId = idFriend;
	ajaxRequest(MEMBERS,'send_friend_request',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);
					}
				}
			);
		}
	}
	var msgVentana = null;
	function showMessageForm(to){
		var html = '<div class="tleft m10 fbold">Asunto:<br/><input type="text" id="msgSubject" class="bgray" style="width:378px"/><input type="hidden" id="msgUser" value="'+to+'"/><br/><br/>';
		html += 'Mensaje:<br/><textarea id="msgBody" class="bgray" rows="15" cols="45"></textarea>';
		html += '<div class="m10 center"><input type="button" onclick="sendMessage()" class="boton gradiente" value="Enviar"/><br/><span class="p5" id="msgStatus"></span></div></div>';
		if (msgVentana == null){
			msgVentana = Window(
				'window_private_message',
				{	
					is_textarea: 	false,
					width:			400,
					height:			100,
					min_width:		160,
					closable:		true,
					draggable:		true,
					disable_screen:	false,
					resizable:		false,
					toogle:			true,
					container:		'pmwc',
					title: 			'Enviar mensaje',
					html:			html
				}	
			);
		}		
		msgVentana.showWindow();
	}
	function sendMessage(){
		if ($('msgUser').value==''){
			alert('Error de parámetros');
			return;
		}
		if (!trim($('msgBody').value)){
			alert('Por favor escriba un mensaje');
			return;
		}
		
		$('msgStatus').innerHTML = 'Enviando mensaje...';
		
		params = {'message':$('msgBody').value,'subject':$('msgSubject').value,'user':$('msgUser').value};
		disable('msgSubject','msgBody');
		ajaxRequest(MEMBERS,'send_members_message',params,displayRetMessage);
	}
		
	function displayRetMessage(html){
		if(msgVentana){
			msgVentana.hideWindow();
			enable('msgSubject','msgBody');
			$('msgBody').value = '';
			$('msgSubject').value = '';
			$('msgUser').value = '';
			$('msgStatus').innerHTML = '';
		}
	}
	
/* 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 = 'left bgray m5 center p5'; 
				div.name = type;
				div.style.width = this.width+'px';
				div.style.height = this.height+'px';
				div.id = plugin+'_'+type;
				
				label = $c('div');
				label.className = 'bggray4 p5';
				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 = '';
	}
	
	/*this.show = function(id){
		for (var i=0;i<this.arr.length;i++){
			if(this.arr[i].id==id)
				$('item'+this.arr[i].id+this.id).style.display='block';
			else
				$('item'+this.arr[i].id+this.id).style.display='none';
		} 
	}	

	this.hide = function(id){
		for (var i=0;i<this.arr.length;i++){
			if(this.arr[i].id==id)
				$('item'+this.arr[i].id+this.id).style.display='none';
		} 
	}	
	
	this.remove = function(id){
		$('item'+id+this.id).parentNode.removeChild($('item'+id+this.id));
	}
	
	this.reset = function(){
		while(this.arr.length>0){
			$('item'+this.arr[this.arr.length-1]['id']+this.id).parentNode.removeChild($('item'+this.arr[this.arr.length-1]['id']+this.id));
		   	this.arr.remove(this.arr.length-1);
		}
		this.arr = null;
		this.arr = new Array();
	}*/
}

/* 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><br/>' +
							'<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,'search_member_contacts',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 += '&volAudio=40&xmlFile='+obj.xml+'&videoTitle='+obj.title+'&embedURL='+obj.link+'&embedPlayer='+EMBED_PLAYER;
	embed += '" allowscriptaccess="always" allowFullScreen="true" quality="high" name="mymovie" style="" src="'+EMBED_PLAYER+'" type="application/x-shockwave-flash" />';
	return embed;
}
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,'retweet',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);
}

/* LEVELBOX */
var LevelBoxInstance = null;
function getLevelBoxInstance(){
	return LevelBoxInstance;
}
var LevelBox = function(options){
	if(LevelBoxInstance!=null) return null;
	LevelBoxInstance = this;
	var _this = this;
	this.defaults = {  
	  	fadeInSpeed: 250,  
	  	fadeOutSpeed: 250,
		TimeToFade: 1000.0,
	  	overlayOpacity: 0.8,
		topDownMargin: 60,
		rightLeftMargin: 40
  	};
	this.initialized = false;
	this.screenWidth = clientWidth() - this.defaults.rightLeftMargin;
	this.screenHeight = clientHeight() - this.defaults.topDownMargin - 30;
	this.open = false;
	this.currentImg = null;
	this.currentImgNode = null;
	this.options = options;
	this.containerDiv = null;
	this.init = function(){
		if(this.initialized) return;
		this.initialized = true;
		this.setupWindow();
		this.setupImages();
	}
	this.setupWindow = function(){
		var _this = this;
		var html =
		'<div id="levelb-overlay"></div>' +
		'<div id="levelb-wrapper">' +
			'<div id="levelb-title">' +
				'<div id="levelb-title-inner"></div>' +
			'</div>' +
			'<div id="levelb-wrapper-inner">' +
				'<div id="levelb-body">' +
					'<div id="levelb-body-inner"></div>' +
					'<div id="levelb-loading">' +
						'<div id="levelb-loading-inner"><span>cargando</span></div>' +
					'</div>' +
				'</div>' +
			'</div>' +
			'<div id="levelb-info">' +
				'<div id="levelb-info-inner">' +
					'<div id="levelb-counter"></div>' +
					'<div id="levelb-nav">' +
						'<a title="Cerrar" id="levelb-nav-close"></a>' +
					'</div>' +
					'<div style="clear: both;"></div>' +
				'</div>' +
			'</div>' +
		'</div>';
		var newNode = document.createElement('div');
		newNode.id = 'levelb-container';
		newNode.innerHTML = html;
		var body = document.getElementsByTagName("body")[0];
		var lastElement = body.childNodes[body.childNodes.length-1];
		insertAfter(newNode, lastElement);
		this.containerDiv = newNode;
		this.containerDiv.overlayDiv = $('levelb-overlay');
		this.containerDiv.overlayDiv.style.opacity = '0';
		this.containerDiv.wrapperDiv = $('levelb-wrapper');
		this.containerDiv.wrapperDiv.titleDiv = $('levelb-title-inner');
		this.containerDiv.wrapperDiv.bodyDiv = $('levelb-body');
		this.containerDiv.wrapperDiv.bodyDiv.imageDiv = $('levelb-body-inner');
		this.containerDiv.wrapperDiv.bodyDiv.loadingDiv = $('levelb-loading');
		this.containerDiv.wrapperDiv.closeBtn = $('levelb-nav-close');
		addEvent(this.containerDiv.wrapperDiv.closeBtn,'click',function(){
			_this.closeLevelBox();
		});
		addEvent(window,'resize',function(){
			_this.resizeWindowHandler();
		});
	}
	this.setupImages = function(){
		var linksx = document.getElementsByTagName('a');
		for(var i=0,length=linksx.length;i<length;i++){
			if(linksx[i].rel == "levelbox"){
				addEvent(linksx[i],'click',function(e){
					_this.openLevelBox(e);
				});
			}
		}
	}
	this.openLevelBox = function(e){
		if(this.open)
			return;
		this.open = true;
		var _this = this;
		var target = getTarget(e);
		if (target.nodeName == 'IMG') target = target.parentNode;
		var url = target.href;
		var title = target.title;
		this.containerDiv.wrapperDiv.style.width = '300px';
		this.containerDiv.wrapperDiv.style.height = '150px';
		this.containerDiv.wrapperDiv.style.visibility = 'visible';
		this.centerDiv(300,150,this.containerDiv.wrapperDiv);
		this.containerDiv.wrapperDiv.bodyDiv.loadingDiv.display = 'block';
		fade(this.containerDiv.overlayDiv.id,0.8,250);
		this.containerDiv.style.display = 'block';
		this.containerDiv.style.visibility = 'visible';
		var img = new Image();
		img.onload = function(){
			var width = img.width;
			var height = img.height;
			var newSize = scaleSize(_this.screenWidth,_this.screenHeight,width, height);
			width  = newSize[0];
			height = newSize[1];
			var imgDiv = _this.containerDiv.wrapperDiv.bodyDiv.imageDiv;
			while(imgDiv.firstChild)
				imgDiv.removeChild(imgDiv.firstChild); 
			var newImg = $c('img');
			newImg.style.width = width+'px';
			newImg.style.height = height+'px';
			newImg.style.opacity = '0';
			newImg.id = 'levelb-image';
			newImg.src = img.src;
			_this.containerDiv.wrapperDiv.style.width = width+'px'; 
			_this.containerDiv.wrapperDiv.style.height = height+'px';
			imgDiv.appendChild(newImg);
			_this.containerDiv.wrapperDiv.bodyDiv.loadingDiv.style.display = 'none';
			fade(newImg.id,1,500);
			_this.containerDiv.wrapperDiv.titleDiv.innerHTML = title;
			_this.centerDiv(width,height,_this.containerDiv.wrapperDiv);
			_this.currentImgNode = newImg;
		}
		img.src = url;
		this.currentImg = img;
	}
	this.centerDiv = function(w,h,div){
		var left = parseInt((this.screenWidth/2) - (w/2) + 20);
    	var top = parseInt((this.screenHeight/2) - (h/2) + 15);
		div.style.left = left+'px';
		div.style.top = top+'px';
	}
	this.closeLevelBox = function(){
		if(!this.open) return;
		this.open = false;
		fade(this.currentImgNode.id,1,250);
		fade(this.containerDiv.overlayDiv.id,0.8,250);
		setTimeout("getLevelBoxInstance().resetLevelBox()",350);
	}
	this.resetLevelBox = function(){
		this.containerDiv.wrapperDiv.style.visibility = 'hidden';
		this.containerDiv.style.display = 'none';
		this.containerDiv.style.visibility = 'hidden';
		var imgDiv = this.containerDiv.wrapperDiv.bodyDiv.imageDiv;
		while(imgDiv.firstChild)
			imgDiv.removeChild(imgDiv.firstChild);
		this.containerDiv.wrapperDiv.bodyDiv.loadingDiv.style.display = 'block';
		this.containerDiv.wrapperDiv.titleDiv.innerHTML = '';
	}
	this.resizeWindowHandler = function(){
		this.screenWidth = clientWidth() - this.defaults.rightLeftMargin;
		this.screenHeight = clientHeight() - this.defaults.topDownMargin - 20;
		if(this.open){
			this.resizeLevelBox();
		}
	}
	this.resizeLevelBox = function(){
		var width = this.currentImg.width;
		var height = this.currentImg.height;
		var newSize = scaleSize(this.screenWidth,this.screenHeight,width,height);
		width  = newSize[0];
		height = newSize[1];
		this.currentImgNode.style.width = width+'px';
		this.currentImgNode.style.height = height+'px';
		this.containerDiv.wrapperDiv.style.width = width+'px'; 
		this.containerDiv.wrapperDiv.style.height = height+'px';
		this.centerDiv(width,height,this.containerDiv.wrapperDiv);
	}
};
/* FIN LEVELBOX */

function fade(eid,maxOp,timeToFade){
	var element = $(eid);
	if (element == null) 
		return;
	element.TimeToFade = (!isNaN(timeToFade)) ? timeToFade : 1000.0;
	element.MaxOp = (!isNaN(maxOp)) ? maxOp : 1;
	if (element.FadeState == null) {
		if (element.style.opacity == null || element.style.opacity == '' || element.style.opacity == ''+element.MaxOp+'') {
			element.FadeState = 2;
		} else { element.FadeState = -2; }
	}
	if (element.FadeState == 1 || element.FadeState == -1) {
		element.FadeState = element.FadeState == 1 ? -1 : 1;
		element.FadeTimeLeft = element.TimeToFade - element.FadeTimeLeft;
	} else {
		element.FadeState = element.FadeState == 2 ? -1 : 1;
		element.FadeTimeLeft = element.TimeToFade;
		setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
	}
}
function animateFade(lastTick, eid){
	var curTick = new Date().getTime();
	var elapsedTicks = curTick - lastTick;
	var element = $(eid);
	if (element.FadeTimeLeft <= elapsedTicks) {
		element.style.opacity = element.FadeState == 1 ? ''+(element.MaxOp)+'' : '0';
		element.style.filter = 'alpha(opacity = ' +
		(element.FadeState == 1 ? ''+((element.MaxOp)*100)+'' : '0') +
		')';
		element.FadeState = element.FadeState == 1 ? 2 : -2;
		return;
	}
	element.FadeTimeLeft -= elapsedTicks;
	var newOpVal = element.FadeTimeLeft / element.TimeToFade;
	if (element.FadeState == 1)
		newOpVal = 1 - newOpVal;
	
	newOpVal = Math.min(element.MaxOp,newOpVal);
	element.style.opacity = newOpVal;
	element.style.filter = 'alpha(opacity = ' + (newOpVal * 100) + ')';
	setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}
function scaleSize(maxW, maxH, currW, currH){
	var ratio = currH / currW;
	if(currW >= maxW){
		currW = maxW;
		currH = currW * ratio;
	}
	if(currH >= maxH){
		currH = maxH;
		currW = currH / ratio;
	}
	return [currW, currH];
}

/* EDITOR */
function edTag(el,tag,param){
	var selText = '';
	var newText = '';
	if (el.setSelectionRange){
		selText = el.value.substring(el.selectionStart,el.selectionEnd);
	}else{
		selText = document.selection.createRange().text;
	}
	switch(tag){
		case 'levelup':
		case 'youtube':
			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]';
				}
			}
			break;
		case 'img':
			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;
		default:
			if (param){
				newText = '['+tag+'='+param+']'+selText+'[/'+tag+']';
			}else{
				newText = '['+tag+']'+selText+'[/'+tag+']';
			}
			break;
	}
	if (newText != '') {
		if (el.setSelectionRange){
			el.value = el.value.substring(0,el.selectionStart) + newText + el.value.substring(el.selectionEnd,el.value.length);
		}else{
			document.selection.createRange().text = newText;
		}
	}
	return false;
}
function makeEd(name,settings){
    var editor = $(name);
	var ul = $c('ul');
	var css = $c('style');
	css.type = 'text/css';
	css.innerHTML = '.edHdr { height: 22px; margin: 0; padding: 0; list-style: none; }';
	css.innerHTML = '.edHdr a { float: left; margin: 3px; outline: none; background-image: url(/libs/templates/images/bbcodes.png); width: 16px; height: 16px; }';
	ul.className = 'edHdr';
	ul.innerHTML = '';
	if (typeof settings != 'undefined'){
		for (tag in settings.buttons){
			switch(settings.buttons[tag]){
				case '|':
					css.innerHTML += '.edHdr .edSep { float: left; height: 16px; border-left: 1px solid #ccc; margin: 3px; }';
					ul.innerHTML += '<li><span class="edSep"></span></li>';
					break;
				case 'b':
					css.innerHTML += '.edHdr a.edB { background-position: 0 -48px; }';
					ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'b\');return false;" class="edB" title="Bold"></a></li>';
					break;
				case 'i':
					css.innerHTML += '.edHdr a.edI { background-position: 0 -64px; }';
					ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'i\');return false;" class="edI" title="Italic"></a></li>';
					break;
				case 'u':
					css.innerHTML += '.edHdr a.edU { background-position: 0 -189px; }';
					ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'u\');return false;" class="edU" title="Underline"></a></li>';
					break;
				case 'center':
					css.innerHTML += '.edHdr a.edC { background-position: 0 -15px; }';
					ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'center\');return false;" class="edC" title="Texto centrado"></a></li>';
					break;
				case 'youtube':
					css.innerHTML += '.edHdr a.edYT { 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 'levelup':
					css.innerHTML += '.edHdr a.edLU { background: url(/app/templates/default/images/levelup.gif); }';
					ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'levelup\');return false;" class="edLU" title="Video de LevelUp"></a></li>';
					break;
				case 'img':
					css.innerHTML += '.edHdr a.edIMG { background-position: 0 -127px; }';
					ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'img\');return false;" class="edIMG" title="Insertar Imágen"></a></li>';
					break;
				case 'url':
					css.innerHTML += '.edHdr a.edURL { background-position: 0 -143px; }';
					ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'url\');return false;" class="edURL" title="Insertar URL"></a></li>';
					break;
				case 'juego':
					css.innerHTML += '.edHdr a.edGame { background-position: 0 -240px; }';
					ul.innerHTML += '<li><a href="#" onclick="edTag($(\''+name+'\'),\'juego\');return false;" class="edGame" title="Insertar Enlace a Juego"></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+'\'),\'levelup\');return false;" class="edLU" title="Video de LevelUp"></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>';
	}
	editor.parentNode.insertBefore(css,editor);
	editor.parentNode.insertBefore(ul,editor);
}
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;
	};
}
/* FIN EDITOR */