/*
'===============================================================================
' Lenguaje:				JavaScript
' Proyecto:				INTRANET CSSD SEVILLA
' Sección: 				
' Archivo:				Calendario.js
' Tipo:					JS 
' Empresa:				Mundivia, S.A.
' Nombre y Apellidos:	Andrés Costa Muñoz [acosta@mundivia.net]
' Fecha de Creación:	21/11/2003
' Revisión:				0
' Descripción:			Funciones para crear un calendario dinámicamente
' Observaciones:		
'
' Registro de modificaciones
' --------------------------
' Marca     Autor     Fecha		  Motivo
' -------   ------	  -------	  ----------------------------------------------
' 		    ACM       21/11/2003  Creación
'===============================================================================
*/

document.write("<style type=text/css>");
document.write("<!--");
document.write(".cal {font-family:Verdana;color:#FFFFFF;FONT-WEIGHT: normal;mso-ansi-language:'ES-TRAD';font-size:6.0pt;mso-bidi-font-size:6.0pt}");
document.write(".calDay {font-family:Verdana;color:#FFFFFF;FONT-WEIGHT: bold;mso-ansi-language:'ES-TRAD';font-size:7.0pt;mso-bidi-font-size:6.0pt}");
document.write(".calNormal {font-family:Verdana;color:#FFFFFF;FONT-WEIGHT: normal;mso-ansi-language:'ES-TRAD';font-size:6.0pt;mso-bidi-font-size:6.0pt}");
document.write(".calShaded {cursor:hand;font-family:Verdana;color:#B0B0B0;FONT-WEIGHT: bold;mso-ansi-language:'ES-TRAD';font-size:6.0pt;mso-bidi-font-size:6.0pt}");
document.write(".calPrioridad1 {cursor:hand;font-family:Verdana;color:#FFFFFF;FONT-WEIGHT: bold;mso-ansi-language:'ES-TRAD';font-size:6.0pt;mso-bidi-font-size:6.0pt;background-color:#FF9900;a:#d9d9d9;}");
document.write(".calPrioridad2 {cursor:hand;font-family:Verdana;color:#FFFFFF;FONT-WEIGHT: bold;mso-ansi-language:'ES-TRAD';font-size:6.0pt;mso-bidi-font-size:6.0pt;background-color:#669900;a:#d9d9d9;}");
document.write(".calPrioridad3 {cursor:hand;font-family:Verdana;color:#FFFFFF;FONT-WEIGHT: bold;mso-ansi-language:'ES-TRAD';font-size:6.0pt;mso-bidi-font-size:6.0pt;background-color:#9966ff;a:#d9d9d9;}");
document.write(".calHighlighted {font-family:Verdana;color:#FFFFFF;FONT-WEIGHT: bold;mso-ansi-language:'ES-TRAD';font-size:6.0pt;mso-bidi-font-size:6.0pt;background-color:#000000;a:#d9d9d9;}");
document.write(".fondoCalendario {background-color:#4092F8;}");
document.write("-->");
document.write("</style>");

function fnCrearCalendario()
{
    onload=init
    function init() {
    	mycalendar.activate()
    }
    
    mycalendar = new Calendar(100,300,25,15)
    mycalendar.build()
    mycalendar.onChange = updateDisplay
    
    writeCSS (mycalendar.css);
    document.write(mycalendar.div);
}


function DynLayer(id,nestref,frame)
{
	if (!is.ns5 && !DynLayer.set && !frame) DynLayerInit()
	this.frame = frame || self
	if (is.ns) {
		if (is.ns4) {
			if (!frame) {
				if (!nestref) var nestref = DynLayer.nestRefArray[id]
				if (!DynLayerTest(id,nestref)) return
				this.css = (nestref)? eval("document."+nestref+".document."+id) : document.layers[id]
			}
			else this.css = (nestref)? eval("frame.document."+nestref+".document."+id) : frame.document.layers[id]
			this.elm = this.event = this.css
			this.doc = this.css.document
		}
		else if (is.ns5) {
			this.elm = document.getElementById(id)
			this.css = this.elm.style
			this.doc = document
		}
		this.x = this.css.left
		this.y = this.css.top
		this.w = this.css.clip.width
		this.h = this.css.clip.height
	}
	else if (is.ie) {
		this.elm = this.event = this.frame.document.all[id]
		this.css = this.frame.document.all[id].style
		this.doc = document
		this.x = this.elm.offsetLeft
		this.y = this.elm.offsetTop
		this.w = (is.ie4)? this.css.pixelWidth : this.elm.offsetWidth
		this.h = (is.ie4)? this.css.pixelHeight : this.elm.offsetHeight
	}
	this.id = id
	this.nestref = nestref
	this.obj = id + "DynLayer"
	eval(this.obj + "=this")
}

function DynLayerMoveTo(x,y) 
{
	if (x!=null) {
		this.x = x
		if (is.ns) this.css.left = this.x
		else this.css.pixelLeft = this.x
	}
	if (y!=null) {
		this.y = y
		if (is.ns) this.css.top = this.y
		else this.css.pixelTop = this.y
	}
}

function DynLayerMoveBy(x,y) 
{
	this.moveTo(this.x+x,this.y+y)
}

function DynLayerShow() 
{
	this.css.visibility = (is.ns4)? "show" : "visible"
}

function DynLayerHide() 
{
	this.css.visibility = (is.ns4)? "hide" : "hidden"
}
DynLayer.prototype.moveTo = DynLayerMoveTo
DynLayer.prototype.moveBy = DynLayerMoveBy
DynLayer.prototype.show = DynLayerShow
DynLayer.prototype.hide = DynLayerHide
DynLayerTest = new Function('return true')

// DynLayerInit Function
function DynLayerInit(nestref) 
{
	if (!DynLayer.set) DynLayer.set = true
	if (is.ns) {
		if (nestref) ref = eval('document.'+nestref+'.document')
		else {nestref = ''; ref = document;}
		for (var i=0; i<ref.layers.length; i++) {
			var divname = ref.layers[i].name
			DynLayer.nestRefArray[divname] = nestref
			var index = divname.indexOf("Div")
			if (index > 0) {
				eval(divname.substr(0,index)+' = new DynLayer("'+divname+'","'+nestref+'")')
			}
			if (ref.layers[i].document.layers.length > 0) {
				DynLayer.refArray[DynLayer.refArray.length] = (nestref=='')? ref.layers[i].name : nestref+'.document.'+ref.layers[i].name
			}
		}
		if (DynLayer.refArray.i < DynLayer.refArray.length) {
			DynLayerInit(DynLayer.refArray[DynLayer.refArray.i++])
		}
	}
	else if (is.ie) {
		for (var i=0; i<document.all.tags("DIV").length; i++) {
			var divname = document.all.tags("DIV")[i].id
			var index = divname.indexOf("Div")
			if (index > 0) {
				eval(divname.substr(0,index)+' = new DynLayer("'+divname+'")')
			}
		}
	}
	return true
}
DynLayer.nestRefArray = new Array()
DynLayer.refArray = new Array()
DynLayer.refArray.i = 0
DynLayer.set = false

// Slide Methods
function DynLayerSlideTo(endx,endy,inc,speed,fn) 
{
	if (endx==null) endx = this.x
	if (endy==null) endy = this.y
	var distx = endx-this.x
	var disty = endy-this.y
	this.slideStart(endx,endy,distx,disty,inc,speed,fn)
}

function DynLayerSlideBy(distx,disty,inc,speed,fn) 
{
	var endx = this.x + distx
	var endy = this.y + disty
	this.slideStart(endx,endy,distx,disty,inc,speed,fn)
}

function DynLayerSlideStart(endx,endy,distx,disty,inc,speed,fn) 
{
	if (this.slideActive) return
	if (!inc) inc = 10
	if (!speed) speed = 20
	var num = Math.sqrt(Math.pow(distx,2) + Math.pow(disty,2))/inc
	if (num==0) return
	var dx = distx/num
	var dy = disty/num
	if (!fn) fn = null
	this.slideActive = true
	this.slide(dx,dy,endx,endy,num,1,speed,fn)
}

function DynLayerSlide(dx,dy,endx,endy,num,i,speed,fn) 
{
	if (!this.slideActive) return
	if (i++ < num) {
		this.moveBy(dx,dy)
		this.onSlide()
		if (this.slideActive) setTimeout(this.obj+".slide("+dx+","+dy+","+endx+","+endy+","+num+","+i+","+speed+",\""+fn+"\")",speed)
		else this.onSlideEnd()
	}
	else {
		this.slideActive = false
		this.moveTo(endx,endy)
		this.onSlide()
		this.onSlideEnd()
		eval(fn)
	}
}

function DynLayerSlideInit() {}
DynLayer.prototype.slideInit = DynLayerSlideInit
DynLayer.prototype.slideTo = DynLayerSlideTo
DynLayer.prototype.slideBy = DynLayerSlideBy
DynLayer.prototype.slideStart = DynLayerSlideStart
DynLayer.prototype.slide = DynLayerSlide
DynLayer.prototype.onSlide = new Function()
DynLayer.prototype.onSlideEnd = new Function()

// Clip Methods

function DynLayerClipInit(clipTop,clipRight,clipBottom,clipLeft) 
{
	if (is.ie) {
		if (arguments.length==4) this.clipTo(clipTop,clipRight,clipBottom,clipLeft)
		else if (is.ie4) this.clipTo(0,this.css.pixelWidth,this.css.pixelHeight,0)
	}
}

function DynLayerClipTo(t,r,b,l) 
{
	if (t==null) t = this.clipValues('t')
	if (r==null) r = this.clipValues('r')
	if (b==null) b = this.clipValues('b')
	if (l==null) l = this.clipValues('l')
	if (is.ns) {
		this.css.clip.top = t
		this.css.clip.right = r
		this.css.clip.bottom = b
		this.css.clip.left = l
	}
	else if (is.ie) this.css.clip = "rect("+t+"px "+r+"px "+b+"px "+l+"px)"
}

function DynLayerClipBy(t,r,b,l) 
{
	this.clipTo(this.clipValues('t')+t,this.clipValues('r')+r,this.clipValues('b')+b,this.clipValues('l')+l)
}

function DynLayerClipValues(which) 
{
	if (is.ie) var clipv = this.css.clip.split("rect(")[1].split(")")[0].split("px")
	if (which=="t") return (is.ns)? this.css.clip.top : Number(clipv[0])
	if (which=="r") return (is.ns)? this.css.clip.right : Number(clipv[1])
	if (which=="b") return (is.ns)? this.css.clip.bottom : Number(clipv[2])
	if (which=="l") return (is.ns)? this.css.clip.left : Number(clipv[3])
}

DynLayer.prototype.clipInit = DynLayerClipInit
DynLayer.prototype.clipTo = DynLayerClipTo
DynLayer.prototype.clipBy = DynLayerClipBy
DynLayer.prototype.clipValues = DynLayerClipValues

// Write Method
function DynLayerWrite(html) 
{
	if (is.ns) {
		this.doc.open()
		this.doc.write(html)
		this.doc.close()
	}
	else if (is.ie) {
		this.event.innerHTML = html
	}
}
DynLayer.prototype.write = DynLayerWrite

// BrowserCheck Object
function BrowserCheck() 
{
	var b = navigator.appName
	if (b=="Netscape") this.b = "ns"
	else if (b=="Microsoft Internet Explorer") this.b = "ie"
	else this.b = b
	this.version = navigator.appVersion
	this.v = parseInt(this.version)
	this.ns = (this.b=="ns" && this.v>=4)
	this.ns4 = (this.b=="ns" && this.v==4)
	this.ns5 = (this.b=="ns" && this.v==5)
	this.ie = (this.b=="ie" && this.v>=4)
	this.ie4 = (this.version.indexOf('MSIE 4')>0)
	this.ie5 = (this.version.indexOf('MSIE 5')>0)
	this.min = (this.ns||this.ie)
}
is = new BrowserCheck()

// CSS Function
function css(id,left,top,width,height,color,vis,z,other) 
{
    if (id=="START") return '<STYLE TYPE="text/css">\n'
	else if (id=="END") return '</STYLE>'
	
    //var str = (left!=null && top!=null)? '#'+id+' {position:absolute; left:'+left+'px; top:'+top+'px;' : '#'+id+' {position:relative;'

       		var str =  '{position:relative;';

    
	if (arguments.length>=4 && width!=null) str += ' width:'+width+'px;'
	if (arguments.length>=5 && height!=null) {
		str += ' height:'+height+'px;'
		if (arguments.length<9 || other.indexOf('clip')==-1) str += ' clip:rect(0px '+width+'px '+height+'px 0px);'
	}
	if (arguments.length>=6 && color!=null) str += (is.ns)? ' layer-background-color:#000000'+color+';' : ' background-color:'+color+';'
	if (arguments.length>=7 && vis!=null) str += ' visibility:'+vis+';'
	if (arguments.length>=8 && z!=null) str += ' z-index:'+z+';'
	if (arguments.length==9 && other!=null) str += ' '+other
	str += '}\n'
	return str
}
function writeCSS(str,showAlert) 
{
	str = css('START')+str+css('END')
	document.write(str)
	if (showAlert) alert(str)
}

function Calendar(x,y,hSpace,vSpace) 
{
	this.name = "Calendar"+(Calendar.count++)
	this.x = x
	this.y = y
	this.hSpace = hSpace
	this.vSpace = vSpace
	this.obj = this.name + "Object"
	eval(this.obj + "=this")
}

{
    var p = Calendar.prototype
    //p.bgColor = '#000000'
    //p.dayBarColor = '#000000'
	p.active = false
    p.switchMonths = true
    p.selectToday = true
    p.daylist = new Array('DO','LU','MA','MI','JU','VI','SA')
    p.changeYear = CalendarChangeYear
    p.changeMonth = CalendarChangeMonth
    p.changeDay = CalendarChangeDay
    p.selectDay = CalendarSelectDay
    p.selectNone = CalendarSelectNone
    p.setDate = CalendarSetDate
    p.useDate = CalendarUseDate
    p.writeDate = CalendarWriteDate
    p.build = CalendarBuild
    p.activate = CalendarActivate
    p.onChange = new Function()
}

function CalendarBuild(year,month,day) 
{
	this.w = 7*this.hSpace
	this.h = 7*this.vSpace
	this.useDate(year,month,day)

    this.div = "<table width=100% border=0 cellspacing=0 cellpadding=0 class=fondoCalendario>";
    this.div += '<tr><td width=25 align=right><a href="javascript:mycalendar.changeMonth(-1)" class="CalDay"><img src="./imagenes/calendarIzq.gif" border=0></a></td><td height=20 width=80%><div id="MesCalendario" align=center class="CalDay">' + monthList[this.month] + " - " + this.year  + '</div></td><td width=25 align=left><a href="javascript:mycalendar.changeMonth(1)" class="CalDay"><img src="./imagenes/calendarDcha.gif" border=0></a></td></tr>\n';
    this.div += '<tr><td colspan=3><div id="'+this.name+'Cal">\n'+
	
    '<div id="'+this.name+'CalDayBar"><table width=100% border=0 cellspacing=0 cellpadding=0 class=fondoCalendario><tr>\n'
	for (var i=0;i<7;i++) {
		this.div+='<td><div id="'+this.name+'CalDay'+this.daylist[i]+'" class="calDay">&nbsp;'+this.daylist[i]+'</div></td>\n'
	}
	this.div+='</tr></table></div><tr><td colspan=3><table width=100% border=0 cellspacing=0 cellpadding=0 class=fondoCalendario><tr>\n'
    
	for (var i=0;i<42;i++) {
		
        this.div+='<td><div id="'+this.name+'Cal'+i+'">'+this.spotstr[i]+'</div></td>\n'
        
        if (i>0 && (i+1)%7 ==0)
        	this.div +='</tr></tr>';
	}
	
    this.div+='</tr></table></td></tr></td></tr></div>';
    
    this.div+='</table>';

}

function CalendarActivate(doChange) 
{
	this.lyr = new DynLayer(this.name+'Cal')
	this.spot = new Array()
	for (var i=0;i<42;i++) {
		this.spot[i] = new DynLayer(this.name+'Cal'+i)
		if (is.ns) this.spot[i].elm.captureEvents(Event.MOUSEDOWN)
		this.spot[i].elm.onmousedown = new Function(this.obj+'.selectDay('+i+'); return false;')
	}
	if (doChange!=false) this.onChange()
}

function getMonthLength(month,year) 
{
	var monthlength = new Array(31,28,31,30,31,30,31,31,30,31,30,31)
	if (month==1 && (year/4==Math.floor(year/4) || year/400==Math.floor(year/400))) {
		return 29
	}
	else return monthlength[month]
}

function CalendarChangeYear(dy) 
{
	this.setDate(this.year+dy,this.month,this.day)
}

function CalendarChangeMonth(dm) 
{
	this.setDate(this.year,this.month+dm,this.day)
}

function CalendarChangeDay(dd) 
{
	this.selectDay(this.todayspot+dd)
}

function CalendarSetDate(year,month,day) 
{
	if (this.active) return false
	else this.active = true
	this.useDate(year,month,day)
	this.writeDate()
	this.onChange()
}

function CalendarUseDate(year,month,day) 
{
	var d = new Date()
	if (month==null) month = d.getMonth()
	if (day==null) day = d.getDate()
	if (year==null) year = d.getYear()
	if (year<100) year += 1900
	if (month<0) {
		month = 11
		year -= 1
	}
	else if (month>11) {
		month = 0
		year += 1
	}
	var l = getMonthLength(month,year)
	if (day>l || day<0) {
		day = l
	}
	
	this.year = year
	this.month = month
	this.day = day

	var date = new Date(this.year,this.month,this.day)
	date.setDate(1)
	this.calshift = (this.month==0)? date.getDay()+1 : date.getDay()  // days from last month to show
	var thisMonth_length = getMonthLength(this.month,this.year)
	var lastMonth = (this.month==0)? 11 : this.month-1
	var lastMonth_length = getMonthLength(lastMonth,this.year)
	var calstart = lastMonth_length-this.calshift+1  // first day to show

	var which,c;
	day = 0
	this.spotday = new Array()
	this.spotstr = new Array()

	for (var i=0;i<this.calshift;i++) {  // days before this month
		this.spotday[i] = calstart+i
		this.spotstr[i] = CalendarGetString(this.spotday[i],0,this.month,this.year)
	}
	this.firstspot = this.calshift  // spot index of day 1
	for (var i=this.calshift;i<thisMonth_length+this.calshift;i++) {  // days in this month
		this.spotday[i] = i-this.calshift+1
		//if (this.spotday[i]==this.day && this.selectToday) {
		//	which = 2
		//	this.todayspot = i  // the highlighted day
		//}
		//else {
			which = 1
		//}
		this.spotstr[i] = CalendarGetString(this.spotday[i],which,this.month,this.year)
	}
	c = 1
	this.lastspot = thisMonth_length+this.calshift
	for (var i=thisMonth_length+this.calshift;i<42;i++) {  // days after this month
		this.spotday[i] = c++
		this.spotstr[i] = CalendarGetString(this.spotday[i],0,this.month,this.year)
	}
}

function CalendarWriteDate() 
{
	for (var i=0;i<42;i++) {
		this.spot[i].write(this.spotstr[i])
	}
	this.active = false
}

var tblFechaEvento = new Array();  // año, mes, dia, prioridad, mensaje


function CalendarGetString(day,which,mes,anio) 
{
	var dia = day;
    
    if (day<10) day = '&nbsp;'+day
	
    var sSalida;
    
    if (which==0) sSalida = '<div class="calShaded">&nbsp;'+day+'&nbsp;</div>';
	if (which==1) sSalida = '<div class="calNormal">&nbsp;'+day+'&nbsp;</div>';
	if (which==2) sSalida = '<div class="calHighlighted">&nbsp;'+day+'&nbsp;</div>';

    // Buscamos el evento
    for(var j=0;j<tblFechaEvento.length;j++)
    { 
       
      if (which!=0 && anio == tblFechaEvento[j][0] && parseInt(mes) == (parseInt(tblFechaEvento[j][1])-1) && parseInt(dia) == parseInt(tblFechaEvento[j][2]))
      {
      	if (tblFechaEvento[j][3]==1) sSalida = '<div class="calPrioridad1">&nbsp;'+ fnAltTexto_Text(tblFechaEvento[j][4],day) +'&nbsp;</div>';
        if (tblFechaEvento[j][3]==2) sSalida = '<div class="calPrioridad2">&nbsp;'+ fnAltTexto_Text(tblFechaEvento[j][4],day) +'&nbsp;</div>';
        if (tblFechaEvento[j][3]==3) sSalida = '<div class="calPrioridad3">&nbsp;'+ fnAltTexto_Text(tblFechaEvento[j][4],day) +'&nbsp;</div>';
      
        j = tblFechaEvento.length + 1;

      }
    }
    return sSalida;    
}


function CalendarSelectDay(i) 
{
	if (i==this.todayspot || this.active) return
    
	// Para moverse entre meses del Calendario
    if (i<this.firstspot && this.switchMonths) {
		this.setDate(this.year,this.month-1,this.spotday[i])
	}
	else if (i>=this.lastspot && this.switchMonths) {
		this.setDate(this.year,this.month+1,this.spotday[i])
	}
    
}

function CalendarSelectNone() 
{
	if (this.todayspot!=null) this.spot[this.todayspot].write(CalendarGetString(this.spotday[this.todayspot],1))
	this.todayspot = null
}

Calendar.count = 0

monthList = Array('Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre')

function updateDisplay() {
    	
        var obj = document.getElementById("MesCalendario");
        obj.innerHTML = monthList[this.month] + " - " + this.year;

}




