// Datos de configuración estáticos
d = new Date();
var defaultMonth = d.getMonth()+1;
var defaultAno = d.getFullYear();
var defaultDia = d.getDate();
var iniMonth = defaultMonth;
var iniAno = defaultAno;
var maxAno = defaultAno + 1;
var minAno = defaultAno - 1;
var titulo_agenda = "";
var fechaHoy = "";
// Datos de configuración dinámicos
var diasLibres = [7,6];
var tiposCSS = ["Normal","Evento","Festivo"];
var objCalendar;
var maxDias=[31,28,31,30,31,30,31,31,30,31,30,31];
var statusOpt = 1;
var title = "";
var positionTitle = "head";
var aMessage = [];
function tipsDayDesc(titulo,tagline,isFestivo,url){
	this.titulo = titulo;
	this.tagline = tagline;
	this.isFestivo = isFestivo;
	this.url = url;
}


function windowPosition()
{
LeftPosition = (screen.width-200)/2;
TopPosition = (screen.height-225)/2;
window.moveTo(LeftPosition,TopPosition);
}

function twoDigits(num)
{
	num += 0;
	if (num < 10)
	{
		num = "0"+num;
	}
	return num;
}

function calendar_event(id,mes,ano){
	if ((ano % 4) == 0){maxDias[1] = 29;}
	this._div = id;
	objCalendar = this;
	fechaHoy = ""+defaultAno+twoDigits(defaultMonth)+twoDigits(defaultDia);
	this.init(mes,ano);
	//windowPosition();
}

calendar_event.prototype.setTitle = function(titulo,pos)
{
	title = titulo;	
	if (pos == "foot" || pos == "head")
	{positionTitle = pos;}
}

calendar_event.prototype.init = function(mes,ano)
{
	this._mes = mes;
	this._ano = ano;
	// Dia de la semana inicial.
	var mostrarDia = mes+"/01/"+ano;
	var getDia = new Date(mostrarDia);
	this._initDay = getDia.getDay();
	if (this._initDay == 0) {this._initDay = 7;} //Si es domingo adaptar al sistema Europeo
}

calendar_event.prototype.toggleStatus = function (dia)
{
	var mes = this._mes;ano = this._ano;
	var swDel = 0;

	switch(statusOpt)
	{
		case (1): //Eventos
		{
			diasEvento[mes-1] = checkOpt(dia,diasEvento[mes-1]);
			break;
		}
	}
	this.draw();

		function checkOpt(dia,listaDias)
		{
			if ((valor = buscarDia(dia,listaDias)) <= -1)
			{
				listaDias = addDia(dia,listaDias);
			}
			else{
				listaDias = delDia(valor,listaDias);
			}
			return listaDias;
		}
		
		function buscarDia(dia,listaDia)
		{
			var day,swEncontrado=-1;
			for (day in listaDia)
			{
				if (listaDia[day] == dia)
				{swEncontrado = day;break;}
			}
			return swEncontrado;
		}
		
		function addDia(dia,listaDia)
		{
			listaDia.push(dia);
			listaDia.sort();
			return listaDia;
		}
		
		function delDia(posDia,listaDia)
		{
			listaDia.splice(posDia,1);
			return listaDia;
		}
		

}


calendar_event.prototype.changeMonth = function(sw) //-1:= -1 mes / 1:= +1 mes
{
	if ((sw == -1) && (this._mes == 1))
	{  
		if (eval(this._ano - 1) < minAno)
		{
			alert(txtMinAno);
			return false;
		}
		this._mes = 12;
		this._ano -= 1;
		var getParam = "common/calendar/getData.php?ano=" + this._ano;
		sndReq(getParam,"verCalendario",this);
	}else
	if ((sw == 1) && (this._mes == 12))
	{  
		if ((eval(this._ano + 1)) > maxAno)
		{
				alert(txtMaxAno);
				return false;
		}
		this._mes = 1;
		this._ano += 1;
		var getParam = "common/calendar/getData.php?mes=1&ano=" + this._ano;
		sndReq(getParam,"verCalendario",this);
	}
	else
	{
		this._mes += sw;
		this.init(this._mes,this._ano);
		this.draw();
	}
	return true;
}


calendar_event.prototype.draw = function()
{
	//init variables;
	var mes = this._mes;ano = this._ano;
	var numDay = 1;
	var _blankCells = false;
 	var dia;
	var x=1;

	strOutput = "<table border='0' cellpadding='3' cellspacing='1' align=\"center\">";
	/* Write Cabecera month */
	strOutput += "<tr id=\"sCabecera\">";
	strOutput += "<th align=\"center\" class=\"cabSemana\"><a href=\"javascript:void(0);\" onClick=\"return objCalendar.changeMonth(-1);\" title=\""+controlMes[0]+"\">&lt;</a></td>";
	strOutput += "<th colspan=\"5\" align=\"center\" class=\"cabSemana\">"+nomMes[mes-1] + " " + ano +"</td>";
	strOutput += "<th align=\"center\" class=\"cabSemana\"><a href=\"javascript:void(0);\" onClick=\"return objCalendar.changeMonth(+1);\" title=\""+controlMes[1]+"\">&gt;</a></td></tr>";
	strOutput += "<tr id=\"sCabecera2\">";
	var claseCabeceraSemana = "cabSemana";
	for(var cabecera=0; cabecera<7; cabecera++)
		{	//claseCabeceraSemana = "Normal";
			//if (dayOnFree(cabecera+1)) {claseCabeceraSemana = "cabSemana";}
			strOutput += "<th class=\"" + claseCabeceraSemana + "\"><a title=\""+nomSemanaLargo[cabecera]+"\">"+nomSemana[cabecera]+"</a></th>";}
	strOutput += "</tr>";
	// Write las semanas
	for (var sem = 1; (sem <= 6 && (numDay <= maxDias[mes-1])); sem++)
	{
	 strOutput += "<tr id='s"+sem+"'>";
	 for (var day = 1; day < 8; day++)
	 {
	 	if (((sem==1) && (day < this._initDay)) || (numDay > maxDias[mes-1]))
		{_blankCells = true;} else {_blankCells = false;}
		if (_blankCells) // Celdas en Blanco...
		{
			strOutput += "<td align=\"right\" class=\"blank\">&nbsp;</td>";
		}
		else
		{
			strOutput += devolverCelda(numDay,day);
			numDay++;
		}
	 }
	 strOutput += "</tr>";
	}
	if (title != "")
	{strOutput += "<t"+positionTitle+"><tr><th colspan='7' class=\"titolCalendar\">"+title+"</th></tr></t"+positionTitle+">";}
	strOutput += "</table>";
	
		
	domlay(objCalendar._div,1,1,1,strOutput);
	//tt_Init();
	function dayOnFree(day)
	{
		var dayWeek,swDayFree = false;
		for (dayWeek in diasLibres)
			{if (diasLibres[dayWeek] == day) {swDayFree = true;break;}}
		return swDayFree;
	}
	
	function devolverCelda(numDay,dd)
	{
		var tipoDay = tiposCSS[0];
		if (dayOnFree(dd))
		{
			tipoDay = "Libre";
		}
		var tips="";
		var url="";
		var returnSTR = numDay;
		var v = ano+""+twoDigits(mes)+twoDigits(numDay);
		var rel = "";
		var rels = "";
		var cVal = 0;
		if (aMessage != null)
		{
			a = aMessage[v];
			if (a != null)
			{
				for (cMsg in a){
					tipoDay = (a[cMsg].isFestivo == 1) ? tiposCSS[2] : tiposCSS[1];
					rel += a[cMsg].titulo+";";
					url = a[cMsg].url; 
					cVal++;
				}
				if (cVal > 1){
					tips = "Esdevenivents";
					url = "index.php?events="+v;
				} else {
					tips = rel.substr(0,rel.length-1);
				}
				tips = " title=\""+tips+"\"";
				if (rel.length > 0){
					rels = " rel=\""+rel+"\"";
				}
				returnSTR = "<a href=\""+url+"\""+tips+"\""+rels+">"+numDay+"</a>";
			}
		}
		//if (v == fechaHoy)
		//{tipoDay += " Hoy"; if (tips == ""){returnSTR = "<a title=\""+hoy+"\"\">"+numDay+"</a>";}}
		return "<td align=\"right\" class=\"" + tipoDay + "\" id=\"d"+numDay+"\">" +returnSTR +"</td>";
	}
	
}


function domlay(id,trigger,lax,lay,content) {
	/*
	 * Cross browser Layer visibility / Placement Routine
	 * Done by Chris Heilmann (mail@ichwill.net)
	 * http://www.ichwill.net/mom/domlay/
	 * Feel free to use with these lines included!
	 * Created with help from Scott Andrews.
	 * The marked part of the content change routine is taken
	 * from a script by Reyn posted in the DHTML
	 * Forum at Website Attraction and changed to work with
	 * any layername. Cheers to that!
	 * Welcome DOM-1, about time you got included... :)
	 */
	// Layer visible
	if (trigger=="1"){
		if (document.layers) document.layers[''+id+''].visibility = "show"
		else if (document.all) document.all[''+id+''].style.visibility = "visible"
		else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "visible"
		}
	// Layer hidden
	else if (trigger=="0"){
		if (document.layers) document.layers[''+id+''].visibility = "hide"
		else if (document.all) document.all[''+id+''].style.visibility = "hidden"
		else if (document.getElementById) document.getElementById(''+id+'').style.visibility = "hidden"
		}
	// Set horizontal position
	if (lax){
		if (document.layers){document.layers[''+id+''].left = lax}
		else if (document.all){document.all[''+id+''].style.left=lax}
		else if (document.getElementById){document.getElementById(''+id+'').style.left=lax+"px"}
		}
	// Set vertical position
	if (lay){
		if (document.layers){document.layers[''+id+''].top = lay}
		else if (document.all){document.all[''+id+''].style.top=lay}
		else if (document.getElementById){document.getElementById(''+id+'').style.top=lay+"px"}
		}
	// change content

	if (content){
	if (document.layers){
		sprite=document.layers[''+id+''].document;
		// add father layers if needed! document.layers[''+father+'']...
		sprite.open();
		sprite.write(content);
		sprite.close();
		}
	else if (document.all) document.all[''+id+''].innerHTML = content;
	else if (document.getElementById){
		//Thanx Reyn!
		rng = document.createRange();
		el = document.getElementById(''+id+'');
		rng.setStartBefore(el);
		htmlFrag = rng.createContextualFragment(content)
		while(el.hasChildNodes()) el.removeChild(el.lastChild);
		el.appendChild(htmlFrag);
		// end of Reyn ;)
		}
	}
}

/* LOADING NEW DATA */
function createRequestObject() {
	var ro;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
		ro = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		ro = new XMLHttpRequest();
		
	}
	return ro;
}

var http = createRequestObject();
var oCal;

function sndReq(action,layout,ooCal) {
	oCal = ooCal;
	layout = document.getElementById(layout);
	layout.innerHTML = "<div style=\" margin:5px auto 5px auto;\"><img  sytle=\"display:block;\" src=\"images/loading.gif\" alt=\"Loading\" /></div><span>Cargant dades</span>";
	if (http){
    http.open('get', action);
    http.onreadystatechange = handleResponse;
    http.send(null);
}else{alert("no support ajax");}
}

function handleResponse() {
	
    if (http.readyState == 4)
	{
		
        var response = http.responseText;
		var idResponse = http.status;
		//document.getElementById("log").innerHTML = document.getElementById("log").innerHTML+"<p>"+response;
		if ((idResponse != 200) && (idResponse != 304)) return false;
		aMessage = new Array();
		if (response.length > 0){
			var aM = response.split("|");
			if (aM.length > 0)
			{
				var posMsg = "";
				for(ct = 0 ; ct < aM.length; ct++)
				{
					h = aM[ct].split("$%");
					if (posMsg.indexOf(h[0]) < 0){
						aMessage[h[0]] = new Array();posMsg += h[0]+";";
					}
					aMessage[h[0]][h[1]] = new tipsDayDesc(h[2],h[3],h[4],h[5]);
				}
			}
		}
		oCal.init(oCal._mes,oCal._ano);
		oCal.draw();
		return true;
	}
}
