var contaCurso=0;
var listaCursos = new Array();
var FinalPrice=0;
function casa(valor)
{
	//alert(valor);
	valor=parseInt (valor);
	if (valor > 0)
	{
		document.getElementById('msg_casa').style.display='block';
		FinalPrice=TotalPrice+90;
	}
	else
	{
		document.getElementById('msg_casa').style.display='none';
		FinalPrice=TotalPrice;
	}


	document.getElementById('preciototal').value=FinalPrice;
	
	
	document.getElementById('preciofinal').value=TotalPrice;

}
function delCurso(div)
{
	id=div.split('_');
	TotalPrice=TotalPrice-parseInt(document.getElementById('precio_'+id[1]).value);
	document.getElementById('preciofinal').value=TotalPrice;	
	elCurso=document.getElementById(div);
	elCurso.parentNode.removeChild(elCurso);

casa(document.getElementById('Accommodation')[document.getElementById('Accommodation').selectedIndex].value);

	for (x=0; x<listaCursos.length; x++)
	{
		if (listaCursos[x][0]==id[1])
		{
			listaCursos.splice(x,1);


			return;
		}
	}
	
}
var TotalPrice=0;
function addCourse()
{
	
	idCurso = document.getElementById('curso')[document.getElementById('curso').selectedIndex].value;
	nombreCurso = document.getElementById('curso')[document.getElementById('curso').selectedIndex].innerHTML;
	fechaCurso = document.getElementById('auto_datestart')[document.getElementById('auto_datestart').selectedIndex].innerHTML;
	valuefechaCurso = document.getElementById('auto_datestart')[document.getElementById('auto_datestart').selectedIndex].value;
	duraCurso = document.getElementById('duracion')[document.getElementById('duracion').selectedIndex].innerHTML;
	valueduraCurso = document.getElementById('duracion')[document.getElementById('duracion').selectedIndex].value;
	precio=parseInt(document.getElementById('precioreal').value);
	
	//alert(idCurso);
	
	if (valuefechaCurso=="no")
	{
		fecha="From "+fechaCurso+" for "+duraCurso;
	claveUnica=idCurso+' '+fechaCurso;
	}
	else
	{
		parFecha=fechaCurso.split(" - ");
		fecha= "From "+parFecha[0]+" to "+parFecha[1];
	claveUnica=idCurso+' '+parFecha[0];
	}

	nextcurso="<strong>"+nombreCurso+"</strong><br />&nbsp;&nbsp;&nbsp;Date:"+fecha+"<br />&nbsp;&nbsp;&nbsp;Price:"+precio;

	// esta ya en la lista?
	for (x=0; x<listaCursos.length; x++)
	{
		if (listaCursos[x][1]==claveUnica){ document.getElementById('errorDupli').style.display='block';return;}
		else document.getElementById('errorDupli').style.display='none';
	}
	
	TotalPrice=TotalPrice+precio;
	document.getElementById('preciofinal').value=TotalPrice;
	
	contaCurso=contaCurso+1;
	
	ArrayCurso = new Array(2);
	ArrayCurso[0]= contaCurso;
	ArrayCurso[1]= claveUnica;
	
	listaCursos[listaCursos.length]= ArrayCurso;
	
	elDiv=document.getElementById('selectedcourses');
	di=document.createElement("div");
	di.setAttribute("id","Dcurso_"+ArrayCurso[0]);
	//tx=document.createTextNode(ArrayCurso[1]);
	//di.appendChild(tx);
	//di.innerHTML=nextcurso;
	
	del=document.createElement("img");
	del.setAttribute("src","/img/del.png");
	del.setAttribute("border","0");
	//del.setAttribute("onclick","document.getElementById('selectedcourses').removeChild(this.parentNode)");
	//del.onclick=document.getElementById('selectedcourses').removeChild(this.parentNode);
	a=document.createElement("a");
	a.setAttribute("href","javascript:delCurso('Dcurso_"+ArrayCurso[0]+"');");
	a.setAttribute("style","float: right; display: block; text-decoration: none;");
	a.appendChild(del);
	di.appendChild(a);
	
	di.innerHTML=di.innerHTML+nextcurso;

	inp=document.createElement("input");
	inp.setAttribute("id","curso_"+ArrayCurso[0]);
	inp.setAttribute("name","curso[]");
	inp.setAttribute("type","hidden");
	inp.setAttribute("value",idCurso);
	di.appendChild(inp);
	inp=document.createElement("input");
	inp.setAttribute("id","nombreCurso_"+ArrayCurso[0]);
	inp.setAttribute("name","nombreCurso[]");
	inp.setAttribute("type","hidden");
	inp.setAttribute("value",nombreCurso);
	di.appendChild(inp);
	inp=document.createElement("input");
	inp.setAttribute("id","precio_"+ArrayCurso[0]);
	inp.setAttribute("name","precio[]");
	inp.setAttribute("type","hidden");
	inp.setAttribute("value",precio);
	di.appendChild(inp);
	inp=document.createElement("input");
	inp.setAttribute("id","datestart[]"+ArrayCurso[0]);
	inp.setAttribute("name","datestart[]");
	inp.setAttribute("type","hidden");
	inp.setAttribute("value",fechaCurso);
	di.appendChild(inp);
	inp=document.createElement("input");
	inp.setAttribute("id","duracion_"+ArrayCurso[0]);
	inp.setAttribute("name","duracion[]");
	inp.setAttribute("type","hidden");
	inp.setAttribute("value",valueduraCurso);
	di.appendChild(inp);
	inp=document.createElement("input");
	inp.setAttribute("id","duracionTXT_"+ArrayCurso[0]);
	inp.setAttribute("name","duracionTXT[]");
	inp.setAttribute("type","hidden");
	inp.setAttribute("value",duraCurso);
	di.appendChild(inp);
	elDiv.appendChild(di);
	casa(document.getElementById('Accommodation')[document.getElementById('Accommodation').selectedIndex].value);
}



var cursocerrado;
function autodatestart()
{
if (document.getElementById('auto_datestart').options.length > 0) 
{  } 
else {return;}
document.getElementById('datestart').value=document.getElementById('auto_datestart')[document.getElementById('auto_datestart').selectedIndex].innerHTML; 
end=document.getElementById('auto_datestart')[document.getElementById('auto_datestart').selectedIndex].value;
if (end!='no'){
 document.getElementById('dateend').value=end; 
 document.getElementById('duradiv').style.display='none';
 document.getElementById('duradiv2').style.display='none';
 cursocerrado=1;
}else{
document.getElementById('duradiv').style.display='block';
document.getElementById('duradiv2').style.display='block';
cursocerrado=0;
}
//calculaWeeks();
//actualizaAjax('auto_datestart','duracion');
}			

function actualizaAjax(desde,hasta){xloadXMLDoc(desde,hasta);}

function calculaWeeks()
{
	if (document.getElementById('duracionextra').options.length > 0) 
{  } 
else {return;}
	if (cursocerrado==1)
	{
		dias=days_between(document.getElementById('datestart').value,document.getElementById('dateend').value);
		sem= Math.round(dias/7);
		if ((dias%7) > 0) sem++;
		document.getElementById('nrosemanas').value=sem;
	}
	else
	{
		normal=MM_findObj('semanas_duracion').value;
		extra=MM_findObj('semanas_duracion_extra').value;
		cantidad=MM_findObj('semanas_cantidad').value;
		cantidadextra=document.getElementById('duracionextra')[document.getElementById('duracionextra').selectedIndex].value
		if (normal=='no' && extra=='no')
		{
			destino='0';
		}
		else if (normal=='no')
		{
			destino='0';
		}
		else if (extra=='no')
		{
			normal=parseInt(normal);
			cantidad= parseInt(cantidad);
			destino=normal*cantidad;
		}
		else
		{
			normal=parseInt(normal);
			cantidad= parseInt(cantidad);
			extra=parseInt(extra);
			cantidadextra= parseInt(cantidadextra);
			destino=(normal*cantidad)+(extra*cantidadextra);
		}
		document.getElementById('nrosemanas').value=destino;
		mirafecha();
	}	
}

function days_between(date1, date2) {
    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24
    fecha1 = date1.split('/');
    fecha2 = date2.split('/');
date1 = new Date(fecha1[2],fecha1[1],fecha1[0]) ;
date2 = new Date(fecha2[2],fecha2[1],fecha2[0]) ;

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)
}

function mirafecha()
{
caja=document.getElementById('datestart').value;
   if (caja)
   {  
      borrar = caja;
      if ((caja.substr(2,1) == "/") && (caja.substr(5,1) == "/"))
      {      
         for (i=0; i<10; i++)
	     {	
            if (((caja.substr(i,1)<"0") || (caja.substr(i,1)>"9")) && (i != 2) && (i != 5))
			{
               borrar = '';
               break;  
			}  
         }
	     if (borrar)
	     { 
	      a = caja.substr(6,4);
		    m = caja.substr(3,2);
		    d = caja.substr(0,2);
		    if((a < 1900) || (a > 2050) || (m < 1) || (m > 12) || (d < 1) || (d > 31))
		       borrar = '';
		    else
		    {
		     if((a%4 != 0) && (m == 2) && (d > 28))	   
		          borrar = ''; // Aņo no viciesto y es febrero y el dia es mayor a 28
			   else	
			   {
		          if ((((m == 4) || (m == 6) || (m == 9) || (m==11)) && (d>30)) || ((m==2) && (d>29)))
			         borrar = '';	      				  	 
			   }  // else
		    } // fin else
       } // if (error)
      } // if ((caja.substr(2,1) == "/") && (caja.substr(5,1) == "/"))			    			
	  else
	     borrar = '';

	  if (borrar == '')
	     {
//	     document.getElementById('datestart_txt').innerHTML='<acronym title="La fecha introducida parece no ser valida">dd/mm/yyyy<img src="http://72.52.153.205/~dracena/2/sites/all/themes/cursos/icons/info_small.gif" border="0" align="baaseline" height="14" width="14" alt="La fecha introducida parece no ser valida"></acronym>';
//	     document.getElementById('dateend_txt').innerHTML='';	     
	     }
	     else
	     {
//		     document.getElementById('dateend_txt').innerHTML='<acronym title="Verifique la fecha calculada automaticamente"> Fecha Inicio + Duracion <img src="http://72.52.153.205/~dracena/2/sites/all/themes/cursos/icons/reload.png" align="baaseline" border="0" height="14" width="14" alt="Verifique fecha calculada"></acronym>';
//		     document.getElementById('datestart_txt').innerHTML='';
		     if (cursocerrado==1)
		     {
		     
		     }
		     else
		     {
			     s=document.getElementById('datestart').value;
			     s_tmp=s.split("/");
			     
			     ini=new Date(
			     parseInt(s_tmp[2]),
			     parseInt((s_tmp[1].substr(0,1)=="0"?s_tmp[1].substr(1,1):s_tmp[1].substr(0,2)))-1,
			     parseInt((s_tmp[0].substr(0,1)=="0"?s_tmp[0].substr(1,1):s_tmp[0].substr(0,2)))
			     );
			     diacomienzo=ini.getDay();
						diames=ini.getDate();
			     ini.setDate(ini.getDate()+dias);

			     if (ini.getDay()==diacomienzo) ini.setDate(ini.getDate()-1);
			     if (ini.getDay()==1){
			     	ini.setDate(ini.getDate()-3);
			     }
			     else if (ini.getDay()==0)
			     {
			     	ini.setDate(ini.getDate()-2);
			     }
					 else if (ini.getDay()==6)
					 {
					 	ini.setDate(ini.getDate()-1);
					 }
			
			     mes = new String (ini.getMonth()+1);
			     dia = new String (ini.getDate());
			     cero=otrocero='';
			     if (mes.length == 1) cero='0';
			     if (dia.length == 1) otrocero='0';
			     fin = otrocero+dia+'/'+cero+mes+'/'+ini.getFullYear();
			     document.getElementById('dateend').value=fin;
		     }
	     }
   } // if (caja)   
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
var preciobase;

function pReqChange() {
    if (req.readyState == 4) {
        if (req.status == 200) {
			if (req.responseText.indexOf('invalid') == -1) {
				var xmld = req.responseXML;
				var xmld2= xmld.getElementsByTagName('opciones');

if (campo=='duracion')
{
/*
	matricula=parseInt(xmld2[0].getAttribute("matricula"));
	if (matricula <1) matricula='0';
	document.getElementById('matricula').value=matricula;
	*/
	
	document.getElementById('semanas_duracion').value=parseInt(xmld2[0].getAttribute("semanas_duracion"));
	document.getElementById('semanas_duracion').value=Math.round(document.getElementById('semanas_duracion').value/7);
autodatestart();
calculaWeeks();
}


//if (campo=='duracionextra' || campo=='duracion')
if (campo=='precioextra')
{
	document.getElementById('duracionextra_txt').innerHTML=xmld2[0].getAttribute("duracion_hand_txt");
	preciobase= xmld2[0].getAttribute("precio");
	preciobase=parseInt(preciobase);
	//alert (preciobase);
	if (preciobase>0 && preciobase!='0')
	{
	document.getElementById('precioreal').value=preciobase;
	document.getElementById('precioreal_txt').innerHTML='';
	}
	else document.getElementById('precioreal_txt').innerHTML='<br />Registration needed for quotation';
	
	document.getElementById('semanas_duracion_extra').value=parseInt(xmld2[0].getAttribute("semanas_duracion_extra"));
	document.getElementById('semanas_duracion_extra').value=Math.round(document.getElementById('semanas_duracion_extra').value/7);
	
	document.getElementById('semanas_cantidad').value=xmld2[0].getAttribute("semanas_cantidad");
/*
calculaWeeks();
}

if (campo=='precioextra')
{
	*/
	precioextra=parseInt(xmld2[0].getAttribute("precioextra"));
	if (precioextra > 0 && precioextra!='0')
	{
	 document.getElementById('precioreal').value=preciobase+precioextra;
	}

calculaWeeks();
}

				if(campo!='precioextra')
				{
				var cim = MM_findObj(campo);
				var prm =  MM_findObj(clave);
				var v1,v2=0;var i = 0;
				var j = cim.options.length;
				for (i=0;i<j;i++){cim.options[cim.options.length -1]= null;}
				for (j=0;j<xmld2[0].childNodes.length;j++) 
				  {
				  v1 = Base64.decode(xmld2[0].childNodes[j].firstChild.nodeValue);
				   v2 = xmld2[0].childNodes[j].getAttribute("idval");
				   cim.options[j] = new Option(v1,v2);
				   }
				   		   	cim.disabled=false;
		   	}
	 			document.getElementById(clave+"_img").src = document.getElementById("spacer_img").src; 
				if (siguiente!='none'){xloadXMLDoc(campo,siguiente);}
		  } else {
            alert("There was a problem retrieving the XML data:" + req.statusText);
        } 
     }
 	}
}

var req;
var siguiente,url,clave,campo,valueClave=null;

function xloadXMLDoc(arg1,arg2) {
	clave=arg1;
	campo=arg2;
	valueClave = '&valor='+escape(MM_findObj(clave).value);
	switch(campo)
	{
	case 'curso':
		siguiente='auto_datestart';
	break;
	case 'auto_datestart':
		siguiente='duracion';
	break;
	case 'duracion':
		siguiente='precioextra';
		valueClave = '&valor[]='+escape(MM_findObj('curso').value)+'&valor[]='+escape(document.getElementById('auto_datestart')[document.getElementById('auto_datestart').selectedIndex].innerHTML);

	break;
	case 'precioextra':
	//		valueClave = '&valor[]='+escape(MM_findObj(clave).value)+'&valor[]='+escape(MM_findObj('duracion').value);
		casa(document.getElementById('Accommodation')[document.getElementById('Accommodation').selectedIndex].value);
		siguiente='none';
	break;
	default:
		siguiente='none';
		casa(document.getElementById('Accommodation')[document.getElementById('Accommodation').selectedIndex].value);
	}

	aleatorio=Math.round(Math.random()*1000);
	url = "/getValue.php?rnd="+aleatorio+"&type=" + escape(clave)+valueClave;
	if (campo!='precioextra')
	{
	 MM_findObj(campo).disabled=true;
	 }
	MM_findObj(clave + '_img').src = MM_findObj('cargando_img').src;
	
    if (window.XMLHttpRequest) {//XMLHttpRequest
        req = new XMLHttpRequest();
        req.onreadystatechange = pReqChange;
        req.open("GET", url, true);
        req.send(null);
    } else if (window.ActiveXObject) {//IE/Windows
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = pReqChange;
            req.open("GET", url, true);
            req.send();
        	}
		}
}














var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}




