function getObj(id)
{
	return document.getElementById(id);
}

function getObjClass(obj)
{
	return obj.className;
}

function setObjClass(obj, cls)
{
	obj.className=cls;
}

function setIdClass(id, cls)
{
	getObj(id).className=cls;
}

function getIdClass(id)
{
	return getObj(id).className;
}

function getObjDivPos(id)
{
	return getObjDivPosRec(id, true);
}


function getObjDivPosRec(id, recurse)
{
	var x=getObj(id).offsetLeft;
	var y=getObj(id).offsetTop;
	
	if (BrowserDetect.browser=="Explorer" && recurse)
	{
		var p=getObj(id).offsetParent;
		while (p!=null)
		{
			x+=p.offsetLeft;
			y+=p.offsetTop;
			p=p.offsetParent;
		}
	}

	return [x, y];
}


function urlencode_utf8(s)
{
	return unescape(encodeURIComponent(s));
}

function urldecode_utf8(s)
{
	return decodeURIComponent(escape(s));
}

function rawurlencode(s)
{
	return encodeURIComponent(s);
}

function rawurldecode(s)
{
	return decodeURIComponent(s);
}

function encodeSearchParam(sp)
{
	return rawurlencode(sp.replace("/", ""));
}

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


/************************
*	Selects				*
************************/

// idbase prefix index suffix
function hideMultiple(idbase, prefix, suffix, startindex, endindex, isUp)
{
	for (var i=startindex; i<=endindex; i++)
	{
		var ob=idbase+prefix+(""+i).replace("-", "_")+suffix;
		if (getObj(ob)!=undefined)
		{
			getObj(ob).style.visibility="hidden";
			getObj(ob).style.height="0px";
		}
	}
}

function showMultiple(idbase, prefix, suffix, startindex, endindex, isUp)
{
	var j=0;
	var ybase=getObjDivPos(idbase+"_selectbox")[1];
	if (isUp)
		ybase=getObjDivPosRec(idbase+"_selectbox", false)[1];
	var hbase=getObj(idbase+"_selectbox").offsetHeight;
	for (var i=startindex; i<=endindex; i++)
	{
		var ob=idbase+prefix+(""+i).replace("-", "_")+suffix;
		if (getObj(ob)!=undefined)
		{
			getObj(ob).style.visibility="visible";
			getObj(ob).style.height="16px";
			getObj(ob).style.position="absolute";
			getObj(ob).style.zIndex="99";
			getObj(ob).style.width=(getObj(idbase+"_selectbox").offsetWidth-6)+"px";
			if (isUp)
			{
				getObj(ob).style.top=(ybase-16*(j+1))+"px";
			}
			else
			{
				getObj(ob).style.top=(ybase+hbase+16*j)+"px";
			}
			j++;
		}
	}
}

function selectOptionClicked(selBaseId, optId, minId, maxId, isUp)
{
	var oldId=getObj(selBaseId+"_hidden").value;
	var newId=optId;
	getObj(selBaseId+"_select").innerHTML=getObj(optId).innerHTML;
	getObj(selBaseId+"_hidden").value=optId;
	hideMultiple(selBaseId, '_', '', minId, maxId, isUp);
	 
	if (oldId!=newId && getObj(selBaseId+"_select").getAttribute("onchange") != null)
		eval(getObj(selBaseId+"_select").getAttribute("onchange"));
}

/*
function selectChanged(selBaseId)
{
	if (selBaseId=='ciudades')
		window.location="agenda/ciudades/"+getObj(selBaseId+"_hidden").value+"/"+getObj(selBaseId+"_select").innerHTML;
}

*/

function selectChanged(id)
{
	document.forms[0].submit();

	var e = document.getElementById(id+"_hidden");
	// el segon replace gestiona els _1 => -1 :P
	var v = e.value.replace(id+"_", "").replace("_", "-");;
	//alert(v);			
}

function selectChangedNoSubmit(id)
{
	var e = document.getElementById(id+"_hidden");
	// el segon replace gestiona els _1 => -1 :P
	var v = e.value.replace(id+"_", "").replace("_", "-");
	document.getElementById(id+"_hidden").value = v;
	//alert(document.getElementById(id+"_hidden").value);			
}

function selectChanged3(id)
{
	document.forms[1].submit();

	var e = document.getElementById(id+"_hidden");
	// el segon replace gestiona els _1 => -1 :P
	var v = e.value.replace(id+"_", "").replace("_", "-");
	//alert(v);			
}


function selectChanged2(id)
{
	if (document.forms[1].getAttribute("id")=="postcommentform")
		document.forms[2].submit();
	else
		document.forms[1].submit();

	var e = document.getElementById(id+"_hidden");
	// el segon replace gestiona els _1 => -1 :P
	var v = e.value.replace(id+"_", "").replace("_", "-");
	//alert(v);			
}


function selectChanged4(id)
{
	if (getObj("PlayNight_shots_Form")!=null)
		getObj("PlayNight_shots_Form").submit();
	if (getObj("PlayNight_Form")!=null)
		getObj("PlayNight_Form").submit();
	else if (document.forms.length>=3 && document.forms[2].getAttribute("id")=="postcommentform")
		document.forms[3].submit();
	else if (document.forms.length>=4 && document.forms[3].getAttribute("id")!="search")
		document.forms[3].submit();
	else
		document.forms[3].submit();

	var e = document.getElementById(id+"_hidden");
	// el segon replace gestiona els _1 => -1 :P
	var v = e.value.replace(id+"_", "").replace("_", "-");
	//alert(v);			
}

function selectRemoveSelectedItem(selectId)
{
	var select = document.getElementById(selectId);
	var i;
	for (i = select.length - 1; i>=0; i--)
	{
		if (select.options[i].selected)
		{
			select.remove(i);
		}
	}
}

function selectLoadValue(selectIdFrom, inputIdTo, tinyMCE)
{
	var selectFrom = document.getElementById(selectIdFrom);
	var inputTo = document.getElementById(inputIdTo);
	
	if (curSelectedIndex!=-1)
	{
		selectFrom.options[curSelectedIndex].value = tinyMCE.get(inputIdTo).getContent();
	}
	
	var value = selectFrom.options[selectFrom.selectedIndex].value;
	
	inputTo.value = value;
	tinyMCE.get(inputIdTo).setContent(value);
	
	curSelectedIndex = selectFrom.selectedIndex;
}

function selectLoadValueText(selectIdFrom, inputIdTo)
{
	var selectFrom = document.getElementById(selectIdFrom);
	var inputTo = document.getElementById(inputIdTo);
	
	if (curSelectedIndexText!=-1)
	{
		selectFrom.options[curSelectedIndexText].value = inputTo.value;
	}
	
	var value = selectFrom.options[selectFrom.selectedIndex].value;
	
	
	inputTo.value = value;
	
	curSelectedIndexText = selectFrom.selectedIndex;
}


function selectSelectedItemIn(selectIdFrom, selectIdTo)
{
	var selectFrom = document.getElementById(selectIdFrom);
	var selectTo = document.getElementById(selectIdTo);		
	
	for (var i=0; i<selectFrom.options.length; i++)
	{
		selectTo.options[i].selected = selectFrom.options[i].selected
	}
}


function selectSelectedItemDown(selectId)
{
	var select = document.getElementById(selectId);
	var selIdx = select.selectedIndex;

	if (selIdx<select.length-1)
	{
		var opt=select.options[selIdx];
		var opt2=select.options[selIdx+1];
		var tmpOpt = document.createElement('option');
		tmpOpt.text = "----------";
		tmpOpt.value = "----------";
		select.options[selIdx]=tmpOpt;
		select.options[selIdx+1]=opt;
		select.options[selIdx]=opt2;
	}
}

function selectSelectedItemUp(selectId)
{
	var select = document.getElementById(selectId);
	var selIdx = select.selectedIndex;

	if (selIdx>0)
	{
		var opt=select.options[selIdx];
		var opt2=select.options[selIdx-1];
		var tmpOpt = document.createElement('option');
		tmpOpt.text = "----------";
		tmpOpt.value = "----------";
		select.options[selIdx]=tmpOpt;
		select.options[selIdx-1]=opt;
		select.options[selIdx]=opt2;
	}
}

function selectSelectAll(selectId)
{
	var select = document.getElementById(selectId);
	var i;
	for (i = select.length - 1; i>=0; i--)
	{
		select.options[i].selected="selected";
	}
}


/************************
*	Folding items		*
************************/

var foldingHeights=new Array();
var foldingIds=new Array();
var foldingAnims=new Array();
var foldingItemAnimTime=500;
var foldingAnimable=false;

function initFoldingItems(sec, fold, count)
{
	imgBg = sec;
	
	if (imgBg == null || imgBg.length==0)
	{
		imgBg = "generic";
	}
	
	foldingItemOpenBG('foldingitem_'+sec, fold, 1, count, "transparent url('/themes/sespm/img/bg/folding/"+imgBg+".png') 0px 0px repeat-x", true);
}

// Obre el folding item "idbase"+index i tanca la resta.
// Index d'1 a totalcount
function foldingItemOpen(idbase, foldingItemIndex, index, totalcount, bgstyle, init)
{
	if (!foldingAnimable && !init)
		return;
	if (animating())
		return;
	setTimeout("foldingItemOpenBG('"+idbase+"', "+foldingItemIndex+", "+index+", "+totalcount+", '"+escape(bgstyle)+"', "+init+")", 10);
}

function foldingItemOpenBG(idbase, foldingItemIndex, index, totalcount, bgstyle, init)
{
//	alert(idbase+" "+foldingItemIndex+" "+index+" "+totalcount);

	if (!foldingAnimable && !init)
		return;

	foldingAnims[foldingItemIndex]=new Array(totalcount);
	foldingIds[foldingItemIndex]=new Array(totalcount);
	
	if (init || foldingHeights[foldingItemIndex]==null)
	{
		foldingHeights[foldingItemIndex]=new Array(totalcount);
		init=true;
	}	
	
	for (var f=1; f<=totalcount; f++)
	{
		foldingIds[foldingItemIndex][f-1]=idbase+""+foldingItemIndex+"_"+f;
		if (f==index)
			getObj(foldingIds[foldingItemIndex][f-1]+"_title").style.background=unescape(bgstyle);
		else
			getObj(foldingIds[foldingItemIndex][f-1]+"_title").style.background="transparent";

		if (init)
			foldingHeights[foldingItemIndex][f-1]=getObj(foldingIds[foldingItemIndex][f-1]).offsetHeight;
	}

	for (var f=1; f<=totalcount; f++)
	{
		if (f==index && getObj(foldingIds[foldingItemIndex][f-1]).offsetHeight<10)
			foldingAnims[foldingItemIndex][f-1]=sin2GradientGeneric(0, foldingHeights[foldingItemIndex][f-1], 50, 1, "", "px", true);
		else if (f==index)
		{
			if (!init)
				return;
			foldingAnims[foldingItemIndex][f-1]=sin2GradientGeneric(foldingHeights[foldingItemIndex][f-1], foldingHeights[foldingItemIndex][f-1], 50, 1, "", "px", true);
		}
		else if (getObj(foldingIds[foldingItemIndex][f-1]).offsetHeight<10)
			foldingAnims[foldingItemIndex][f-1]=sin2GradientGeneric(0, 0, 50, 1, "", "px", true);
		else
			foldingAnims[foldingItemIndex][f-1]=sin2GradientGeneric(foldingHeights[foldingItemIndex][f-1], 0, 50, 1, "", "px", true);
	}

	if (init)
	{
		animClear(simpleAnimateTimer);
		multipleSimpleAnimate(foldingIds[foldingItemIndex], ".style.height", foldingAnims[foldingItemIndex], foldingAnims[foldingItemIndex][0].length, -1, -1);
		foldingAnimable=true;
	}
	else
		foldingItemsApplyAnim(foldingIds[foldingItemIndex], foldingAnims[foldingItemIndex]);
}

function foldingItemsApplyAnim(ids, anim)
{
	animClear(simpleAnimateTimer);
	multipleSimpleAnimate(ids, ".style.height", anim, anim[0].length, foldingItemAnimTime, foldingItemAnimTime);
}

/************************
*	Reproduccio media	*
************************/

function playAudio(divId, url, allowDload, autostart, width)
{
	if (!swfobject.hasFlashPlayerVersion("8.0.0"))
	{
		if (confirm("Necesita una versión de Flash Player más nueva para escuchar el audio.\nPulse aceptar si desea instalarla.\nUna vez instalada, recarge esta página."))
			window.open('http://www.macromedia.com/go/getflash', 'Flash', '');
		return;
	}

	getObj(divId).style.height="19px";

	var flashvars = {
		file : url,
		autostart : false, // (autostart==null || autostart==true?"true":"false"),
		abouttext : "PlayGround",
		aboutlink : "http://www.playgroundmag.net",
		linktarget : "_new"
	};
	var params = {};
	var attributes = {
		id : divId+"_embed",
		allowfullscreen : "false",
		allowscriptaccess : "always"
	};

	swfobject.embedSWF("/files/modules/player/player.swf", divId, (width!=null?width:"476"), "22", "8.0.0", false, flashvars, params, attributes);

	if (autostart==null || autostart==true)
		setTimeout("var player=getObj('"+divId+"_embed'); player.sendEvent('PLAY');", 500);
}

function playVideo(divId, url, width, height, showBar)
{
	if (!swfobject.hasFlashPlayerVersion("9.0.98"))
	{
		if (confirm("Necesita una versión de Flash Player más nueva para visualizar el vídeo.\nPulse aceptar si desea instalarla.\nUna vez instalada, recargue esta página."))
			window.open('http://www.macromedia.com/go/getflash', 'Flash', '');
		return;
	}
	
	getObj(divId).style.width=width+"px";
	getObj(divId).style.height=height+"px";
	getObj(divId).style.margin="0px";
	getObj(divId).style.backgroundColor="transparent";

	var flashvars = {
		file : url,
		autostart : false,
		abouttext : "SESPM",
		aboutlink : "http://www.sespm.es",
		linktarget : "_new",
		controlBar : (!showBar? "none" : "bottom")
	};
	var params = {};
	var attributes = {
		id : divId+"_embed",
		allowfullscreen : "true",
		allowscriptaccess : "always"
	};
	swfobject.embedSWF("/files/modules/player/player.swf", divId, width, height, "9.0.98", false, flashvars, params, attributes);
}

function openAudio(divId, url, allowDload)
{
	playAudio(divId, url, allowDload, false);
}

function openVideo(divId, url, allowDload)
{
	playVideo(divId, url, allowDload, false);
}

function playTVProximamente(divId)
{
	var flashvars = {
		file : "/f/movies/playtv.m4v",
		autostart : "true",
		abouttext : "PlayGround",
		aboutlink : "http://www.playgroundmag.net",
		linktarget : "_new"
	};
	var params = {};
	var attributes = {
		id : divId,
		name : divId, 
		allowfullscreen : "false",
		allowscriptaccess : "always"
	};
	swfobject.embedSWF("/files/modules/player/player.swf", divId, "480", "380", "9.0.98", false, flashvars, params, attributes);
}

function playTVMovie(divId, movie, titleId, title, subtitleId, subtitle, linkInputId, serverName, videoId, videoArrayPosition, textoId, texto)
{
	var flashvars = {
		file : movie,
		autostart : "true",
		abouttext : "PlayGround",
		aboutlink : "http://www.playgroundmag.net",
		linktarget : "_new"
	};
	var params = {};
	var attributes = {
		id : divId,
		name : divId, 
		allowfullscreen : "false",
		allowscriptaccess : "always"
	};
	swfobject.embedSWF("/files/modules/player/player.swf", divId, "480", "380", "9.0.98", false, flashvars, params, attributes);

	playTVServerName=serverName;
	getObj(linkInputId).value="http://"+serverName+"/playtv/v/"+videoId;
	currentPlayTVPlaying=videoArrayPosition;
	
	var titleText=document.createTextNode(title);
	var subtitleText=document.createTextNode(subtitle);
	var textoText=document.createTextNode(texto);

	var titleObj=getObj(titleId);
	var subtitleObj=getObj(subtitleId);
	var textoObj=getObj(textoId);

	while (titleObj.childNodes.length>0)
		titleObj.removeChild(titleObj.childNodes.item(titleObj.childNodes.length-1));

	while (subtitleObj.childNodes.length>0)
		subtitleObj.removeChild(subtitleObj.childNodes.item(subtitleObj.childNodes.length-1));

	while (textoObj.childNodes.length>0)
		textoObj.removeChild(textoObj.childNodes.item(textoObj.childNodes.length-1));
		
	titleObj.appendChild(titleText);
	subtitleObj.appendChild(subtitleText);
	//textoObj.appendChild(textoText);
	textoObj.innerHTML = texto;
}

function homeTop5Play(divId, innerDivId, type, videoId, videoThumb, startPlaying)
{
	if (type=="youtube")
	{
		var flashvars = {
			autoplay : (startPlaying?"1":"0")
		};
		var params = {};
		var attributes = {
			id : innerDivId,
			autostart : (startPlaying?"true":"false"),
			allowfullscreen : "false",
			allowscriptaccess : "always"
		};
		swfobject.embedSWF("http://www.youtube.com/v/" + videoId + "&amp;autoplay=1", innerDivId, "230", "186", "9.0.98", false, flashvars, params, attributes);
	}
	else if (type=="googlevideo")
	{
		var flashvars = {
			autoplay : (startPlaying?"true":"false"),
			playerMode : "simple",
			showShareButtons : "false"
		};
		var params = {};
		var attributes = {
			id : innerDivId,
			autostart : (startPlaying?"true":"false"),
			allowfullscreen : "false",
			allowscriptaccess : "always"
		};
		swfobject.embedSWF("http://video.google.com/googleplayer.swf?docId=" + videoId, innerDivId, "230", "186", "9.0.98", false, flashvars, params, attributes);
	}
	else if (type=="playground")
	{
		var flashvars = {
			file : videoId,
			autostart : (startPlaying?"true":"false"),
			abouttext : "PlayGround",
			aboutlink : "http://www.playgroundmag.net",
			linktarget : "_new"
		};
		var params = {};
		var attributes = {
			id : innerDivId,
			allowfullscreen : "false",
			allowscriptaccess : "always"
		};
		swfobject.embedSWF("/files/modules/player/player.swf", innerDivId, "230", "186", "9.0.98", false, flashvars, params, attributes);
	}
	else if (type=="vimeo")
	{
		var flashvars = {
			autoplay : (startPlaying?"1":"0")
		};
		var params = {};
		var attributes = {
			id : innerDivId,
			autostart : (startPlaying?"true":"false"),
			allowfullscreen : "false",
			allowscriptaccess : "always"
		};
		swfobject.embedSWF("http://vimeo.com/moogaloop.swf?clip_id="+videoId+"&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1&amp;autoplay=1", innerDivId, "230", "186", "9.0.98", false, flashvars, params, attributes);
	}	
	else if (type=="dailymotion")
	{
		var flashvars = {
			autoplay : (startPlaying?"1":"0")
		};
		var params = {};
		var attributes = {
			id : innerDivId,
			autostart : (startPlaying?"true":"false"),
			allowfullscreen : "false",
			allowscriptaccess : "always"
		};
		swfobject.embedSWF("http://www.dailymotion.com/swf/"+videoId+"&related=0&canvas=medium&autoplay=1", innerDivId, "230", "186", "9.0.98", false, flashvars, params, attributes);
	}	
	else if (type=="myspace")
	{
		var flashvars = {
			autoplay : (startPlaying?"1":"0")
		};
		var params = {};
		var attributes = {
			id : innerDivId,
			autostart : (startPlaying?"true":"false"),
			allowfullscreen : "false",
			allowscriptaccess : "always"
		};
		swfobject.embedSWF("http://mediaservices.myspace.com/services/media/embed.aspx/m="+videoId+",t=1,mt=video,searchID=,primarycolor=,secondarycolor=", innerDivId, "230", "186", "9.0.98", false, flashvars, params, attributes);
	}		
}

function homeTop5FlashPlayNow(divId, innerDivId, type, videoId, videoThumb, startPlaying)
{
	var flashvars = {};
	var params = {
		wmode : "transparent"
	};
	var attributes = {
		id : innerDivId,
		allowfullscreen : "false",
		allowscriptaccess : "always",
		onclick : "homeTop5Play('"+divId+"', '"+innerDivId+"', '"+type+"', '"+videoId+"', '"+videoThumb+"', true);"
	};
	swfobject.embedSWF("/themes/sespm/img/playnow.swf", innerDivId, "230", "43", "9.0.98", false, flashvars, params, attributes);
}

function loadImagePainter(divId, id, shotId, paintedId)
{
	var flashvars = {
		id : id,
		shotId : shotId,
		paintedId : paintedId
	};
	
	var params = {};
	var attributes = {
		id : divId
	};
	swfobject.embedSWF("/files/modules/imgpainter/imagepainter.swf", divId, "730", "500", "9.0.0", false, flashvars, params, attributes);
}

/************************
*	Shots				*
************************/
var currShot=0;
var totalShots=0;
var currPaintedPage=0;
var totalPaintedPages=1;
var linkShotsURLPrefix="";
var linkShotsURLSuffix="";
var linkPaintShotsURLPrefix="";
var linkSendShotsURLPrefix="";
var shotOverImage="";
var shotOutImage="";



function loadShotCommentsAjax(idObj, idImg)
{

var xmlHttp;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
      document.getElementById(idObj).innerHTML=xmlHttp.responseText;
      }
    }
  xmlHttp.open("GET","/ajax/shotcomments/1355/"+idImg,true);
  xmlHttp.send(null);
  }


function goShot(imgId, imgArr, pos, currShotIndexDiv, linkTextBoxId, origImageLinkId, sendLinkId, paintLinkId, paintedDivId, currPaintedPageDivId)
{
	getObj(currShotIndexDiv).innerHTML=(pos+1)+" / "+totalShots;
	var tit=document.title;
	var posPar=tit.lastIndexOf("(");
	if (posPar!=-1)
	{
		tit = tit.substr(0, posPar+1) + (pos+1) + " de " + totalShots + ")";
		document.title=tit;
	}
	currShot=pos;

	shotOverImage=imgArr[pos][1];
	shotOutImage=imgArr[pos][1];
	
	var shotOverImageId = imgArr[pos][0];

	if (imgArr[pos][3].length>0)
		shotOverImage=imgArr[pos][3][0][2];
		
	var formComments = document.forms["postcommentform"];
	formComments.idImagen.value = shotOverImageId;
		
	setTimeout("getObj('"+imgId+"OverPreload').src='"+shotOverImage+"'; getObj('"+imgId+"').src='"+shotOutImage+"';", 125);
	
	loadShotCommentsAjax("shotSlideComments", shotOverImageId);
	
	getObj('shotSlideComments').innerHTML="<div style=\"font-size:10px; padding-right: 160px;\">Cargando...</div>";
		
	updateShotsVariables(imgArr, pos, linkTextBoxId, origImageLinkId, sendLinkId, paintLinkId, paintedDivId, currPaintedPageDivId)
}

function nextShot(imgId, imgArr, currPos, currShotIndexDiv, linkTextBoxId, origImageLinkId, sendLinkId, paintLinkId, paintedDivId, currPaintedPageDivId)
{
	if (currPos<imgArr.length-1)
		goShot(imgId, imgArr, currPos+1, currShotIndexDiv, linkTextBoxId, origImageLinkId, sendLinkId, paintLinkId, paintedDivId, currPaintedPageDivId);
	else
		goShot(imgId, imgArr, 0, currShotIndexDiv, linkTextBoxId, origImageLinkId, sendLinkId, paintLinkId, paintedDivId, currPaintedPageDivId);	
}

function prevShot(imgId, imgArr, currPos, currShotIndexDiv, linkTextBoxId, origImageLinkId, sendLinkId, paintLinkId, paintedDivId, currPaintedPageDivId)
{
	if (currPos>0)
		goShot(imgId, imgArr, currPos-1, currShotIndexDiv, linkTextBoxId, origImageLinkId, sendLinkId, paintLinkId, paintedDivId, currPaintedPageDivId);
	else
		goShot(imgId, imgArr, imgArr.length-1, currShotIndexDiv, linkTextBoxId, origImageLinkId, sendLinkId, paintLinkId, paintedDivId, currPaintedPageDivId);	
}

function updateShotsVariables(imgArr, index, linkTextBoxId, origImageLinkId, sendLinkId, paintLinkId, paintedDivId, currPaintedPageDivId)
{
	getObj(linkTextBoxId).value=linkShotsURLPrefix+imgArr[index][0]+linkShotsURLSuffix;
	getObj(origImageLinkId).setAttribute("href", imgArr[index][2]);
	getObj(sendLinkId).setAttribute("href", linkSendShotsURLPrefix+imgArr[index][0]);
	getObj(paintLinkId).setAttribute("onclick", "window.open('"+linkPaintShotsURLPrefix+imgArr[index][0]+"/00000001', 'imagepainter', 'width=800,height=620,toolbar=no,status=no');");
	updatePaintedShotsDiv(imgArr, index, paintedDivId, currPaintedPageDivId, 0);
}

function updatePaintedShotsDiv(imgArr, index, paintedShotsDivId, currPaintedPageDivId, page)
{
	var numPainted=imgArr[index][3].length;
	var numPaintedPages=Math.ceil(numPainted/18);
	
	totalPaintedPages=numPaintedPages;
	
	if (page<0)	page=0;
	else if (page>=numPaintedPages) page=numPaintedPages-1;

	currPaintedPage=page;
	
	var currPaintedPageDiv=getObj(currPaintedPageDivId);

	while (currPaintedPageDiv.childNodes.length>0)
		currPaintedPageDiv.removeChild(currPaintedPageDiv.childNodes.item(currPaintedPageDiv.childNodes.length-1));

	var currPaintedPageDivCounter=document.createTextNode((currPaintedPage+1)+" / "+totalPaintedPages);
	currPaintedPageDiv.appendChild(currPaintedPageDivCounter);
	
	var lines=Math.ceil((imgArr[index][3].length-page*18)/3);

	var div=getObj(paintedShotsDivId);
	
	while (div.childNodes.length>0)
		div.removeChild(div.childNodes.item(div.childNodes.length-1));

	if (lines<6)
		div.style.minHeight=(110*lines)+"px";
	else
		div.style.minHeight=(110*6)+"px";
	
	if (numPainted==0)
	{
		div.style.minHeight="0px";
		div.style.height="65px";
//		div.setAttribute("class", "standardtext standardtextbody");
		setObjClass(div, "standardtext standardtextbody");
		var text=document.createTextNode("No hay pintadas de los usuarios para este shot");
		div.appendChild(text);
		return;
	}
	else
	{
//		div.setAttribute("class", "");
		setObjClass(div, "");
	}
	
	for (var i=page*18; i<numPainted && i<(page+1)*18; i++)
	{
		div.appendChild(createPaintedShotItem(imgArr, index, i%3, Math.floor(i/3), -page*6));
	}
}

function createPaintedShotItem(imgArr, index, column, row, rowOffset)
{
	var div=document.createElement("div");
//	div.setAttribute("class", "shotssmallimgindexdiv"+(column==2?" shotssmallimgindexdivrightmost":""));
	setObjClass(div, "shotssmallimgindexdiv"+(column==2?" shotssmallimgindexdivrightmost":""));
//	div.setAttribute("style", "position: absolute; margin-left: " + (162*column) + "px; margin-top: " + (110*(row+rowOffset)) + "px;");
	
	var a=document.createElement("a");
//	a.setAttribute("class", "colorblack nodec");
	setObjClass(a, "colorblack nodec");
	a.setAttribute("target", "_new");
	a.setAttribute("alt", "Pulsa para ver");
	a.setAttribute("title", "Pulsa para ver");
	a.setAttribute("href", imgArr[index][3][row*3+column][0]);
	
	var img=document.createElement("img");
//	img.setAttribute("class", "shotssmallimgindex");
	setObjClass(img, "shotssmallimgindex");
	img.setAttribute("border", "0");
	img.setAttribute("src", imgArr[index][3][row*3+column][1]);
	
	a.appendChild(img);
	div.appendChild(a);
	
	return div;
}






function numPagesChange()
{
	var url = "/ajax/docpages";
	
	document.getElementById("progress").style.visibility="visible";
	
	var form=new MultiPartFormData();
	form.addVariable("texto", tinyMCE.get("texto").getContent());
	form.addVariable("numPages", document.getElementById("numPages").value);
	
	form.finish();

	var post=form.getData();
	
	ajaxPost(url, post, "multipart/form-data; boundary=\""+form.getBoundary()+"\"", "numPagesChangeCallback", true);
}




function numPagesChangeCallback(ajax)
{
	var num = ajax.responseXML.getElementsByTagName("PlayGround")[0].childNodes[0].nodeValue;
	document.getElementById("pageLenLines").value = num;
	document.getElementById("progress").style.visibility="hidden";	
}

function submitCommentForm()
{
	var url = "/ajax/submitcomment";
	
	document.getElementById("progress").style.visibility="visible";
	
	var form=new MultiPartFormData();
	form.addVariable("idDocumento", document.getElementById("idDocumento").value);
	form.addVariable("sectionOriginalName", document.getElementById("sectionOriginalName").value);
	form.addVariable("extraURL", document.getElementById("extraURL").value);
	form.addVariable("nombre", document.getElementById("nombre").value);
	form.addVariable("email", document.getElementById("email").value);
	
	if (document.getElementById("valoracion_hidden")!=null)
	{
		form.addVariable("valoracion_hidden", document.getElementById("valoracion_hidden").value);
	}
	
	form.addVariable("idImagen", document.getElementById("idImagen").value);
	form.addVariable("comentario", document.getElementById("comentario").value);
	form.addVariable("captchatext", document.getElementById("captchatext").value);
	
	form.finish();

	var post=form.getData();
	
	ajaxPost(url, post, "multipart/form-data; boundary=\""+form.getBoundary()+"\"", "submitCommentFormCallback", true);	
}

function submitCommentFormCallback(ajax)
{
	var errorText = ajax.responseXML.getElementsByTagName("PlayGround")[0].childNodes[0].nodeValue;
	
	if (errorText==null || errorText=="")
	{
		var idDocumento = document.getElementById("idDocumento").value;
		
		if (document.getElementById("idImagen").value!=null && document.getElementById("idImagen").value!="")
		{
			loadShotCommentsAjax("shotSlideComments", document.getElementById("idImagen").value);	
		}
		else
		{		
			loadDocCommentsAjax("docComments", idDocumento);
			getObj('docComments').innerHTML="<div style=\"font-size:10px; padding-right: 160px;\">Cargando...</div>";
		}
				
		document.getElementById("progress").style.visibility="hidden";
		document.getElementById("docCommentsError").innerHTML="";
	    document.getElementById("captcha").src = document.getElementById("captcha").src + "&" + (new Date()).getTime();
	    document.getElementById("nombre").value = "";
	    document.getElementById("email").value = "";
	    document.getElementById("comentario").value = "";
	    document.getElementById("captchatext").value = "";
	}
	else
	{
		document.getElementById("docCommentsError").innerHTML=errorText;
		document.getElementById("progress").style.visibility="hidden";
	}
}


function loadDocCommentsAjax(idObj, idDocumento)
{
	var xmlHttp;
	try
	  {
	  // Firefox, Opera 8.0+, Safari
	  xmlHttp=new XMLHttpRequest();
	  }
	catch (e)
	  {
	  // Internet Explorer
	  try
	    {
	    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	    }
	  catch (e)
	    {
	    try
	      {
	      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	      }
	    catch (e)
	      {
	      alert("Your browser does not support AJAX!");
	      return false;
	      }
	    }
	  }
	  xmlHttp.onreadystatechange=function()
	    {
	    if(xmlHttp.readyState==4)
	      {
		      document.getElementById(idObj).innerHTML=xmlHttp.responseText;
		      $(idObj).blindDown();
	      }
	    }
	  xmlHttp.open("GET","/ajax/doccomments/"+idDocumento,true);
	  xmlHttp.send(null);
}




function getSuggestedWords()
{
	var url = "/ajax/suggestedwords";
	
	document.getElementById("progressWords").style.visibility="visible";
	
	var form=new MultiPartFormData();
	form.addVariable("texto", tinyMCE.get("texto").getContent());
	
	form.finish();

	var post=form.getData();
	
	ajaxPost(url, post, "multipart/form-data; boundary=\""+form.getBoundary()+"\"", "getSuggestedWordsCallback", true);
}




function getSuggestedWordsCallback(ajax)
{
	var num = ajax.responseXML.getElementsByTagName("PlayGround")[0].childNodes[0].nodeValue;
	document.getElementById("suggestedWords").innerHTML = num;
	document.getElementById("progressWords").style.visibility="hidden";	
}

function home980TopVideoPlay(divId, innerDivId, type, videoId, videoThumb, titulo, subtitulo, startPlaying)
{
	if (type=="youtube")
	{
		var flashvars = {
			autoplay : (startPlaying?"1":"0")
		};
		var params = {};
		var attributes = {
			id : innerDivId,
			autostart : (startPlaying?"true":"false"),
			allowfullscreen : "false",
			allowscriptaccess : "always"
		};
		swfobject.embedSWF("http://www.youtube.com/v/" + videoId + "&amp;autoplay=" + (startPlaying?"1":"0"), innerDivId, "480", "270", "9.0.98", false, flashvars, params, attributes);
	}
	else if (type=="googlevideo")
	{
		var flashvars = {
			autoplay : (startPlaying?"true":"false"),
			playerMode : "simple",
			showShareButtons : "false"
		};
		var params = {};
		var attributes = {
			id : innerDivId,
			autostart : (startPlaying?"true":"false"),
			allowfullscreen : "false",
			allowscriptaccess : "always"
		};
		swfobject.embedSWF("http://video.google.com/googleplayer.swf?docId=" + videoId, innerDivId, "480", "270", "9.0.98", false, flashvars, params, attributes);
	}
	else if (type=="playground")
	{
		var flashvars = {
			file : videoId,
			autostart : (startPlaying?"true":"false"),
			abouttext : "PlayGround",
			aboutlink : "http://www.playgroundmag.net",
			linktarget : "_new"
		};
		var params = {};
		var attributes = {
			id : innerDivId,
			allowfullscreen : "false",
			allowscriptaccess : "always"
		};
		swfobject.embedSWF("/files/modules/player/player.swf", innerDivId, "480", "270", "9.0.98", false, flashvars, params, attributes);
	}
	else if (type=="vimeo")
	{
		var flashvars = {
			autoplay : (startPlaying?"1":"0")
		};
		var params = {};
		var attributes = {
			id : innerDivId,
			autostart : (startPlaying?"true":"false"),
			allowfullscreen : "false",
			allowscriptaccess : "always"
		};
		swfobject.embedSWF("http://vimeo.com/moogaloop.swf?clip_id="+videoId+"&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1&amp;autoplay=1", innerDivId, "480", "270", "9.0.98", false, flashvars, params, attributes);
	}	
	else if (type=="dailymotion")
	{
		var flashvars = {
			autoplay : (startPlaying?"1":"0")
		};
		var params = {};
		var attributes = {
			id : innerDivId,
			autostart : (startPlaying?"true":"false"),
			allowfullscreen : "false",
			allowscriptaccess : "always"
		};
		swfobject.embedSWF("http://www.dailymotion.com/swf/"+videoId+"&related=0&canvas=medium&autoplay=1", innerDivId, "480", "270", "9.0.98", false, flashvars, params, attributes);
	}	
	else if (type=="myspace")
	{
		var flashvars = {
			autoplay : (startPlaying?"1":"0")
		};
		var params = {};
		var attributes = {
			id : innerDivId,
			autostart : (startPlaying?"true":"false"),
			allowfullscreen : "false",
			allowscriptaccess : "always"
		};
		swfobject.embedSWF("http://mediaservices.myspace.com/services/media/embed.aspx/m="+videoId+",t=1,mt=video,searchID=,primarycolor=,secondarycolor=", innerDivId, "480", "270", "9.0.98", false, flashvars, params, attributes);
	}
	
	var h1Elem = document.createElement("h1");
	h1Elem.className="colorblack";
	var h1Text=document.createTextNode(rawurldecode(titulo));
	h1Elem.appendChild(h1Text);
	
	var h2Elem = document.createElement("h2");
	h2Elem.className="colorblack";
	var h2Text=document.createTextNode(rawurldecode(subtitulo));
	h2Elem.appendChild(h2Text);
	
	var titObj=getObj("homeTopVideoTitulo");
	var subtitObj=getObj("homeTopVideoSubtitulo");

	while (titObj.childNodes.length>0)
		titObj.removeChild(titObj.childNodes.item(titObj.childNodes.length-1));

	while (subtitObj.childNodes.length>0)
		subtitObj.removeChild(subtitObj.childNodes.item(subtitObj.childNodes.length-1));

	titObj.appendChild(h1Elem);
	subtitObj.appendChild(h2Elem);
}


/**************************************
 * Baixada de fitxers via subscripció *
 **************************************/

// dloadSubsFile: Mostra el div per veure si es pot baixar un fitxer, posant l'adreça de correu. Envia un mail a l'adreça indicada, si esta subscrit, amb el link.
// Dona opcio de subscriure's a la news.
// Params:
//	fileId: Id de fitxer a ficheros_documentos;
function dloadSubsFile(fileId)
{
	var bodyArr = document.getElementsByTagName("body");
	var body=bodyArr[0];
	
	if (body==null)
		alert("body nullllll");
		
	if (getObj("subsDloadDiv_"+fileId)!=null)
	{
		body.removeChild(getObj("subsDloadDiv_"+fileId));
	}

	var eDiv=document.createElement("div");
	eDiv.id="subsDloadDiv_"+fileId;
	eDiv.className="subsDloadDiv";
	eDiv.style.display="none";
	
	var eTextDloadDiv = document.createElement("div");
	eTextDloadDiv.className="date colorblack";
	var eDloadByMailText = document.createTextNode(_t["Please type in your email address to download this podcast"]);


	eTextDloadDiv.appendChild(eDloadByMailText);

	var eEmailInputDiv = document.createElement("div");
	var eEmailInput = document.createElement("input");
	eEmailInput.className="stdinput";
	eEmailInput.name="dloadsubs_email";
	eEmailInput.id="dloadsubs_email";
	eEmailInput.size = "35";
	eEmailInputDiv.className="paddingtop10 paddingbottom10";
	eEmailInputDiv.appendChild(eEmailInput);
	var eSendText = document.createTextNode("enviar >>");
	var eSendSpaceText = document.createTextNode(" ");
	var eSendLink = document.createElement("a");
	eSendLink.className="date nodec colormagenta nolink colormagentalink";
	eSendLink.onclick = function() {
		var url = "/ajax/verifyusermail";		
		var form=new MultiPartFormData();
		form.addVariable("fileId", fileId);		
		form.addVariable("email", eEmailInput.value);		
		form.finish();
		var post=form.getData();		
		ajaxPost(url, post, "multipart/form-data; boundary=\""+form.getBoundary()+"\"", "verifyUserMailCallback", true);
	};
	eSendLink.appendChild(eSendText);
	eEmailInputDiv.appendChild(eSendSpaceText);
	eEmailInputDiv.appendChild(eSendLink);

	var eSubsDiv = document.createElement("div");
	eSubsDiv.className="date colorblack";
	var eSubsHereText = document.createTextNode(_t["subscribe here!"]);
	var eSubsHereLink = document.createElement("a");
	eSubsHereLink.target="_blank";
	eSubsHereLink.href="/newsletter/sdl";
	eSubsHereLink.className = "nodec colormagenta nolink colormagentalink";
	eSubsHereLink.appendChild(eSubsHereText);

	var eCloseDiv = document.createElement("div");
	eCloseDiv.style.float="right";
	var eCloseText = document.createTextNode(_t["(close)"]);
	var eCloseLink = document.createElement("a");
	eCloseLink.onclick = function () {$("#subsDloadDiv_"+fileId).fadeOut();};
	eCloseLink.className = "date nodec colormagenta nolink colormagentalink";
	eCloseLink.appendChild(eCloseText);
	eCloseDiv.appendChild(eCloseLink);

	eSubsDiv.appendChild(eSubsHereLink);
	eSubsDiv.appendChild(eCloseDiv);

	eDiv.appendChild(eTextDloadDiv);
	eDiv.appendChild(eEmailInputDiv);
	eDiv.appendChild(eSubsDiv);
	
	body.appendChild(eDiv);

	$("#subsDloadDiv_"+fileId).fadeIn();
}

function verifyUserMailCallback(ajax)
{
	var res = ajax.responseXML.getElementsByTagName("PlayGround")[0].childNodes[0].childNodes[0].nodeValue;
	var fileId = ajax.responseXML.getElementsByTagName("PlayGround")[0].childNodes[1].childNodes[0].nodeValue;
	var email = ajax.responseXML.getElementsByTagName("PlayGround")[0].childNodes[2].childNodes[0].nodeValue;
	
	if (res=="0")
	{
		alert(_t["nonexistentUserMail"]);
	}
	else
	{
		alert(_t["mailverifyOk"]);
		var url = "/ajax/senddownloadlink";		
		var form=new MultiPartFormData();
		form.addVariable("fileId", fileId);		
		form.addVariable("email", email);		
		form.finish();
		var post=form.getData();		
		ajaxPost(url, post, "multipart/form-data; boundary=\""+form.getBoundary()+"\"", "void", true);		
	}
}

function regenCaptcha(captchaImg)
{
	captchaImg.src="/files/gencaptcha.php?w=128&h=40&_rnd="+Math.random();
}


// Callback JWPlayer
function playerReady(player)
{
//	alert("playerReady " + player + " " + player["id"]);
	var pl=getObj(player["id"]);

	if (player["id"]=="pgRadioHidden")
		addPGRadioListeners(pl);
	else if (player["id"]=="playtvmovie")
		addPlayTVListeners(pl);
}
// FI Callback JWPlayer



/***********
 * Banners *
 ***********/

function selectPosicion()
{
	var v = document.getElementById("secciones").value;
	
	if (v=="-1")
		return;
	
	window.open (v + "?preview=1", "wnd","status=0,toolbar=0,menubar=0,resizable=1,scrollbars=1,height=600,width=800");	
}

function addToOpener(idPosicion)
{
	window.opener.addPosicion(idPosicion);
	window.close();
}

function addPosicion(idPosicion)
{
	var selPosiciones = document.getElementById("selPosiciones");
	var selSectionNames = document.getElementById("selSectionNames");
	var selSecciones = document.getElementById("secciones");
	
	var optPos = document.createElement("option");
	optPos.text = idPosicion + " - " + selSecciones.value;
	optPos.value = idPosicion;	
	selPosiciones[selPosiciones.length] = optPos;
	
	var optSect = document.createElement("option");
	optSect.text = selSecciones.value;
	optSect.value = selSecciones.value;
	selSectionNames[selSectionNames.length] = optSect;
}

function registerBannerImpression(idBanner, idPosicion)
{
	//ajaxGet("/ajax/banneraction/impression/"+idBanner+"/"+idPosicion);

	var encIdPosicion = idPosicion.replace(/\//gi, "|");

	ajaxGet("/ajax/banneraction/impression/"+idBanner+"/"+encIdPosicion);
}

function registerBannerClick(idBanner, idPosicion)
{
	//ajaxGet("/ajax/banneraction/click/"+idBanner+"/"+idPosicion);

	var encIdPosicion = idPosicion.replace(/\//gi, "|");

	ajaxGet("/ajax/banneraction/click/"+idBanner+"/"+encIdPosicion);
}

function ajaxGet(url)
{
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e){
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
			
		}
	}
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}


function ajaxGetDocsMonths(idTipo, idObj, idVerMas)
{
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e){
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
	      	document.getElementById(idObj).innerHTML=xmlHttp.responseText;
			$(idObj).blindDown();$(idVerMas).fade();
		}
	}
	xmlHttp.open("GET", '/ajax/docsmonths/'+idTipo, true);
	xmlHttp.send(null);
}

var idCvShown = null;
var idVerMasHidden = null;

function showCv(idObj, idVerMas, idVerMenos)
{
	$(idObj).blindDown();
	$(idVerMas).fade();
	$(idVerMenos).appear();
	
	if (idCvShown != null)
	{
		$(idCvShown).blindUp();
		$(idVerMasHidden).appear();
	}
	
	idCvShown = idObj;
	idVerMasHidden = idVerMas;
}

function hideCv(idObj, idVerMas, idVerMenos)
{
	$(idObj).blindUp();
	$(idVerMenos).fade();
	$(idVerMas).appear();
	idCvShown = null;
}

function floatingFormToggleVisibility(formDivId, transpDivId, id)
{
	if ($(formDivId).visible())
	{
		// tancar
		$(formDivId).fade({duration: 0.4});
		$(transpDivId).fade({duration: 0.4});		
	}
	else
	{
		// obrir - "resettem" el formulari primer
		$("contactBoxProgress_"+id).fade({duration: 0.1});
		$("contactBoxFormDiv_"+id).appear({duration: 0.1});
		$("contactBoxThankYou_"+id).fade({duration: 0.1});
		
		$("contactBoxNombre_"+id).value = "";
		$("contactBoxMail_"+id).value = "";
		$("contactBoxMotivo_"+id).value = "";
		$("contactBoxTexto_"+id).value = "";
			
		$(formDivId).appear({duration: 0.4});
		$(transpDivId).appear({duration: 0.4});
	}

	/*if (!$(transpDivId).visible())
		$(transpDivId).appear({duration: 0.4});
	else
		$(transpDivId).fade({duration: 0.4});

	if (!$(formDivId).visible())
		$(formDivId).appear({duration: 0.4});
	else
		$(formDivId).fade({duration: 0.4});*/
}



function loginBoxToggleVisibility(formDivId, transpDivId, id)
{
	if ($(formDivId).visible())
	{
		// tancar
		$(formDivId).fade({duration: 0.4});
		$(transpDivId).fade({duration: 0.4});		
	}
	else
	{
		// obrir - "resettem" el formulari primer
		$("loginBoxFormDiv_"+id).appear({duration: 0.1});
		
/*		$("contactBoxNombre_"+id).value = "";
		$("contactBoxMail_"+id).value = "";
		$("contactBoxMotivo_"+id).value = "";
		$("contactBoxTexto_"+id).value = "";
*/			
		$(formDivId).appear({duration: 0.4});
		$(transpDivId).appear({duration: 0.4});
	}
}



function contactBoxSubmit(id)
{
	//var url = "/ajax/contactBoxSubmit";
	var url = "/ajax/contact";
	
	$("contactBoxProgress_"+id).appear({duration: 0.2});
	
	var form=new MultiPartFormData();
	form.addVariable("id", id);
	form.addVariable("nombre", $("contactBoxNombre_"+id).value);
	form.addVariable("mail", $("contactBoxMail_"+id).value);
	form.addVariable("motivo", $("contactBoxMotivo_"+id).value);
	form.addVariable("texto", $("contactBoxTexto_"+id).value);	
	form.addVariable("formDestination", $("formDestination_"+id).value);	
	form.addVariable("formDescription", $("formDescription_"+id).value);	
	form.finish();

	var post=form.getData();
	
	ajaxPost(url, post, "multipart/form-data; boundary=\""+form.getBoundary()+"\"", "contactBoxSubmitCallback", true);
}




function contactBoxSubmitCallback(ajax)
{
	var num = ajax.responseXML.getElementsByTagName("PlayGround")[0].childNodes[0].nodeValue;
	
	$("contactBoxProgress_"+num).fade({duration: 0.2});
	$("contactBoxFormDiv_"+num).fade({duration: 0.2});
	$("contactBoxThankYou_"+num).appear();
}





function comentBoxToggleVisibilityForReply(formDivId, transpDivId, id, idComentarioReplied, quote)
{
	comentBoxToggleVisibility(formDivId, transpDivId, id);

	$("commentBoxTexto_"+id).value = "{cita}\n" + quote.replace(/∂/g, "\n").replace(/\{cita\}/g, "") + "\n{cita}";
	$("idComentario_"+id).value = idComentarioReplied;
}



function comentBoxToggleVisibility(formDivId, transpDivId, id)
{
	if ($(formDivId).visible())
	{
		// tancar
		$(formDivId).fade({duration: 0.4});
		$(transpDivId).fade({duration: 0.4});		
	}
	else
	{
		// obrir - "resettem" el formulari primer
		$("commentBoxProgress_"+id).fade({duration: 0.1});
		$("commentBoxFormDiv_"+id).appear({duration: 0.1});
		$("commentBoxThankYou_"+id).fade({duration: 0.1});
		
		//$("commentBoxNombre_"+id).value = "";
		$("commentBoxMail_"+id).value = "";
//		$("commentBoxMotivo_"+id).value = "";
		$("commentBoxTexto_"+id).value = "";
		$("commentBoxCAPTCHA_"+id).value = "";
		regenCaptcha($("commentCAPTCHA"));
		
		$(formDivId).appear({duration: 0.4});
		$(transpDivId).appear({duration: 0.4});
	}
}

function commentBoxSubmit(id)
{
	//var url = "/ajax/contactBoxSubmit";
	var url = "/ajax/comment";
	
	$("commentBoxProgress_"+id).appear({duration: 0.2});
	
	var form=new MultiPartFormData();
	form.addVariable("id", id);
	form.addVariable("nombre", $("commentBoxNombre_"+id).value);
	form.addVariable("mail", $("commentBoxMail_"+id).value);
	form.addVariable("texto", $("commentBoxTexto_"+id).value);	
	form.addVariable("idDocumento", $("idDocumento_"+id).value);	
	form.addVariable("idComentario", $("idComentario_"+id).value);	
	form.addVariable("captcha", $("commentBoxCAPTCHA_"+id).value);	
	form.addVariable("urlDocumento", window.location.href);	
	
	form.finish();

	var post=form.getData();
	
	ajaxPost(url, post, "multipart/form-data; boundary=\""+form.getBoundary()+"\"", "commentBoxSubmitCallback", true);
}





function commentBoxSubmitCallback(ajax)
{
	var num = ajax.responseXML.getElementsByTagName("PlayGround")[0].childNodes[0].nodeValue;

	var submitErrorNodes = ajax.responseXML.getElementsByTagName("SubmitError");
	
	$("commentBoxProgress_"+num).fade({duration: 0.2});

	var errStr=null;
	if (submitErrorNodes!=null && submitErrorNodes.length>0)
	{
		errStr=submitErrorNodes[0].childNodes[0].nodeValue;
		regenCaptcha($("commentCAPTCHA"));
		alert(errStr);
		return;
	}
	
	$("commentBoxFormDiv_"+num).fade({duration: 0.4});
	$("commentBoxThankYou_"+num).appear({duration: 0.4});
	
	loadDocCommentsAjax("commentsDiv", num);
}



function ajaxGetDocFaq(idDoc, idObj, idProgress)
{
	var xmlHttp;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e){
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
	      	document.getElementById(idObj).innerHTML=xmlHttp.responseText;
			$(idObj).blindDown({duration: 0.4});
			$(idObj).style.paddingBottom="0px";
			$(idObj).style.paddingTop="0px";
			$(idObj).morph("padding-bottom: 50px; padding-top: 50px;", {duration: 0.4});
			$(idProgress).blindUp({duration: 0.4});
//			$(idProgress).style.visibility="hidden";
		}
	}
	xmlHttp.open("GET", '/ajax/docfaq/'+idDoc, true);
	xmlHttp.send(null);
}

var loginJustToggled = false;
function toggleMiSespmLoginBox()
{
	var e = $('miSespmMenu');
	var lb = $('miSespmMenuLoginBox');
	if (e.className == "menuTopLinkMiSespm")
	{
		e.className = "menuTopLinkMiSespmSelected";
		//lb.style.display = "inherit"
		lb.blindDown({duration: 0.3});
	}
	else
	{
		//lb.style.display = "none"
		lb.blindUp({duration: 0.3, afterFinish: function() {$('miSespmMenu').className="menuTopLinkMiSespm";}});
		//e.className = "menuTopLinkMiSespm";
	}
	
	loginJustToggled = true;
}




function submitLoginForm(usernameDivId, passDivId)
{
	var url = "/ajax/auth/login";
	
	//document.getElementById("progress").style.visibility="visible";
	
	var form=new MultiPartFormData();
	form.addVariable("loginUsername", $(usernameDivId).value);
	form.addVariable("loginPassword", $(passDivId).value);
	
	form.finish();

	var post=form.getData();
	
	ajaxPost(url, post, "multipart/form-data; boundary=\""+form.getBoundary()+"\"", "submitLoginFormCallback", true);
}

function submitLoginFormCallback(ajax)
{
	var authOk = ajax.responseXML.getElementsByTagName("PlayGround")[0].childNodes[0].childNodes[0].nodeValue;	
	var username = ajax.responseXML.getElementsByTagName("PlayGround")[0].childNodes[1].childNodes[0].nodeValue;

	if (authOk == 'migrar')
	{
		alert("Bienvenido a la nueva Web de la SESPM.\n\nA continuación será redirigido a una página de actualización de datos para que pueda acceder a las secciones privadas de la web.");
		window.location.href="/migrar";	
	}
	else if (authOk == 'true')
	{
		location.reload();
	}
	else
	{
		alert('Autenticación incorrecta!');
	}

	//document.getElementById("pageLenLines").value = num;
	//document.getElementById("progress").style.visibility="hidden";	
}

function logoutUser()
{
	var url = "/ajax/auth/logout";
	
	var form=new MultiPartFormData();
	form.finish();
	var post=form.getData();
	ajaxPost(url, post, "multipart/form-data; boundary=\""+form.getBoundary()+"\"", "logoutCallback", true);
}

function logoutCallback(ajax)
{
	location.reload();
}

function sociosSearch(nomFilt, apeFilt, numSocFilt, mailFilt)
{
	if (nomFilt.trim().length==0 && apeFilt.trim().length==0 && numSocFilt.trim().length==0 && mailFilt.trim().length==0)
	{
		alert("Por favor introduzca algún dato para filtrar");
		return;
	}
	
//	sociosSearchIniciales(nomFilt, apeFilt, numSocFilt, mailFilt);
	sociosSearchResults(nomFilt, apeFilt, numSocFilt, mailFilt);
}

function sociosSearchIniciales(nomFilt, apeFilt, numSocFilt, mailFilt)
{
	$('indexContainer').blindUp({duration: 0.4, queue: {position:"end", scope:"sociosSearch"}});
		
	var url = "/ajax/busca_iniciales_socios/" + encodeSearchParam(nomFilt) + "/" + encodeSearchParam(apeFilt) + "/" + encodeSearchParam(numSocFilt) + "/" + encodeSearchParam(mailFilt);
	
	var form=new MultiPartFormData();
	form.finish();
	var post=form.getData();
	ajaxPost(url, post, "multipart/form-data; boundary=\""+form.getBoundary()+"\"", "sociosSearchInicialesCallback", true);	
}

function sociosSearchInicialesCallback(ajax)
{
	$('indexDiv').innerHTML = ajax.responseText;
	$('indexContainer').blindDown({duration: 0.4, queue: {position:"end", scope:"sociosSearch"}});
}

function sociosSearchResults(nomFilt, apeFilt, numSocFilt, mailFilt)
{
	$('resultsContainer').blindUp({duration: 0.4, queue: {position:"end", scope:"sociosSearch"}});
		
	var url = "/ajax/busca_socios/" + encodeSearchParam(nomFilt) + "/" + encodeSearchParam(apeFilt) + "/" + encodeSearchParam(numSocFilt) + "/" + encodeSearchParam(mailFilt);
	
	var form=new MultiPartFormData();
	form.finish();
	var post=form.getData();
	ajaxPost(url, post, "multipart/form-data; boundary=\""+form.getBoundary()+"\"", "sociosSearchResultsCallback", true);
	
}

function sociosSearchResultsCallback(ajax)
{
	$('resultsDiv').innerHTML = ajax.responseText;
	$('resultsContainer').blindDown({duration: 0.4, queue: {position:"end", scope:"sociosSearch"}});
}

function showSociosRes(divId)
{
	var i=1;
	var ob=$('res'+i);
	var wasOpen=false;
	while (ob!=null)
	{
		if (ob.visible())
		{
			if (divId!="res"+i)
				ob.blindUp({duration: 0.4, queue: {position:"end", scope:"sociosRes"}});
			else
				wasOpen=true;
		}
		
		i++;
		ob=$('res'+i);
	}
	if (!wasOpen)
		$(divId).blindDown({duration: 0.4, queue: {position:"end", scope:"sociosRes"}});
}


function ftpLeavePage(e) {
    var btnEnviar = document.getElementById("btnEnviar");

    if (btnEnviar != null)
    {
	if(!e) e = window.event;
	//e.cancelBubble is supported by IE - this will kill the bubbling process.
	e.cancelBubble = true;
	e.returnValue = '¿Seguro que desea abandonar la página? Debe pulsar el botón enviar para completar la carga de ficheros.'; //This is displayed on the dialog

	//e.stopPropagation works in Firefox.
	if (e.stopPropagation) {
		e.stopPropagation();
		e.preventDefault();
	}
    }
}


var _currentPollFormNumber = "";

function castVote(formNumber) {
    document.getElementById("pollProgress_" + formNumber).style.visibility="visible";
    _currentPollFormNumber = formNumber;

    var f = $('pollForm_' + formNumber);
    var idOption = null;
    var idPoll = f.idPoll.value;

    for (var i = 0; i < f.pollAnswer.length; i++) {
	if (f.pollAnswer[i].checked) {
	    idOption = f.pollAnswer[i].value;
	    break;
	}
    }

    if (idOption == null) {
	alert("Por favor, seleccione la opción por la que desea votar.");
	document.getElementById("pollProgress_" + formNumber).style.visibility="hidden";
	return;
    }

    //alert("Casting vote for option "+idOption+" of poll "+idPoll);
    var url = "/ajax/pollvote/" + idPoll + "/" + idOption;
    ajaxGet(url, "castVoteCallback", true);

    url = "/ajax/pollresults/" + idPoll;
    ajaxGet(url, "pollResultsCallback", true);

}

function castVoteCallback(ajax) {
    //alert("Vote cast!");
    document.getElementById("pollProgress_" + _currentPollFormNumber).style.visibility="hidden";
}

function pollResultsCallback(ajax) {
    //alert("Poll results received");
    document.getElementById("pollProgress_" + _currentPollFormNumber).style.visibility="hidden";
    document.getElementById("pollProgress_" + _currentPollFormNumber).style.display="none";
    $('poll_' + _currentPollFormNumber).innerHTML = ajax.responseText;
}

function loadPollResults(formNumber) {
    document.getElementById("pollProgress_" + formNumber).style.visibility="visible";
    document.getElementById("pollProgress_" + formNumber).style.display="inline";
    _currentPollFormNumber = formNumber;
    
    var f = $('pollForm_' + formNumber);
    var idPoll = f.idPoll.value;

    url = "/ajax/pollresults/" + idPoll;
    ajaxGet(url, "pollResultsCallback", true);
}
