/* funciones genéricas */

function radomNumber() {
	var randomnumber = Math.floor(Math.random() * 999999);
	return randomnumber;
}

function redirect(url) {
	window.location=url;
} 

function trim(text) {
	return text.replace(/^(\s|\&nbsp;)*|(\s|\&nbsp;)*$/g,"");
}

function translate(s) {
	if (typeof(i18n)!='undefined' && i18n[s]) {
		return i18n[s];
	}
	return s;
}

/* gestion de referencias a comentario */

function loadCommentReference(objectType,objectId,position,parentId) {
	var url = "/respuesta/" + objectType + "/" + objectId + "/" + position;
	var posParent = $("#comment" + parentId).position();
	var heightParent = $("#comment" + parentId).height();
	var topPosition = posParent.top + heightParent + 20;
	$("#commentReference").mouseout(function() {
		$(this).html("");
	});
	$("#commentReference").css({'top': topPosition, 'border': '1px solid #CCC'});
	$("#commentReference").html("<p class='popRulaContent'><img src='/static/images/loader.gif' /><br />"+translate("Cargando...")+"</p>");
	$("#commentReference").load(url);
}

function removeCommentReference(){
	$("#commentReference").css('border','none');
	$("#commentReference").html("");
	$("#commentReference").addClass('loadHiddenContent');
}

/* gestión de condiciones */

function conditionsAccepted(form) {
	var conditionsAccepted = form['accepted'];
	if (!conditionsAccepted.checked){
		var errors = document.getElementById("conditionsErrors");
		errors.innerHTML = translate("Debes aceptar las condiciones de uso");
		return false;
	}
	return true;
}

function clearConditionsErrors() {
	var errors = document.getElementById("conditionsErrors");
	errors.innerHTML = "";
}

/* gestión de watermarks */

function clearField(element) { // TODO: revisar si se sigue usando
	element.value = "";
	element.onfocus = "";
}

function checkFields(form) {
	var username = form["j_username"];
	var password = form["j_password"];
	if (username.onfocus != "") {
		//username.value = "";
	}
	if (password.onfocus != "") {
		//password.value = "";
	}
}

/* gestión del editor */

function attachEditor(id) {
	if (!tinyMCE.get(id)) {
		tinyMCE.execCommand("mceAddControl", false, id);
	}
}

function dettachEditor(id) {
	if (tinyMCE.get(id)) {
		tinyMCE.execCommand("mceRemoveControl", false, id);
	}
}

/* gestión de popups */

function rulaPop(){
	var overlay = document.createElement("div");
	var overlay_bg = document.createElement("div");
	var popup = document.createElement("div");
	popup.id = "popRula";
	overlay.id = "overlayRula";
	overlay_bg.id = "overlayRula_bg";
	overlay.appendChild(popup);
	document.body.appendChild(overlay_bg);
	document.body.appendChild(overlay);
	$("#" + popup.id).addClass("popupRula");
	$("#" + overlay.id).addClass("baseRula");
	$("#" + overlay_bg.id).addClass("baseRula_bg");
	$("#" + popup.id).html("<p class='popRulaContent'><img src='/static/images/loader.gif' /><br />"+translate("Cargando...")+"</p>");
	var popheight = 100;
	var popwidth = 50;
	var overheight =  document.getElementById("overlayRula").offsetHeight;	
	var overwidth = document.getElementById("overlayRula").offsetWidth;
	popup.style.top = ((overheight - popheight) / 2) + "px";
	popup.style.left = ((overwidth - popwidth) / 2) + "px";
}

function closeRulaPop(){
	var overlay = document.getElementById("overlayRula");
	var overlay_bg = document.getElementById("overlayRula_bg");
	document.body.removeChild(overlay);
	document.body.removeChild(overlay_bg);
}

function openPopup(width, type) {
	var overlay = document.createElement("div");
	var overlay_bg = document.createElement("div");
	var popup = document.createElement("div");
	if (!type) {
		popup.id = "popup";
		overlay.id = "overlay";
		overlay_bg.id = "overlay_bg";
	} else {
		popup.id = type;
		overlay.id = type + "Overlay";
		overlay_bg.id = type + "Overlay_bg";
	}
	popup.style.width = width + "px";
	overlay.appendChild(popup);
	document.body.appendChild(overlay_bg);
	document.body.appendChild(overlay);
	$("#" + popup.id).addClass("popup");
	$("#" + overlay.id).addClass("overlay");
	$("#" + overlay_bg.id).addClass("overlay_bg");
}

function fixPopup(type){
	if (!type) {
		var popup = document.getElementById("popup");
		var popheight = popup.offsetHeight;
		var popwidth = popup.offsetWidth;
		var overheight =  document.getElementById("overlay").offsetHeight;	
		var overwidth = document.getElementById("overlay").offsetWidth;
	} else {
		var popup = document.getElementById(type);
		var popheight = popup.offsetHeight;
		var popwidth = popup.offsetWidth;
		var overheight =  document.getElementById(type + "Overlay").offsetHeight;
		var overwidth = document.getElementById(type + "Overlay").offsetWidth;
	}	
	
	popup.style.marginTop = ($(document).scrollTop() + ((overheight - popheight) / 2)) + "px";
	popup.style.left = ((overwidth - popwidth) / 2) + "px";
}

function setPopAbsolute(){
	var popup = document.getElementById("popup");	
	var popup = document.getElementById("popup");
	var popheight = popup.offsetHeight;
	var popwidth = popup.offsetWidth;
	var overwidth = document.getElementById("overlay").offsetWidth;
	popup.style.position="absolute";
	popup.style.left = ((overwidth - popwidth) / 2) + "px";
	popup.style.top = 100 + "px";
}
function setPopRelative(){
	var popup = document.getElementById("popup");	
	var popup = document.getElementById("popup");
	var popheight = popup.offsetHeight;
	var popwidth = popup.offsetWidth;
	var overwidth = document.getElementById("overlay").offsetWidth;
	popup.style.position="relative";
	popup.style.margin = "0 auto";
	popup.style.top = 100 + "px";
}

function closePopup(type) {
	if (isPopupOpen()) {
		var overlay;
		var overlay_bg;
		if (!type) {
			overlay = document.getElementById("overlay");
			overlay_bg = document.getElementById("overlay_bg");
		} else {
			overlay = document.getElementById(type + "Overlay");
			overlay_bg = document.getElementById(type + "Overlay_bg");
		}
		document.body.removeChild(overlay);
		document.body.removeChild(overlay_bg);
		if (!hasPostFinished()) { // para destruir el div de un formulario en la capa principal
			enableSubmit(document.getElementById("post").parentNode.id);
			hideState();
			removeDiv();
		}
	}
}

function closeLiveMessage(){
	$('.alertMessage').animate({bottom : '10px',opacity: 0},500);
}

function hideAfter(typeId,seconds){
	setTimeout(function() {		
		if(typeId == 'alertMessage'){
			closeLiveMessage();
		}
	}, seconds*1000);
}

function showState(container) {
	$("#" + container.id + " :submit").addClass("submit_loading");
}

function hideState() {
	$(":submit").removeClass("submit_loading");
}

function disableSubmit(containerId) {
	$("#" + containerId + " :submit").attr("disabled", true);
}

function enableSubmit(containerId) {
	$("#" + containerId + " :submit").attr("disabled", false);
}

function loadSending() {
	$("#sending").load("/sending/popup", function() {
		fixPopup("sending");
	});
}

function loadInfo(code) {
	$("#info").load("/info/popup?message=" + code, function() {
		fixPopup("info");
	});
}

function loadUrl(url) {
	showLoadingCursor();
	$("#popup").load(url, function() {
		fixPopup();
		hideLoadingCursor();
	});
}

function loadUrlPromo(url) {
	$("#popup2").load(url, function() {
		fixPopup("popup2");
	});
}

function loadUrlPop(url) {
	$("#popup").load(url);
}

/* abrir ventana (para shareBox de twitter) */

function wopen(url, name, w, h){
  // Fudge factors for window decoration space.
  // In my tests these work well on all platforms & browsers.
  w += 32;
  h += 96;
  wleft = (screen.width - w) / 2;
  wtop = (screen.height - h) / 2;
  // IE5 and other old browsers might allow a window that is
  // partially offscreen or wider than the screen. Fix that.
  // (Newer browsers fix this for us, but let's be thorough.)
  if (wleft < 0) {
    w = screen.width;
    wleft = 0;
  }
  if (wtop < 0) {
    h = screen.height;
    wtop = 0;
  }
  var win = window.open(url,
    name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=no, menubar=no, ' +
    'status=no, toolbar=no, scrollbars=no, resizable=no');
  // Just in case width and height are ignored
  win.resizeTo(w, h);
  // Just in case left and top are ignored
  win.moveTo(wleft, wtop);
  win.focus();
}

/* gestión del botón +1 */
function plusOne(plusOne){
	console.debug("+1: " + plusOne.state + " de " + plusOne.href);
	var state = plusOne.state;
	var href = plusOne.href;
	if (state == 'on'){
	 var url = "/google/plusOne?url=" + href;
	 $.get(url);
	}
	else if (state == 'off'){
	 var url = "/google/minusOne?url=" + href;
	 $.get(url);
	}
	   
}

/* gestión del calendario */

function openCalendar(daysToClose) { // si sólo se usa en las encuestas, está bien así
	openPopup(200);
	if (!daysToClose){
		loadUrl("/calendar?from=today");
	} else {
		loadUrl("/calendar?from=today&days=" + daysToClose );
	}
}

function reloadCalendar(month, year, min, max) {
	loadUrl("/calendar/reload?month=" + month + "&year=" + year + "&min=" + min + "&max=" + max);
}

function setDate(day, month, year) {
	var expirationDate = document.getElementById("expirationDate");
	expirationDate.value = normalize(day, 2) + "/" + normalize(month, 2) + "/" + normalize(year, 4);
	closePopup();
}

function normalize(value, length) {
	for (var i = 0; i < length - value.toString().length; i++) {
		value = "0" + value;
	}
	return value;
}

/* gestión de referencias */

function loadRefPopup(url) {
	$("#popup").load(url, function() {
		var link_text = document.getElementById("link_text");
		link_text.focus();
		fixPopup();
	});
}

/*function processLink() {
	var editor = tinyMCE.activeEditor;
	var text = editor.getContent();
	var space = trim(text).lastIndexOf(" ");
	var from;
	if (space != -1) {
		from = space;
	} else {
		from = 3; // <p>
	}
	var to = text.lastIndexOf("</p>");
	var word = text.substring(from, to);
	while (word.match(/\&nbsp;/i)) {
		
	}
	if (word.match(/\.{3}$/)) {
		to -= 3;
		word = word.substring(0, word.length -3);
	}
	if (word.match(/\W$/)) {
		to -= 1;
		word = word.substring(0, word.length -1);
	}
	var enter = word.indexOf("</p>");
	if (enter != -1) {
		if (word.match(/\&nbsp;/i)) {
			to -= word.length - enter;
			word = word.substring(0, enter);			
		} else {
			from += word.indexOf("<p>") + 3;
			word = word.substring(from);
		}
	}
	alert(word);
}*/

function tryLink() {
	var link_url = document.getElementById("link_url").value;
	if (link_url.match(/^https?:\/\//i)) {
		var start = link_url.indexOf("//") + 2;
		link_url = link_url.substring(start);
	}
	window.open("http://" + link_url, "_blank");
}

function checkLinkText(text, url) {
	return url.length == 0 || trim(text).length > 0;
}

function checkLinkUrl(url) {
	return url.match(/^(https?:\/\/)?\w+([\.\-]\w+)*\.\w{2,4}(\:\d+)*([\/\.\-\?\&\%\#\=]\w+)*\/?$/i);
}

function innerImagenLink() {
	var link_text = document.getElementById("imageCategory").value;
	if (link_text.length > 0) {
		var link = "<img src=\"http://6cero.com/" + link_text +"\" />";
		setLink(link);
	} else {
		finish();
	}
}

function createOutterLink() {
	var link_text = document.getElementById("link_text").value;
	var link_url = document.getElementById("link_url").value;
	if (checkLinkText(link_text, link_url)) {
		if (link_url.length > 0) {
			if (checkLinkUrl(link_url)) {
				if (link_url.match(/^https?:\/\//i)) {
					var start = link_url.indexOf("//") + 2;
					link_url = link_url.substring(start);
				}
				var link = "<a href=\"http://" + link_url + "\" target=\"_blank\">" + link_text + "</a>";
				setLink(link);	
			} else {
				setLinkUrlError();
			}
		} else {
			finish();
		}
	} else { // si hay url, pero no texto...
		setLinkTextError();
	}
}

function createInnerLink() {
	var link_text = document.getElementById("link_text").value;
	var link_url = document.getElementById("link_url").value;
	if (checkLinkText(link_text, link_url)) {
		if (link_url.length > 0) {
			var link = "<a href=\"" + link_url + "\">" + link_text + "</a>";
			setLink(link);
		} else {
			finish();
		}
	} else { // si hay url, pero no texto...
		setLinkTextError();
	}
}

function setInnerLink(text, url) {
	var link_text = document.getElementById("link_text");
	var link_url = document.getElementById("link_url");
	if (trim(link_text.value).length == 0) {
		link_text.value = text;
	}
	link_url.value = url;
}

function setLinkTextError() {
	var linkTextErrors = document.getElementById("linkTextErrors");
	linkTextErrors.innerHTML = translate("Introduce aquí el texto que quieras enlazar");
}

function setLinkUrlError() {
	var linkUrlErrors = document.getElementById("linkUrlErrors");
	linkUrlErrors.innerHTML = translate("URL incorrecta");
}

function clearLinkTextErrors() {
	var linkTextErrors = document.getElementById("linkTextErrors");
	linkTextErrors.innerHTML = "";
}

function clearLinkUrlErrors() {
	var linkUrlErrors = document.getElementById("linkUrlErrors");
	linkUrlErrors.innerHTML = "";
}

function setLink(link) {
	var editor = tinyMCE.activeEditor;
	editor.selection.setContent(link);
	finish();
}

function finish() {
	var editor = tinyMCE.activeEditor;
	editor.focus();
	closePopup();
}

//EDITOR NEW EDITOR NEW EDITOR NEW EDITOR NEW EDITOR NEW EDITOR NEW
/*NEW ARTICLE VIDEO */ 
function restartVideoForm(){
	iframe = document.getElementById('videoIframe');
	iframe.src = '/upload/video';
	iframe.style.display = "block"; 
	$('#buttonsPostVideo').hide();
	$('#contentVideo').html('');
	$('#youtube').attr('value','');
	$('#hashVideo').attr('value','');
	$('#embedCode').attr('value','');
}
function restartVideoPollForm(){
	$('#buttonsPollPostVideo').hide();
	$('#imageUploadLink').show();
	$('#contentPollVideo').html('');
	$('#youtube').attr('value','');
	$('#hashVideo').attr('value','');
}
function restartVideoFormPop(){
	iframe = document.getElementById('videoIframe');
	iframe.src = '/upload/video';
	iframe.style.display = "block";
	$('#buttonsPostVideo').hide();
	$('#contentVideo').html('');
	fixPopup();
}
function restartListVideoFormPop(position){
	iframe = document.getElementById('videoIframe');
	iframe.src = '/upload/video?position=' + position;
	iframe.style.display = "block";
	$('#buttonsPostVideo').hide();
	$('#contentVideo').html('');
	fixPopup();
}
function restartImageBasic(){
	$('#imageUploadLink').show();
	$('#buttonsPostImage').hide();
	$('#contentImage').html('');
	$('#originalName').attr('value','');
	$('#hashImage').attr('value','');
	$('#embedCode').attr('value','');
}

function restartMediaList(position){
	$('#mediaUploadLink' + position).show();
	//$('#imageUploadLink' + position).show();
	$('#buttonsPostImage' + position).hide();
	$('#contentImage' + position).html('');
	$('#hashImage' + position).attr('value','');
	//$('#videoUploadLink' + position).show();
	$('#buttonsPostVideo' + position).hide();
	$('#contentVideo' + position).html('');
	$('#originalName' + position).attr('value','');
	$('#youtube' + position).attr('value','');
	$('#hashVideo' + position).attr('value','');
	$('#embedCode' + position).attr('value','');
}


function embedHtmlInText(content, destiny) {
	var finalDestiny = document.getElementById(destiny);
	var contentToEmbed = document.getElementById(content).innerHTML;
	if (content == "contentImage") {
		contentToEmbed = contentToEmbed.replace("_s.jpg", "_m.jpg");
		contentToEmbed = contentToEmbed.replace("leftImaEditor", "rightImaEditor");
	}
	finalDestiny.value = contentToEmbed;
}

function embedListMediaInText() {
	//sacar todos los contentImage y contentVideo y pasarlos a embedCode
	$("div[id^='contentImage']").each(function () {
		var name = $(this).attr("id");
		var position = name.split("contentImage")[1];
		var finalDestiny = document.getElementById("embedCode"+position);
		var contentToEmbed = $(this).html().trim();
		if (contentToEmbed.length > 0){
			contentToEmbed = contentToEmbed.replace("_m.jpg", "_o.jpg");
			contentToEmbed = contentToEmbed.replace("leftImaEditor", "centerImaEditor");
			contentToEmbed = contentToEmbed.replace("leftTextAlign", "centerTextAlign");
			contentToEmbed = contentToEmbed.replace("width=\"200\"", "");
			finalDestiny.value = contentToEmbed;
			console.debug("insertada imagen " + position);
		}
	});
	$("div[id^='contentVideo']").each(function () {
		var name = $(this).attr("id");
		var position = name.split("contentVideo")[1];
		var finalDestiny = document.getElementById("embedCode"+position);
		var contentToEmbed = $(this).html().trim();
		if (contentToEmbed.length > 0){
			contentToEmbed = resizeVideo("insertionContent" + position, 670); //"contentVideo"
			contentToEmbed = contentToEmbed.replace("errorYoutubeMedium","errorYoutubeLarge");
			finalDestiny.value = contentToEmbed;
			console.debug("insertado vídeo " + position);
		}
	});
}

function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

function insertVideoEditor(anchor, divContainer) {
	anchor.onclick = ""; // deshabilitamos el botón
	var ed = tinyMCE.activeEditor, doc = ed.getDoc(), dom = ed.dom, selection = ed.selection;;
	var div = doc.createElement("div");
	div.setAttribute("class", "insertionAdvancedContent");
	var contentVideoOriginalCode = document.getElementById(divContainer).innerHTML;
	contentVideoOriginalCode = contentVideoOriginalCode.replace("insertionContent", "");
	contentVideoOriginalCode = contentVideoOriginalCode.replace("loadHiddenContent", "");
	contentVideoOriginalCode = contentVideoOriginalCode.replace("objectEmbeded", "loadHiddenContent");
	contentVideoOriginalCode = contentVideoOriginalCode.replace("centerTextAlign", "leftTextAlign");
	div.innerHTML = contentVideoOriginalCode;
	restoreBookmark();
	var currentNode = selection.getNode();
	if (tinymce.isWebKit && currentNode.nodeName == "BODY" && selection.isCollapsed()) { // si estamos en Chrome y currentNode es <body>...
		currentNode = selection.getSel().anchorNode;
		if (currentNode.nodeType == 3) { // si el nodo es de texto...
			currentNode = currentNode.parentNode; // seleccionamos el padre
		}
	}
	if (currentNode.nodeName == "BODY") { // si el foco no está en el editor o no hay ningún elemento...
		currentNode = getLastNode(ed); // insertamos el vídeo al final (si no existe nodo, se crea)
		selection.select(currentNode); // seleccionamos el nodo
		selection.collapse(true); // y colocamos el cursor al principio
	}
	var referenceNode = currentNode; // por defecto, el nodo de referencia es el nodo actual
	if (currentNode.nodeName != "P") { // si éste no es un P...
		if (dom.getParent(currentNode, "P")) { // pero estamos dentro de uno...
			referenceNode = dom.getParent(currentNode, "P"); // usamos éste como nodo de referencia
		} else { // si no (por ejemplo, si estamos en un LI)...
			referenceNode = currentNode.parentNode; // cogemos el padre (sea del tipo que sea; por ejemplo, OL o UL)
		}
	}
	if (dom.getParent(currentNode, "BLOCKQUOTE")) { // si estamos dentro de un BLOCKQUOTE...
		referenceNode = dom.getParent(currentNode, "BLOCKQUOTE"); // usamos éste como nodo de referencia
	}
	var parentNode = referenceNode.parentNode;
	parentNode.insertBefore(div, referenceNode);
	setTimeout(function() {
		ed.focus();
		ed.execCommand("mceAutoResize");
		closePopup();
	}, 1250);
}

function insertListVideo(anchor, divContainer, position) {
	anchor.onclick = ""; // deshabilitamos el botón
	
	var buttonsPostVideo = document.getElementById("buttonsPostVideo" + position);
	buttonsPostVideo.style.display = "block";	
	var mediaUploadLink = document.getElementById("mediaUploadLink" + position);
	mediaUploadLink.style.display = "none";
	
	//document.getElementById(divContainer).innerHTML = document.getElementById("insertionContent").innerHTML;
	var div = document.getElementById("insertionContent");
	div.id = "insertionContent" + position; //renombramos insertionContent
	var originalContent = resizeVideo("insertionContent" + position, 200);
	originalContent = originalContent.replace("errorYoutubeLarge","errorYoutubeMedium");
	
	document.getElementById(divContainer).innerHTML = originalContent;
	/*var videoUploadLink = document.getElementById("videoUploadLink" + position);
	videoUploadLink.style.display = "none";
	//quitamos también la subida de imagen para ese elemento
	var imageUploadLink = document.getElementById("imageUploadLink" + position);
	imageUploadLink.style.display = "none"; */
	closePopup();
}

function resizeVideo(divContainer, newWidth){
	console.debug("resizeando video de " + divContainer + " a " + newWidth);
	var originalContent = document.getElementById(divContainer).parentNode.innerHTML;
	var originalWidth = $("#" + originalContent).find("[width]").attr("width");
	var originalHeight = $("#" + originalContent).find("[height]").attr("height");
	var height = originalHeight * newWidth / originalWidth | 0; // entero
	originalContent = originalContent.replace(/width=\"\d+?\"/g, "width=\"" + newWidth + "\"");
	originalContent = originalContent.replace(/height=\"\d+?\"/g, "height=\"" + height + "\"");
	return originalContent;
}

function showPollVideo(anchor, divContainer) {
	anchor.onclick = ""; // deshabilitamos el botón
	var originalContent = resizeVideo(divContainer, 300);
	originalContent = originalContent.replace("errorYoutubeLarge","errorYoutubeMedium");
	document.getElementById("contentPollVideo").innerHTML = originalContent;
	document.getElementById("buttonsPollPostVideo").style.display = "block";
	document.getElementById("imageUploadLink").style.display = "none";
	closePopup();
}

function setNewEditor() {
	var ed = tinyMCE.activeEditor;
	$(".mceToolbar").hide(); // ocultamos la botonera original
    $(".mcePopup").mouseenter(storeBookmark); // almacenamos la posición del cursor cuando abandonamos el área del editor
	var $c = $("#" + tinyMCE.activeEditor.id + "_ifr").contents();
	
	setTimeout(function() {
		$c.find('.optionsVideoEditor').each(function () {
			$(this).children('img').attr('width',670);
		});
		$c.find('.helpRight').each(function () {
			$(this).parent().removeClass('rightImaEditor');
			$(this).parent().addClass('rightImaEditor');
			var widthImaRelated = $(this).prev('img').width();
			$(this).css({"margin-left" : widthImaRelated-292 + 'px'});
		});
		ed.execCommand("mceAutoResize");
		setNewEditorMenu();
	}, 1250);

	$c.delegate(".imageEditor", "mouseenter", function() {
		storeBookmark();
		$(this).children(".optionsImageEditor").css({"position" : "absolute", "display" : "block"});
	});
	$c.delegate(".imageEditor", "mouseleave", function() {
		$(this).children(".optionsImageEditor").css({"position" : "absolute", "display" : "none"});
	});
   
}

function setNewEditorMenu(){
	$("#newmenu").followScroll({"margin": 10});
}

function changeImaEditorStyle(id, position) {
	var ed = tinyMCE.activeEditor;
	var myIFrame = document.getElementById(ed.id + "_ifr");
	var content = myIFrame.contentWindow.document.getElementById(id + "wrap");
	var img = myIFrame.contentWindow.document.getElementById(id + "pic");
	var imageWidth = img.width;
	var contenthelp = myIFrame.contentWindow.document.getElementById(id);
	if (position == "picLeft") {
		content.setAttribute("class", "insertionAdvancedContent imageEditor leftImaEditor");
		contenthelp.setAttribute("class", "optionsImageEditor helpLeft");
	} else if (position == "picRight") {
		content.setAttribute("class", "insertionAdvancedContent imageEditor rightImaEditor");
		contenthelp.setAttribute("class", "optionsImageEditor helpRight");
		if (img.className == "original") {
			contenthelp.style.marginLeft = imageWidth - 292; // es la anchura del div del menu
		} else if (img.className == "large") {
			contenthelp.style.marginLeft = 670 - 292; 
		} else if (img.className == "medium") {
			contenthelp.style.marginLeft = 300 - 292; 
		} else if (img.className == "small"){
			contenthelp.style.marginLeft = 70 - 292; 
		} else{
			contenthelp.style.marginLeft = 300 - 292; 
		}
	} else {
		content.setAttribute("class", "insertionAdvancedContent imageEditor centerImaEditor");
		contenthelp.setAttribute("class", "optionsImageEditor helpCenter");
	}
	setTimeout(function() {
		var widthOriginal = img.offsetWidth; // anchura de la foto
		if (widthOriginal == 670) {
			content.setAttribute("class", "insertionAdvancedContent imageEditor centerImaEditor");
			img.setAttribute("class", "large");
			contenthelp.setAttribute("class", "optionsImageEditor helpCenter");
		}
		ed.focus();
		ed.execCommand("mceAutoResize");
	}, 1250);
}

function changeImaEditorSize(id, size) {
	var ed = tinyMCE.activeEditor;
	var myIFrame = document.getElementById(ed.id + "_ifr");
	var content = myIFrame.contentWindow.document.getElementById(id + "pic");
	if (content) {
		var contentPic = myIFrame.contentWindow.document.getElementById(id + "wrap");
		var contenthelp = myIFrame.contentWindow.document.getElementById(id);
		var baseSrc= content.src.substr(0,content.src.lastIndexOf('_'));
		content.setAttribute("class", size);		
		if (size == 'original') {
			content.src = baseSrc + "_o.jpg";
		} else if (size == 'large') {
			content.src = baseSrc + "_l.jpg";
		} else if (size == 'medium') {
			content.src = baseSrc + "_m.jpg";
		} else {
			content.src = baseSrc + "_s.jpg";
		}
		content.setAttribute("data-mce-src", content.src);
		if (contenthelp.className == 'optionsImageEditor helpRight') {
			if (size == 'original') {
				contenthelp.style.marginLeft = content.width - 292; // la anchura del div del menu
			} else if (size == 'large') {
				contenthelp.style.marginLeft = 670 - 292; 
			} else if (size == 'medium') {
				contenthelp.style.marginLeft = 300 - 292;
			} else {
				contenthelp.style.marginLeft = 70 - 292;
			}
		}		
		setTimeout(function() {
			var widthOriginal = contentPic.offsetWidth; // anchura de la foto
			if (widthOriginal == 670) {
				contentPic.setAttribute("class", "insertionAdvancedContent imageEditor centerImaEditor");
				contenthelp.setAttribute("class", "optionsImageEditor helpCenter");
			}
			if (size == 'original') {
				contenthelp.style.marginLeft = widthOriginal - 292;
			}
			ed.focus();
			ed.execCommand("mceAutoResize");
		}, 1250);
	}
}

function deleteImaEditor(id){
	var ed = tinyMCE.activeEditor;
	var myIFrame = document.getElementById('text_ifr');
	var content = myIFrame.contentWindow.document.getElementById(id + "wrap");
	myIFrame.contentWindow.document.body.removeChild(content);
	setTimeout(function() {
		ed.focus();
		ed.execCommand("mceAutoResize");
	}, 1250);
}

function checkAnonimous(){
	if ($('#anonimousComments1').attr('disabled')){
	    $('#anonimousComments1').attr('disabled','');
	    $('#anonimousComments1').attr('checked','checked');
	}else{
	    $('#anonimousComments1').attr('disabled','disabled');
	    $('#anonimousComments1').attr('checked','');
	}
}

/*	enviar video link youtube */
function sendYoutube(id) {
	var contentInput = document.getElementById(id).value;
	if (contentInput != ""){
		var divFile = document.createElement("div");
		divFile.id = "fileYoutube" + id;
		divFile.style.display = "block";
		divFile.setAttribute("class", "mensYoutube");
		var pFile = document.createElement("p");
		pFile.innerHTML = contentInput;
		var quit = document.createElement("a");
		quit.href = "javascript:;";
		quit.setAttribute("onclick", "hideSent('fileYoutube" + id + "')");
		quit.innerHTML = "&nbsp;" + translate("cambiar");
		divFile.appendChild(pFile);
		divFile.appendChild(quit);
	}
	document.getElementById('mens' + id).style.display = "none";
}

/* gestión de popup de gallery */
function openGallery(type,id) {
	openPopup(800);
	loadUrlPop("/" + type + "/galeria/" + id);
	setPopRelative();
}

/* gestión de popups de info */

function calmDown() {
	openPopup(550, "info");
	loadInfo("INFO_PACIENCIA");
}

function aboutUs() {
	openPopup(550, "info");
	loadInfo("INFO_ABOUT_US");
}

function whatIs() {
	openPopup(550, "info");
	loadInfo("INFO_WHAT_IS_6CERO");
}

function conditions() {
	openPopup(550, "info");
	loadInfo("INFO_CONDITIONS");
}

/* gestión de contenidos de texto */

function limit(maxLength, element, event) {
	var code = event.keyCode;
	if (code != 8 && code != 46 && code != 37 && code != 38 && code != 39 && code != 40) {			
		return element.value.length < maxLength;
	}
}

function count(maxLength, element) {
	var counter = document.getElementById(element.id + "_counter");
	if (element.value.length > maxLength) {
		element.value = element.value.substring(0, maxLength);
	}
	var remaining = maxLength - element.value.length;
	if (remaining == 1) {
		counter.innerHTML = translate("1 carácter restante");
	} else {
		counter.innerHTML = remaining + translate(" caracteres restantes");
	}
}
function count_comment(maxLength, element, target) {
	var counter_id=element.id + '_' + target + "_counter";
	var counter = document.getElementById(counter_id);
	if (element.value.length > maxLength) {
		element.value = element.value.substring(0, maxLength);
	}
	var remaining = maxLength - element.value.length;
	if (remaining == 1) {
		counter.innerHTML = translate("1 carácter restante");
	} else {
		counter.innerHTML = remaining + translate(" caracteres restantes");
	}
}

/* gestión de cookies */

function createCookie(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(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 eraseCookie(name) {
    createCookie(name, "", -1);
}

function areCookiesEnabled() {
    var r = false;
    createCookie("testing", "Hello", 1);
    if (readCookie("testing") != null) {
        r = true;
        eraseCookie("testing");
    }
    return r;
}

/* gestión de localización */

function isHome() {
	var regexp = new RegExp("^//?$");
	return window.location.pathname.match(regexp) != null;
}

function isPage(url) {
	var regexp = new RegExp("^//?" + url + "/");
	return window.location.pathname.match(regexp) != null;
}

function isModule(objectType) {
	if (objectType == "f") //página de ranking
		return false;
	if (objectType == "p") //página de portadas
		return false;
	if (objectType == "oo") //página de onces antiguos
		return false;
	return !isPage(objectType);
}

function isTwito() {
	return isPage("t");
}

function isDataModificationPage() {
	return isPage("modificar\-datos");
}

function isTab(divId) {
	return document.getElementById(divId) != null;
}

/* ocultar y mostrar capas */

function show(div) {
	if (document.getElementById(div)) {
		document.getElementById(div).style.display = "block";
	}
}
function hide(div) { 
	if (document.getElementById(div)) {
		document.getElementById(div).style.display = "none";
	}
}

/* cambiar clase */

function changeClass(div,name) {
	document.getElementById(div).className = name;
}

/* fecha actual */

var muestra;
function makeArray(n) {
	this.length = n;
	for (i = 1; i <= n; i++) {
		this[i] = 0;
	}
	return this;
}

/* cambiar titulo de pagina */
function changeTitle(titulo) {
	document.title = titulo;
}

/* gestor de fichajes */

function rumorSearcher(rumorId){
	var url = "/gestor/fichajes?";
	if (rumorId)
		url += "rumorId=" + rumorId;
	if ($('#searchPlayer').val()){
		url += "&player=" + $('#searchPlayer').val();
	}
	if ($('#searchFrom').val()){
		url += "&fromCategory=" + $('#searchFrom').val();;
	}
	if ($('#searchTo').val()){
		url += "&toCategory=" + $('#searchTo').val();
	}
	window.location.href = url;
}

function signingSearcher(signingId){
	var url = "/gestor/fichajes/editar?signingId=" + signingId;
	if ($('#searchPlayer').val()){
		url += "&player=" + $('#searchPlayer').val();
	}
	if ($('#searchFrom').val()){
		url += "&fromCategory=" + $('#searchFrom').val();;
	}
	if ($('#searchTo').val()){
		url += "&toCategory=" + $('#searchTo').val();
	}
	window.location.href = url;
}

/* buscadores de equipo / jugador para el gestor */
function categorySearcher(){
	var url = "/gestor/categorias/todas";
	if ($('#searchCategory').val()){
		url += "?category=" + $('#searchCategory').val();
	}
	window.location.href = url;
}

function playerSearcher(){
	var url = "/gestor/players/todos";
	if ($('#searchPlayer').val()){
		url += "?player=" + $('#searchPlayer').val();
	}
	window.location.href = url;
}

function playerCategorySearcher(playerId){
	var url = "/gestor/players/usuario?playerId=" + playerId;
	if ($('#categorySearch').val()){
		url += "&categorySearch=" + $('#categorySearch').val();
	}
	window.location.href = url;
}

function twitterCategorySearcher(){
	var url = "/gestor/twitter";
	if ($('#searchCategory').val()){
		url += "?category=" + $('#searchCategory').val();
	}
	window.location.href = url;
}
