function $(id) { return document.getElementById(id); }
String.prototype.substr_count = function(s) { var p = 0, c = 0; while ((p = this.indexOf(s, p)) >= 0) { c++; p++; } return c; };
String.prototype.basename = function() { return this.substr(this.lastIndexOf('/') + 1); };
String.prototype.trim = function() { return this.replace(/^\s+/g, '').replace(/\s+$/g, ''); };
String.prototype.explode = function(s, c) {
	if (c == undefined) return this.split(s);
	var l = this.split(s);
	for (var n = l.length - 2; n >= c - 1; n--) l[n] += s + l[n + 1];
	l.length = c;
	return l;
};

function getDistTime(t1, t2, levels) {
	if (levels === undefined) levels = 2;
	if (t2 === undefined) t2 = (new Date()).getTime();
	var time = Math.abs(t2 - t1);
	var list = [
		[365*24*60*60, 'a&ntiled;o', 'a&ntiled;os'],
		[30*24*60*60, 'mes', 'meses'],
		[7*24*60*60, 'semana', 'semanas'],
		[24*60*60, 'd&iacute;a', 'd&iacute;as'],
		[60*60, 'hora', 'horas'],
		[60, 'minuto', 'minutos'],
		[1, 'segundo', 'segundos'],
		[0, '', '']
	];
	
	var s = [];
	
	for (var n = 0; n < list.length; n++) { var c = list[n];
		var count = Math.floor(time / c[0]);
		
		if (count == 0) continue;

		s.push(count + ' ' + ((count == 1) ? c[1] : c[2]));
		time %= c[0];
		
		if (time <= 0) break;
		if (--levels <= 0) break;
	}
	
	if (t2 == t1) return 'ahora mismo';
	
	var ret = ((t2 - t1) > 0) ? 'hace ' : 'dentro de ';
	
	for (var n = 0; n < s.length; n++) {
		if (n != 0) ret += (n == s.length - 1) ? ' y ' : ', ';
		ret += s[n];
	}
	
	return ret;
};

function processSearchSubmit(form) {
	var text = form.search.value;
	document.location.href = '/encontrar/' + text + '.php';
	return false;
}

var CategoryListTimerList = {};
var CategoryListLastVisible;
var CategoryListWidth = 220;
var CategoryListHeight = 90;

function getPosition(obj) {
	var top = obj.offsetTop, left = obj.offsetLeft;
	while (obj.offsetParent) if (obj = obj.offsetParent) { top += obj.offsetTop; left += obj.offsetLeft; }
	return  { 'left' : left, 'top' : top };
}

// Obtenemos el objeto de Ajax
function getAjaxObject() {
	var xmlhttp;

	try {
		xmlhttp = new XMLHttpRequest();
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
			} catch (e) {
				xmlhttp = undefined;
			}
		}
	}

	return xmlhttp;
}

// Obtenemos los datos de una direcci??, al terminar llamamos a una
// funci??allback.
function httpGetData(url, callback, relative) {
	var xmlhttp = getAjaxObject();
	
	if (relative === undefined || relative) url = 'http://' + window.location.host + '/' + url;

	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && callback) callback(xmlhttp.responseText, xmlhttp.status);
	};
	
	try {		
		xmlhttp.open('GET', url, true);
		xmlhttp.send('');
	} catch (e) {
		alert('Error al abrir url: ' + url + "\n" + String(e));
	}
};

function httpPostData(url, data, callback, relative) {
	var xmlhttp = getAjaxObject();

	if (relative === undefined || relative) url = 'http://' + window.location.host + '/' + url;

	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && callback) callback(xmlhttp.responseText, xmlhttp.status);
	};
	
	xmlhttp.open('POST', url, true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
	xmlhttp.setRequestHeader("Content-length", data.length);
	xmlhttp.setRequestHeader("Connection", "close");	
	xmlhttp.send(data);
};

function httpGetJson(url, callback) {
	httpGetData(url, function(cdata) {
		var data = undefined;
		try {
			eval('data=' + cdata + ';');
		} catch (e) {
			alert('Invalid json: ' + cdata + "\n" + String(e));
		}
		if (callback) callback(data);
	});
};

function httpPostJson(url, data, callback, nocache) {
	//if (nocache) url += '&time=' + (new Date()).getTime();
	//alert(1);

	httpPostData(url, data, function(cdata) {
		var data = undefined;
		try {
			eval('data=' + cdata + ';');
		} catch (e) {
			alert('Invalid json: ' + cdata + "\n" + String(e));
		}
		if (callback) callback(data);
	});
};

// Realizamos una acci?? mostramos el resultado mediante un alert
function performActionAndShow(action, params) {
	httpGetData('opajax.php?action=' + action + '&' + params, alert);
}

// Validamos un email
function validateEmail(email) {
	var re = /^[a-z0-9!#$%&*+-=?^_`{|}~]+(\.[a-z0-9!#$%&*+-=?^_`{|}~]+)*@([-a-z0-9]+\.)+([a-z]{2,3}|info|arpa|aero|coop|name|museum)$/i;
	if (typeof(email) != 'string') return false;
	return re.test(email);
} validate_email = validateEmail;

var cookie = {};

// Definimos una cookie
cookie.set = function(name, value, expires, path, domain, secure) {
	var domain = document.location.host;
	domain = (domain.substr_count('.') >= 2) ? ('.' + domain.explode('.', 2)[1]) : ('.' + domain);
	
	document.cookie = 
		name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "/") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "")
	;
}

// Definimos una cookie que no expira
cookie.setForever = function(name, value) {
	cookie.set(name, value, new Date((new Date()).getFullYear() + 10, 01, 01), '/');
}

// Obtenemos una cookie
cookie.get = function(name) {
	var dc = document.cookie;
	var prefix = name + "=";

	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);

	if (end == -1) end = dc.length;

	return unescape(dc.substring(begin + prefix.length, end));
}

// Borramos una cookie
cookie.remove = function(name, path, domain) {
	if (!cookie.get(name)) return;
	document.cookie = (
		name + "=" +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT"
	);
}

function getConnectionList() {
	return {
		'56 kbps'   : 56000   ,
		'128 Kbps'  : 128000  ,
		'512 Kbps'  : 512000  ,
		'1 Mbps'    : 1024000 ,
		'2 Mbps'    : 2048000 ,
		'3 Mbps'    : 3072000 ,
		'4 Mbps'    : 4096000 ,
		'6 Mbps'    : 6144000 ,
		'20 Mbps'   : 20480000
	};
} get_connection_list = getConnectionList;

//function get_connection_list() { return getConnectionList(); }

// Obtenemos el tiempo necesario para descargar el archivo
function getTime(size, speed) { return (size * 8) / speed; };
get_time = getTime;

// Obtenemos el texto en horas, minutos y segundos
function getTimeText(time) {
	var div = 3600, ctime = Math.ceil(time), value;
	var ret = '';
	while (true) {
		value = parseInt(ctime / div).toString(); ctime %= div;
		if (value.length == 1) value = '0' + value;
		ret += value + ':';
		if (div == 1) break; div /= 60;
	}
	return ret.substr(0, ret.length - 1);
} get_time_text = getTimeText;

// Enfocamos la barra de b?da
function focusevent() {
	var searchobj = document.getElementById('TopSearch');
	if (!searchobj) searchobj = document.getElementById('fullsearch');
	if (!searchobj) return;
	//searchobj.focus();
	//searchobj.select();
}

function TopLoginSwap() {
	if ($('TopLostPassword').style.display != 'none') {
		$('TopLoginForm').style.display    = 'inline';
		$('TopLostPassword').style.display = 'none';
		$('TopLoginUser').focus();
	} else {
		$('TopLoginForm').style.display    = 'none';
		$('TopLostPassword').style.display = 'inline';
	}
}

function getOS() {
	function UA(v) { return (navigator.userAgent.indexOf(v) != -1); }
	function AV(v) { return (navigator.appVersion.indexOf(v) != -1); }

	if (UA('NT 6'  )) return 'Windows Vista';
	if (UA('NT 5.1')) return 'Windows XP';
	if (AV('NT'    )) return 'Windows NT';
	if (UA('NT 5.2')) return 'Windows Server 2003';
	if (UA('NT 5'  )) return 'Windows 2000';
	if (UA('Win') && UA('98')) return 'Windows 98';
	if (UA('Win') && UA('95')) return 'Windows 95';
	if (AV('SunOS' )) return 'SunOS';
	if (AV('Linux' )) return 'Linux';
	if (UA('Mac'   )) return 'Macintosh';
	if (AV('HP'    )) return 'HP-UX';
	if (UA('IRIX'  )) return 'Irix';
	if (navigator.appName == "WebTV Internet Terminal") return 'WebTV';
	if (AV('16'    )) return "Windows 3.1";
	
	return 'Unknown';
}

function portableAttachEvent(nevent, callback) {
	(document.all) ?
		window.attachEvent('on' + nevent, callback) :
		window.addEventListener(nevent, callback, true)
	;
}

function loadScript(url, callback) {
	var s = document.createElement('script');
	if (callback !== undefined)
	s.onload = callback;
	s.onreadystatechange = function(v) { if (s.readyState == 'loaded') s.onload(); };
	s.type = 'text/javascript';
	s.src = url;
	document.getElementsByTagName('head')[0].appendChild(s);
}

portableAttachEvent('load', focusevent);
