/*  Yerbabuena Software SCA, 2008  |  www.yerbabuena.es
 * ----------------------------------------------------
 *
 * The DHTML Calendar, version 1.0
 *
 * This script is developed by YSENGINEERS
 *
 * This script is distributed under the GNU Lesser General Public License.
 * Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
 */

// $Id: week_macrojs.js 3807 2008-09-05 12:28:05Z davidmacias $

/** The Calendar object constructor. */
var div_stack = new Array();
var viewPopup;
var day_year;
var day_month;
var day_day;
var day_after = '';
var hour_start = '00.0';
var hour_end;
var own_member;
var auth_member;
var httpRequest;
var redirect_url;
var invitation_url;
var absoluteUrl;
var calendarUrl;
var title;
var div_top;
var div_left;
var options_id;
var can_move;
var move_event;
var id_cell;
var id_event_edit;     
var duration_event_edit;
var event_object;
//Si el navegador del cliente es Mozilla la variable siguiente valdrá true
//var moz = document.getElementById && !document.all;
var estoyArrastrando = false;
var wscrollLeft = 0;
var wscrollTop = 0;
var var_ajust_event = 5;
var dobj;
var nav = navigator.appName;
var week_days = new Array();
var day_end;
var month_end;
var year_end;
var permission=false;

/*if (nav == 'Microsoft Internet Explorer'){
	var_ajust_event = 100;
}else if(nav == 'Opera'){
	var_ajust_event = 5;
}*/
      
pulsed = new Boolean();
pulsed = false;
pulsed_day = new Boolean();
pulsed_day = false;

function crearXMLHttpRequest(){
    var xmlHttp=null;
    if (window.ActiveXObject) 
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    else 
      if (window.XMLHttpRequest) 
        xmlHttp = new XMLHttpRequest();
    return xmlHttp;
}
   
function retardo(n){
    for (i=0;i<=n;i++){
        window.setTimeout('return 0', 1);
    }   
}
   
function reservaCita(ru, cu){
     var httpRequest2;
 
     httpRequest2 = crearXMLHttpRequest();
     httpRequest2.open('GET', ru, true);
     httpRequest2.send(null);
     httpRequest2.onreadystatechange = function (){
                                        if(httpRequest.readyState == 4){
                                          invitacion_url(calendar_url=cu)
                                        }
                                      };
}
   
function invitacion_url(calendar_url){
     var httpRequest2;
     
     httpRequest2 = crearXMLHttpRequest();
     invitation_script = absoluteUrl + '/invitation_url?calendar_url=' + calendar_url + '&auth_member=' + auth_member + '&own_member=' + own_member + '&day=' + day_day + '&month=' + day_month + '&year=' + day_year + '&hour_start=' + hour_start
     httpRequest2.open('GET', invitation_script, true);
     httpRequest2.send(null);
     httpRequest2.onreadystatechange = function (){
                                    if(httpRequest2.readyState == 4){
                                      invitation_url = httpRequest2.responseText.toString();
                                      if (invitation_url != ''){
                                            invitacion(invitation_url,calendar_url);
                                          }else{
                                            window.location=calendar_url
                                          }
                                        }
                                      };
     
}
   
function invitacion(invitation_url,calendar_url){
     var httpRequest2;
     
     httpRequest2 = crearXMLHttpRequest();
     httpRequest2.open('GET', invitation_url, true);
     httpRequest2.send(null);
     httpRequest2.onreadystatechange = function (){
                                        if(httpRequest2.readyState == 4){
                                            window.location=calendar_url
                                        }
                                      };
     
}

function pulsa_sombrea_days(id, dayYear, dayMonth, dayDay){
				
		pulsed = true;
		day_year = dayYear;
	    day_month = dayMonth;
	    day_day = dayDay;
	    //Borra el sombreado y cierra la ventana de creacion de evento si ya estaba abierta antes
	    cancelar_cita();
	    viewPopup = true;  
	    document.getElementById(id).style.backgroundColor='#EAEAEA';	     
}
   
function pulsa_sombrea(id, hourStart, dayYear, dayMonth, dayDay){
     
     pulsed = true;
     day_year = dayYear;
     day_month = dayMonth;
     day_day = dayDay;
     hour_start = hourStart;
     //Borra el sombreado y cierra la ventana de creacion de evento si ya estaba abierta antes
     cancelar_cita();
     div_stack.push(id);
     document.getElementById(id).style.backgroundColor='#EAEAEA';
     viewPopup = true;
}

function pasa_sombrea_days(id, day){

	
	if (pulsed){
		div_start = 'div00.0' + day_day;
		div_end = 'div00.0' + day;
		
		for (var i = 0; i < week_days.length; i++){
			document.getElementById('div00.0'+week_days[i]).style.backgroundColor = '#ffffff';
			if (day_day == week_days[i].toString()){
				reverse = true;
			}
			if (day == week_days[i].toString()){
				reverse = false;
			}
		}
						
		if (!reverse){
			sw = 0
			for (var i = 0; i < week_days.length; i++){
				if (week_days[i].toString() == day_day){
					sw = 1;
					document.getElementById(div_start).style.backgroundColor = '#eaeaea';
				}
				if (week_days[i].toString() == day){
					sw = 2;
					document.getElementById(div_end).style.backgroundColor = '#eaeaea';
				}
				if (week_days[i].toString() != day && sw == 1){
					document.getElementById('div00.0'+week_days[i]).style.backgroundColor = '#eaeaea';
				}
			}
		}else{
			sw = 0
			for (var i = week_days.length - 1; i >= 0; i--){
				if (week_days[i].toString() == day_day){
					sw = 1;
					document.getElementById(div_start).style.backgroundColor = '#eaeaea';
				}
				if (week_days[i].toString() == day){
					sw = 2;
					document.getElementById(div_end).style.backgroundColor = '#eaeaea';
				}
				if (week_days[i].toString() != day && sw == 1){
					document.getElementById('div00.0'+week_days[i]).style.backgroundColor = '#eaeaea';
				}
			}
		}
		
		
	}
}
function pasa_sombrea(id, dayYear, dayMonth){
     
     document.getElementById('div_coord').style.visibility = 'hidden';
     document.getElementById('div_coord').innerHTML = id;
      
     if (dayYear)	day_year = dayYear;
     if (dayMonth)	day_month = dayMonth;
     
     id_cell = id;
     if (nav == 'Netscape'){
     	id_split = id.split('.');
     	now = id_split[0] + '.' + id_split[1].charAt(0) + day_day;
     }else{
     	if (id_cell){
     		id_split = id.split('.');
     		now = id_split[0] + '.' + id_split[1].charAt(0) + day_day;
     	}else{
     		id_split = '';
     		now = '';
     	}
     }
     
     if (move_event){    
		soltarBoton();
        move_event = false;
        if (id_cell != 'undefined'){
            document.location.href = document.location + '/moveEvent?id=' + id_event_edit + '&div=' + id_cell + '&year=' + 			day_year + '&month=' + day_month;
        }
    }         

    if (pulsed){
        div_start = 'div' + hour_start + day_day;
        div_end = now;
        hour_now = now.replace("div","");
        hour_now = hour_now.split('.');
        hour_now = hour_now[0] + '.' + hour_now[1].charAt(0);

        float_start = parseFloat(hour_start)
        float_now = parseFloat(hour_now)

        for (i = 8.0; i<20.0; i+=0.5){
            id_div = 'div' + i + day_day;
            if (i % 1 == 0) {
               id_div = 'div' + i + '.0' + day_day;
            } else {
               id_div = 'div' + i + day_day;    
            }
            document.getElementById(id_div).style.backgroundColor='#FFFFFF';
            div_stack.pop();
        }

        //Sombrea las celdas cuando muevo el raton desde la hora que he hecho clic hacia arriba
        if (float_start < float_now){
            for (i = float_start;i <= float_now; i+=0.5){
                if (i % 1 == 0) {
                   id_div = 'div' + i + '.0' + day_day;
                } else {
                   id_div = 'div' + i + day_day;    
                }
                document.getElementById(id_div).style.backgroundColor='#EAEAEA';
                div_stack.push(now);
            }
        }

        //Sombrea las celdas cuando muevo el raton desde la hora que he hecho clic hacia abajo
        if (float_start > float_now){
            for (i = float_start - 0.5;i >= float_now; i-=0.5){
                if (i % 1 == 0) {
                   id_div = 'div' + i + '.0' + day_day;
                } else {
                   id_div = 'div' + i + day_day;    
                }
                document.getElementById(id_div).style.backgroundColor='#EAEAEA';
                div_stack.push(now);
            }
        }

        if (float_start == float_now){
            id_div = 'div' + float_start + day_day;
            if (float_start % 1 == 0) {
               id_div = 'div' + float_start + '.0' + day_day;
            }
            document.getElementById(id_div).style.backgroundColor='#EAEAEA';
            div_stack.push(now);
        }
    }    
}

function formatDate(year, mes, dia){
                                    
    //Devuelve la fecha en formato, Ej: Lunes 1 de Enero

    int_mes = mes.valueOf() - 1;
    mydate = new Date(year,int_mes,dia);
    dia_semana = mydate.getDay();
    
    if (dia_semana == '0'){
        dia_semana = 'Domingo';
    }else if(dia_semana == '1'){
        dia_semana = 'Lunes';
    }else if(dia_semana == '2'){
        dia_semana = 'Martes';
    }else if(dia_semana == '3'){
        dia_semana = 'Mi&eacute;rcoles';
    }else if(dia_semana == '4'){
        dia_semana = 'Jueves';
    }else if(dia_semana == '5'){
        dia_semana = 'Viernes';
    }else if(dia_semana == '6'){
        dia_semana = 'S&aacute;bado';
    }                

    if (mes == '1'){
        mes = 'Enero';
    }else if(mes == '2'){
        mes = 'Febrero';
    }else if(mes == '3'){
        mes = 'Marzo';
    }else if(mes == '4'){
        mes = 'Abril';
    }else if(mes == '5'){
        mes = 'Mayo';
    }else if(mes == '6'){
        mes = 'Junio';
    }else if(mes == '7'){
        mes = 'Julio';
    }else if(mes == '8'){
        mes = 'Agosto';
    }else if(mes == '9'){
        mes = 'Septiembre';
    }else if(mes == '10'){
        mes = 'Octubre';
    }else if(mes == '11'){
        mes = 'Noviembre';
    }else if(mes == '12'){
        mes = 'Diciembre';
    }
    
    return dia_semana + ' ' + dia + ' de ' + mes;
}

function up_mouse_days(ownMember, authMember, absolute_url, calendar_url, divWidth, divHeight, divTop, divLeft, day, month, year){
	pulsed = false;
	if (viewPopup){		
		day_after = '';
		hour_start = '0.0';
		hour_end = '0.0'
		day_end = day;
		month_end = month;
		year_end = year;
		div_top = divTop.toString() + 'px';
		div_left = divLeft;
		
		if (permission){
			if (parseFloat(divLeft.replace(/%/g,'')) > 70){
	         	div_left = parseFloat(div_left.replace(/%/g,'')) - 50;
	         	div_left = div_left.valueOf() + '%';
	         	document.getElementById('event_title_div').style.top=div_top;
	         	document.getElementById('event_title_div').style.left=div_left;
	         	document.getElementById('create_event_corner1').style.display = "none";
	         	document.getElementById('create_event_corner2').style.display = "inline";
	         }else{
	         	document.getElementById('event_title_div').style.top=div_top;
	         	document.getElementById('event_title_div').style.left=div_left;
	         	document.getElementById('create_event_corner2').style.display = "none";
	         	document.getElementById('create_event_corner1').style.display = "inline";
	         }
	         document.getElementById('event_title_div').style.display = "inline";
	         document.form_event_create.event_title.focus();
	         
	         if (options_id){
	             document.getElementById(options_id).style.display = 'none';
	             document.getElementById('types_' + options_id).style.display = 'none';
	         }
	         
	         own_member = ownMember;
	         auth_member = authMember;
	         absoluteUrl = absolute_url;
	         calendarUrl = calendar_url;
	         document.getElementById('date').innerHTML = formatDate(day_year, day_month, day_day);
	    }
	         viewPopup = false;	    
	}
}

function up_mouse(hourEnd, ownMember, authMember, absolute_url, calendar_url, divWidth, divHeight, divTop, divLeft){
     
     // This if isn't Netscape navigator, view up_changeEvent function.
     if (can_move){
	move_event = true;
	can_move = false;
	pasa_sombrea(id_cell);
     }

     if (viewPopup) {
     	 
	         day_after = day_day;
	         pulsed=false;
	         day_end = '';
			 month_end = '';
			 year_end = '';
			 
	    if (permission){
	         if (parseFloat(hourEnd) <= parseFloat(hour_start)){
	             hour_end = hour_start;
	             hour_start = (parseFloat(hourEnd) - 0.5).toFixed(1).toString();
	         }else{
	             hour_end = hourEnd;
	         }
	         div_top = (divTop-90).toString()+'px';
	         div_left = divLeft;
	         
	         //if (div_top == '-30px'){}
	         
	         if (parseFloat(divLeft.replace(/%/g,'')) > 70){
	         	div_left = parseFloat(div_left.replace(/%/g,'')) - 50;
	         	div_left = div_left.valueOf() + '%';
	         	document.getElementById('event_title_div').style.top=div_top;
	         	document.getElementById('event_title_div').style.left=div_left;
	         	document.getElementById('create_event_corner1').style.display = "none";
	         	document.getElementById('create_event_corner2').style.display = "inline";
	         }else{
	         	document.getElementById('event_title_div').style.top=div_top;
	         	document.getElementById('event_title_div').style.left=div_left;
	         	document.getElementById('create_event_corner2').style.display = "none";
	         	document.getElementById('create_event_corner1').style.display = "inline";
	         }
	         document.getElementById('event_title_div').style.display = "inline";
	         document.form_event_create.event_title.focus();
	         
	         if (options_id){
	             document.getElementById(options_id).style.display = 'none';
	             document.getElementById('types_' + options_id).style.display = 'none';
	         }
	         
	         own_member = ownMember;
	         auth_member = authMember;
	         absoluteUrl = absolute_url;
	         calendarUrl = calendar_url;
	         document.getElementById('date').innerHTML = formatDate(day_year, day_month, day_day);
	     }
         viewPopup = false;
     }
}
   
function trim(cadena){
    //Quita espacios en blanco al principio y al final de la cadena
   
    
    for(i=0; i<cadena.length; ){
        if(cadena.charAt(i)==" "){
            cadena=cadena.substring(i+1, cadena.length);
        }else{
            break;
        }
    }

    for(i=cadena.length-1; i>=0; i=cadena.length-1){
                                                    
        if(cadena.charAt(i)==" ")
                    cadena=cadena.substring(0,i);
        else
            break;
    }
            
    return cadena
}    

function confirmar_cita(){
      
    title = document.getElementById('event_title').value;
    httpRequest = crearXMLHttpRequest();
    elements = document.getElementById('form_event_create').elements;
    var categories = new Array();
    for (var i = 0; i < elements.length; i++){
    	if (elements[i].checked){
    		categories.push(elements[i].value);
    	}
    }
 
    pagina = calendarUrl + '/eventMethod?title=' + title + '&hour_start=' + hour_start + '&hour_end=' + hour_end + '&day_year='+ day_year + '&day_month=' + day_month + '&day_day=' + day_day + '&calendar_url=' + calendarUrl + '&categories=' + categories + '&year_end=' + year_end + '&month_end=' + month_end + '&day_end=' + day_end;

    if (trim(title) != ''){
        document.location.href=pagina;
    }
}
   
function cancelar_cita(){  

    var div_id = 'div' + hour_start + day_day;
    var hstart = 8.0
    var hend = 20.0
    
    document.getElementById('event_categories_div').style.display = "none";
    document.getElementById('event_title_div').style.display = "none";
  
	for (i=0;i<week_days.length;i++){
  		div_id = 'div00.0'+week_days[i].toString();
  		document.getElementById(div_id).style.backgroundColor='#fff';
  	}
  	
    for (i=hstart;i<=hend;i+=0.5){
        document.getElementById(div_id).style.backgroundColor='#fff';
        div_id = 'div' + i.toFixed(1).toString() + day_day;
    }
   
    if (day_after != ''){
        var div_id = 'div' + hour_start + day_after;
        for (i=hstart;i<=hend;i+=0.5){
            document.getElementById(div_id).style.backgroundColor='#fff';
            div_id = 'div' + i.toFixed(1).toString() + day_after;
        }
     }

}

function mostrar_categorias_opciones(id){

	div = document.getElementById(id);
	visible = div.style.display;
	
	if (visible == 'none'){
		div.style.display = 'inline';
	}else{
		div.style.display = 'none';
	}

}

function close_options(id){

	document.getElementById(id).style.display = 'none';
	id_categories = 'types_' + id;
	document.getElementById(id_categories).style.display = 'none';

}

function mostrar_categorias_popup(){

	div = document.getElementById('event_categories_div');
	visible = div.style.display;
	
	if (visible == 'inline'){
		div.style.display = 'none';
	}else{
		div.style.display = 'inline';
	}

}// End mostrar_categorias_popup

function abrir_opciones(id, style_event, duration){
    
    if (!move_event){
	if (!can_move){
        	document.getElementById('event_title_div').style.display = 'none';
        	document.getElementById('event_categories_div').style.display = 'none';
        	
        	if (options_id){
            	 document.getElementById(options_id).style.display = 'none';
            	 document.getElementById('types_' + options_id).style.display = 'none';
         	}
         	
        	options_id = id;
        	if (permission){
	        	document.getElementById(options_id).style.display = 'inline';
	          
	        	top_event = style_event.top.replace('px','');
	
	        	if ((duration == '1:00:00') || (duration == '0:30:00')){
	        	    top_event = parseInt(top_event) - 67;
	        	}else if(duration.toString().indexOf('days') != -1){
	        		top_event = parseInt(top_event) - 87;
	        	}else{
	        	    top_event = parseInt(top_event) - 45;
	        	}
	
	        	top_event = top_event.valueOf() + 'px';
	        	width_event = style_event.width.replace('%','');
	        	left_event = style_event.left.replace('%','');
	        	left_event = parseInt(left_event) + parseInt(width_event);
	        	left_event = left_event.valueOf() + '%'
	        
	        	document.getElementById(options_id).style.top = top_event;
	        	document.getElementById(options_id).style.left = left_event;
	        }

		if (day_after != ''){
        	var div_id = 'div' + hour_start + day_after;
			var hstart = 8.0
			var hend = 20.0
        	for (i=hstart;i<=hend;i+=0.5){
        	    document.getElementById(div_id).style.backgroundColor='#fff';
        	    div_id = 'div' + i.toFixed(1).toString() + day_after;
        	}
     	}	
	}
    }
       
}
     
function up_changeEvent(id, duration){
	
	if (permission){
	    if (nav == 'Netscape'){
			event = ev_mouse;
			fobj = event.target;
			move_event = true;
	    	id_event_edit = id;
	    	duration_event_edit = duration;
	    }else{
			fobj = event.srcElement;
			can_move = true;
			id_event_edit = id;
	    	duration_event_edit = duration;
	    }
	
	    while (fobj.tagName.toLowerCase() != "html" && fobj.id != "event_div") {
	
		if (nav == 'Netscape'){
			fobj = fobj.parentNode;
		}else{
			fobj = fobj.parentElement;
		}
	    }
	
	    if (fobj.id == "event_div") {
		
	    	estoyArrastrando = true;
	    	dobj = fobj;
	    	return false;
	    }
	}
        
}

function scrollWindow(){

   scrollFrameLeft = document.getElementById('window_scroll_div').scrollLeft;
   scrollFrameTop = document.getElementById('window_scroll_div').scrollTop;
   wscrollLeft = document.documentElement.scrollLeft + scrollFrameLeft;
   wscrollTop = document.documentElement.scrollTop + scrollFrameTop;

}
var ev_mouse;

function arrastrarRaton(ev){

  ev_mouse = ev;

  if (estoyArrastrando) {
  
    if (nav == 'Netscape'){
		newLeft = ev_mouse.clientX + wscrollLeft - parseInt(document.getElementById('container_body').offsetLeft);
    	newTop = ev_mouse.clientY + wscrollTop + var_ajust_event - parseInt(document.getElementById('container_body').offsetTop);
		// Hace que al mover la capa se ponga en primer plano
   		dobj.style.zIndex = '600';
    	// Asigno el Left y el Top del div del evento "En Firefox tiene que ser con 
		// mayuscula (Left, Top) y en Explorer minuscula"
    	dobj.style.Left = newLeft.valueOf() + 'px';
    	dobj.style.Top = newTop.valueOf() + 'px';
    }else{
		// document.getElementById('raton').innerHTML = event.clientX;
		newLeft = event.clientX + wscrollLeft;
		newTop = event.clientY + wscrollTop + var_ajust_event;
		// Hace que al mover la capa se ponga en primer plano
	   	dobj.style.zIndex = '600';
    	// Asigno el Left y el Top del div del evento
    	dobj.style.left = newLeft - parseInt(document.getElementById('container_body').offsetLeft) - parseInt(document.getElementById('window_scroll_div').offsetLeft);
    	dobj.style.top = newTop - parseInt(document.getElementById('window_scroll_div').offsetTop);
    }         

    return false;
  }
  
}
window.onscroll = scrollWindow;
document.getElementById('window_scroll_div').onscroll = scrollWindow;
document.getElementById('window_scroll_div').onmousemove = arrastrarRaton;
   
function soltarBoton() {	
  estoyArrastrando = false;
}

function impedir_copiar(){
       
	//TODO       
}
