/**
 * Calendar Script
 * Creates a calendar widget which can be used to select the date more easily than using just a text box
 * http://www.openjs.com/scripts/ui/calendar/
 * 
 * Neia Ltda 2009 todos los derechos reservados
 */
window.onload=inicializar;
//variables del banner
var cont =-1;
var delay = 6000;
var lock = false;
var run;
var ruta="./rsc/img/banner/";
var rutaBanner="./rsc/img/banner/";
var iniciado=false;
//
imgSigCont=false;
imgAntCont=false;

function inicializar(){
    iniciarCalendario();
    iniciarBanner();
    ubicarPrimerCampo();
}
function ubicarPrimerCampo(){
    if(document.forms[0]){
        var encontrado = false;
        for(var i=0; i < document.forms[0].length && !encontrado; i++){
            if (document.forms[0][i].type != "hidden"){    
                if (document.forms[0][i].disabled != true){
                    document.forms[0][i].focus();
                    encontrado = true;
                }
            }
        }
    }    
}
function iniciarCalendario(){
	elementos=getElementsByClassName('calendario','');
	activarCalendario(elementos);
}

/*busca todos los elementos cuyo class sea calendario*/
function activarCalendario(elementos){
	for(i=0;i<elementos.length;i++){
		calendar.set(elementos[i].id);
	}
}
function getElementsByClassName(classname, node) {

	if(!node) node = document.getElementsByTagName("body")[0];
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
      if(re.test(els[i].className))a.push(els[i]);
    return a;
}
calendar = {
	month_names: ["January","February","March","April","May","June","July","Augest","September","October","November","December"],
	month_names_es: ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],
	weekdays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],weekdays_es: ["Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa"],
	month_days: [31,28,31,30,31,30,31,31,30,31,30,31],
	//Get today's date - year, month, day and date
	today : new Date(),
	opt : {},
	data: [],

	//Functions
	/// Used to create HTML in a optimized way.
	wrt:function(txt) {
		this.data.push(txt);
	},
	
	/* Inspired by http://www.quirksmode.org/dom/getstyles.html */
	getStyle: function(ele, property){
		if (ele.currentStyle) {
			var alt_property_name = property.replace(/\-(\w)/g,function(m,c){return c.toUpperCase();});//background-color becomes backgroundColor
			var value = ele.currentStyle[property]||ele.currentStyle[alt_property_name];
		
		} else if (window.getComputedStyle) {
			property = property.replace(/([A-Z])/g,"-$1").toLowerCase();//backgroundColor becomes background-color

			var value = document.defaultView.getComputedStyle(ele,null).getPropertyValue(property);
		}
		
		//Some properties are special cases
		if(property == "opacity" && ele.filter) value = (parseFloat( ele.filter.match(/opacity\=([^)]*)/)[1] ) / 100);
		else if(property == "width" && isNaN(value)) value = ele.clientWidth || ele.offsetWidth;
		else if(property == "height" && isNaN(value)) value = ele.clientHeight || ele.offsetHeight;
		return value;
	},
	getPosition:function(ele) {
		var x = 0;
		var y = 0;
		while (ele) {
			x += ele.offsetLeft;
			y += ele.offsetTop;
			ele = ele.offsetParent;
		}
		if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") {
			x += document.body.leftMargin;
			offsetTop += document.body.topMargin;
		}
	
		var xy = new Array(x,y);
		return xy;
	},
	/// Called when the user clicks on a date in the calendar.
	selectDate:function(year,month,day) {
		var ths = _calendar_active_instance;
		document.getElementById(ths.opt["input"]).value = year + "-" + month + "-" + day; // Date format is :HARDCODE:
		ths.hideCalendar();
	},
	/// Creates a calendar with the date given in the argument as the selected date.
	makeCalendar:function(year, month, day) {
		year = parseInt(year);
		month= parseInt(month);
		day	 = parseInt(day);
		
		//Display the table
		var next_month = month+1;
		var next_month_year = year;
		if(next_month>=12) {
			next_month = 0;
			next_month_year++;
		}
		
		var previous_month = month-1;
		var previous_month_year = year;
		if(previous_month< 0) {
			previous_month = 11;
			previous_month_year--;
		}
		
		this.wrt("<table>");
		this.wrt("<tr><th><a href='javascript:calendar.makeCalendar("+(previous_month_year)+","+(previous_month)+");' title='"+this.month_names_es[previous_month]+" "+(previous_month_year)+"'><img src=\""+(ruta)+"cal_ant.gif\" alt=\"Mes anterior\" /></a></th>");
		this.wrt("<th colspan='5' class='calendar-title'><select name='calendar-month' class='calendar-month' onChange='calendar.makeCalendar("+year+",this.value);'>");
		for(var i in this.month_names_es) {
			this.wrt("<option value='"+i+"'");
			if(i == month) this.wrt(" selected='selected'");
			this.wrt(">"+this.month_names_es[i]+"</option>");
		}
		this.wrt("</select>");
		this.wrt("<select name='calendar-year' class='calendar-year' onChange='calendar.makeCalendar(this.value, "+month+");'>");
		var current_year = this.today.getYear();
		if(current_year < 1900) current_year += 1900;
		
		for(var i=current_year-30; i<current_year+30; i++) {
			this.wrt("<option value='"+i+"'");
			if(i == year) this.wrt(" selected='selected'");
			this.wrt(">"+i+"</option>");
		}
		this.wrt("</select></th>");
		this.wrt("<th><a href='javascript:calendar.makeCalendar("+(next_month_year)+","+(next_month)+");' title='"+this.month_names_es[next_month]+" "+(next_month_year)+"'><img src=\""+(ruta)+"cal_sig.gif\" alt=\"Mes siguiente\" /></a></th></tr>");
		this.wrt("<tr class='header'>");
		for(var weekday=0; weekday<7; weekday++) this.wrt("<td class=\"weekday\" >"+this.weekdays_es[weekday]+"</td>");
		this.wrt("</tr>");
		
		//Get the first day of this month
		var first_day = new Date(year,month,1);
		var start_day = first_day.getDay();
		
		var d = 1;
		var flag = 0;
		
		//Leap year support
		if(year % 4 == 0) this.month_days[1] = 29;
		else this.month_days[1] = 28;
		
		var days_in_this_month = this.month_days[month];

		//Create the calender
		for(var i=0;i<=5;i++) {
			if(w >= days_in_this_month) break;
			this.wrt("<tr>");
			for(var j=0;j<7;j++) {
				if(d > days_in_this_month) flag=0; //If the days has overshooted the number of days in this month, stop writing
				else if(j >= start_day && !flag) flag=1;//If the first day of this month has come, start the date writing

				if(flag) {
					var w = d, mon = month+1;
					if(w < 10)	w	= "0" + w;
					if(mon < 10)mon = "0" + mon;

					//Is it today?
					var class_name = '';
					var yea = this.today.getYear();
					if(yea < 1900) yea += 1900;

					if(yea == year && this.today.getMonth() == month && this.today.getDate() == d) class_name = " today";
					if(day == d) class_name += " selected";
					
					class_name += " " + this.weekdays_es[j].toLowerCase();

					this.wrt("<td class='days"+class_name+"'><a href='javascript:calendar.selectDate(\""+year+"\",\""+mon+"\",\""+w+"\")'>"+w+"</a></td>");
					d++;
				} else {
					this.wrt("<td class='days'>&nbsp;</td>");
				}
			}
			this.wrt("</tr>");
		}
		this.wrt("</table>");
		this.wrt("<input type='button' value='Cerrar' class='calendar-cancel' onclick='calendar.hideCalendar();' />");

		document.getElementById(this.opt['calendar']).innerHTML = this.data.join("");
		this.data = [];
	},
	
	/// Display the calendar - if a date exists in the input box, that will be selected in the calendar.
	showCalendar: function() {
		var input = document.getElementById(this.opt['input']);
		
		//Position the div in the correct location...
		var div = document.getElementById(this.opt['calendar']);
		var xy = this.getPosition(input);
		var width = parseInt(this.getStyle(input,'width'));
		div.style.left=(xy[0]+width+10)+"px";
		div.style.top=xy[1]+"px";

		// Show the calendar with the date in the input as the selected date
		var existing_date = new Date();
		var date_in_input = input.value;
		if(date_in_input) {
			var selected_date = false;
			var date_parts = date_in_input.split("-");
			if(date_parts.length == 3) {
				date_parts[1]--; //Month starts with 0
				selected_date = new Date(date_parts[0], date_parts[1], date_parts[2]);
			}
			if(selected_date && !isNaN(selected_date.getYear())) { //Valid date.
				existing_date = selected_date;
			}
		}
		
		var the_year = existing_date.getYear();
		if(the_year < 1900) the_year += 1900;
		this.makeCalendar(the_year, existing_date.getMonth(), existing_date.getDate());
		document.getElementById(this.opt['calendar']).style.display = "block";
		_calendar_active_instance = this;
	},
	
	/// Hides the currently show calendar.
	hideCalendar: function(instance) {
		var active_calendar_id = "";
		if(instance) active_calendar_id = instance.opt['calendar'];
		else active_calendar_id = _calendar_active_instance.opt['calendar'];
		
		if(active_calendar_id) document.getElementById(active_calendar_id).style.display = "none";
		_calendar_active_instance = {};
	},
	
	/// Setup a text input box to be a calendar box.
	set: function(input_id) {
		var input = document.getElementById(input_id);
		if(!input) return; //If the input field is not there, exit.
		
		if(!this.opt['calendar']) this.init();
		
		var ths = this;
		input.onclick=function(){
			ths.opt['input'] = this.id;
			ths.showCalendar();
		};
	},
	
	/// Will be called once when the first input is set.
	init: function() {
		if(!this.opt['calendar'] || !document.getElementById(this.opt['calendar'])) {
			var div = document.createElement('div');
			if(!this.opt['calendar']) this.opt['calendar'] = 'calender_div_'+ Math.round(Math.random() * 100);

			div.setAttribute('id',this.opt['calendar']);
			div.className="calendar-box";

			document.getElementsByTagName("body")[0].insertBefore(div,document.getElementsByTagName("body")[0].firstChild);
		}
	}
}
/* verifica los argumentos(el numero y el tipo) de una funci�n
 * 
 * Pre: tipos= Object, Array, Function, String, Number, Boolean o [new Test() >  objecto >] Test
 *      argumentos
 * Pos: return true si los argumentos(el numero y el tipo)son validos y si no genera una ecepcion; 
 */
function strict( tipos, argumentos ) {
	
	
	
	// Validar el numero de argumentos
	if ( tipos.length != argumentos.length ) {
		throw "Numero invalido de argumentos. Se esperaba " + tipos.length + ", y s�lo se recibieron " + argumentos.length;
	}
	// validar los tipos de argumentos
	for ( var i = 0; i < argumentos.length; i++ ) {
	//
		if ( argumentos[i].constructor != types[i] ) {
			throw "Tipo invalido, se esperaba " + tipos[i].name + " y se recibio " + argumentos[i].constructor.name;
		}
	}
}


/**Banner*/
// Opacity and Fade in script.
// Script copyright (C) 2008 http://www.cryer.co.uk/.
// Script is free to use provided this copyright header is included.
function SetOpacity(object,opacityPct)
{
  // IE.
  object.style.filter = 'alpha(opacity=' + opacityPct + ')';
  // Old mozilla and firefox
  object.style.MozOpacity = opacityPct/100;
  // Everything else.
  object.style.opacity = opacityPct/100;
}
function ChangeOpacity(id,msDuration,msStart,fromO,toO)
{
  var element=document.getElementById(id);
  var opacity = element.style.opacity * 100;
  var msNow = (new Date()).getTime();
  opacity = fromO + (toO - fromO) * (msNow - msStart) / msDuration;
  if (opacity<0) 
    SetOpacity(element,0)
  else if (opacity>100)
    SetOpacity(element,100)
  else
  {
    SetOpacity(element,opacity);
    element.timer = window.setTimeout("ChangeOpacity('" + id + "'," + msDuration + "," + msStart + "," + fromO + "," + toO + ")",1);
  }
}
function FadeIn(id)
{
  var element=document.getElementById(id);
  if (element.timer) window.clearTimeout(element.timer); 
  var startMS = (new Date()).getTime();
  element.timer = window.setTimeout("ChangeOpacity('" + id + "',1000," + startMS + ",0,100)",1);
}
function FadeOut(id)
{
  var element=document.getElementById(id);
  if (element.timer) window.clearTimeout(element.timer); 
  var startMS = (new Date()).getTime();
  element.timer = window.setTimeout("ChangeOpacity('" + id + "',1000," + startMS + ",100,0)",1);
}
function FadeInImage(foregroundID,newImage,backgroundID)
{
  var foreground=document.getElementById(foregroundID);
  if (backgroundID)
  {
    var background=document.getElementById(backgroundID);
    if (background)
    {
      background.style.backgroundImage = foreground.style.backgroundImage;
      background.style.backgroundRepeat = 'no-repeat';
    }
  }
  //alert(foreground.src + newImage);
  SetOpacity(foreground,0);
  foreground.style.backgroundImage = 'url(' + newImage + ')';
  if (foreground.timer) window.clearTimeout(foreground.timer); 
  var startMS = (new Date()).getTime();
  foreground.timer = window.setTimeout("ChangeOpacity('" + foregroundID + "',1000," + startMS + ",0,100)",10);
}


function iniciarBanner()
{
	if(imagenes.length!=0){
		var ctrlIzq=document.getElementById("ctrlImgIzq");
		var ctrlDer=document.getElementById("ctrlImgDer");
		ctrlIzq.onclick = imgAnt;
		ctrlDer.onclick = imgSig;
		auto();
	}
}
function imgAnt(){
	if(imagenes.length!=0){
		auto();
		var banner=document.getElementById("banner");
		var bannerHref=document.getElementById("anunImgHref");
		if (cont == 0){
			cont = imagenes.length;	
		}
		if (imgSigCont){
			imgSigCont=false;
			cont=cont-2;
			if(cont==0)
				cont = imagenes.length;
		}
		cont--;
		bannerHref.href= imagenes[cont];
		cont--;
		bannerHref.title = imagenes[cont];
		//banner.alt = imagenes[cont];
		cont--;
		
		FadeInImage('bannerFade',rutaBanner + imagenes[cont],'banner');
		//banner.style.backgroundImage =  "url(\""+ rutaBanner + imagenes[cont]+ "\")";
		imgAntCont=true;
		auto();
		
		return false;
	}
}
function imgSig(){
	if(imagenes.length!=0){
		auto();
		var banner=document.getElementById("banner");
		var bannerHref=document.getElementById("anunImgHref");
		
		if (imgAntCont){
			imgAntCont=false;
			cont=cont+2;
			if(cont==imagenes.length-1){
				cont=-1;
			}
		}
		else{
			if(cont==imagenes.length-1){
				cont=0;
			}
			if (cont==0 && !iniciado)
				cont=cont+2;
			else if (cont==0 && iniciado)
				cont--;
		}
		cont++;
		FadeInImage('bannerFade',rutaBanner + imagenes[cont],'banner');
		//banner.style.backgroundImage = "url(\"" + rutaBanner + imagenes[cont] + "\")";
		
		cont++;
		//banner.alt = imagenes[cont];
		bannerHref.title = imagenes[cont];
		cont++;
		bannerHref.href= imagenes[cont];
		imgSigCont=true;
		iniciado=true;
		auto();
		return false;
	}
}
function auto(){	
	if(imagenes.length!=0){
		if (lock == true) {
			lock = false;
			window.clearInterval(run);
		}
		else if (lock == false) {
			lock = true;
			run = setInterval("imgSig()", delay);
		}
	}
}
