var ms_cal;
var magicdiv;

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();

function validate_c() {
	var formulario = document.getElementById('frm_contacto');
	if(formulario.nombre.value.length < 2) {
		alert('El campo nombre no puede quedar vacio');
		formulario.nombre.focus();
		return false;
	}
	if(formulario.apellido.value.length < 2) {
		alert('El campo apellido no puede quedar vacio');
		formulario.nombre.focus();
		return false;
	}
	if(formulario.email.value.length < 10) {
		alert('El campo e-mail no puede quedar vacio');
		formulario.email.focus();
		return false;
	}
	if(formulario.comentario.value.length < 10) {
		alert('El campo comentarios y otras consultas no puede quedar vacio');
		formulario.comentario.focus();
		return false;
	}
	formulario.submit();
}

function validate_b() {
	var formulario = document.getElementById('frm_consulta');
	if(formulario.nombre.value.length < 3) {
		alert('El campo Nombre no puede quedar vacio');
		formulario.nombre.focus();
		return false;
	}
	if(formulario.email.value.length < 3) {
		alert('El campo E-mail no puede quedar vacio');
		formulario.email.focus();
		return false;
	}
	if(formulario.fecha_desde.value.length < 3) {
		alert('El campo Fecha aproximada de salida no puede quedar vacio');
		formulario.fecha_desde.focus();
		return false;
	}
	if(formulario.fecha_hasta.value.length < 3) {
		alert('El campo Fecha aproximada de regreso no puede quedar vacio');
		formulario.fecha_hasta.focus();
		return false;
	}
	formulario.submit();
}

function sndReqSitio(action,id) {
	http.open('post', 'files/rpc.php?action='+action+'&cod='+ encodeURI(id));
	http.onreadystatechange = handleResponse;
	http.send(null);
}

function get_weather() {
	magicdiv = 'weather1_result';
	var seleccionado = document.getElementById('weather_cities').options[document.getElementById('weather_cities').selectedIndex].value;
	if(seleccionado.length == 8) {
		sndReqSitio('weather',seleccionado);
		magicdiv = 'weather';
		document.getElementById(magicdiv).style.display = 'block';
		document.getElementById(magicdiv).innerHTML = '<img src=\"img/loading.gif\" width=\"16\" height=\"22\" align=\"absmiddle\"> Obteniendo reporte. Aguarde unos segundos...';	
	} else {
		return false;
		alert('pinga');
	}
}

function handleResponse() {
	if(http.readyState == 4){
        var response = http.responseText;
		if(document.getElementById('cant_pass')) {
			var cantidad = document.getElementById('cant_pass');
		}
        var update = new Array();
        if(response.indexOf('|' != -1)) {
            update = response.split('|');
			if(cantidad == null) {
				document.getElementById(update[0]).innerHTML = update[1];
				if(update[0] == 'weather') {
					doThePNGcrapAgain();
				}
			} else {
				var pasajeros = document.getElementById('pasajeros');
				var new_psg = document.createElement('div');
				new_psg.innerHTML = update[1];
				cantidad.value = parseInt(cantidad.value) + 1;
				pasajeros.appendChild(new_psg);				
			}
        }
    }
}

function pipa() {
	for(i = 0; i < ms_cal.selectedDates.length; i++) {
		alert(ms_cal.selectedDates[i]);
	}
}

function validar() {
	var formulario = document.getElementById('reservas');
	formulario.submit();
}

function validar_cars() {
	var formulario = document.getElementById('cars');
	formulario.submit();
}

function validar_hotel() {
	var formulario = document.getElementById('hotel');
	formulario.submit();
}


function agregarEvento() {
	var mySelect = document.getElementById('select_eventos');
	var myHour = document.getElementById('event_hour').options[document.getElementById('event_hour').selectedIndex].value;
	var myMinute = document.getElementById('event_minute').options[document.getElementById('event_minute').selectedIndex].value;
	var myPlace = document.getElementById('ubicaciones_items').options[document.getElementById('ubicaciones_items').selectedIndex].value;
	var currentPlace = document.getElementById('current_locations');
	var myDates = new String();
	var myDates_desc = new String();
	var selectedDates = new Array();
	if(ms_cal.selectedDates.length < 1) {
		alert('Debe selecccionar al menos una fecha en el calendario.');
		return false;
	} else {
		for(i= 0; i < ms_cal.selectedDates.length; i++) {
			if(i > 0) {
				myDates += '@';
				myDates_desc += ', ';
			}
			myDates += ms_cal.selectedDates[i].dateFormat("Y-m-d");
			myDates_desc += ms_cal.selectedDates[i].dateFormat("F, d Y");
		}
	}
	myDates += "#" + myHour + ':' + myMinute;
	myDates_desc += " a las " + myHour + ':' + myMinute;
	myDates += "#" + myPlace;
	myDates_desc += " en " + document.getElementById('ubicaciones_items').options[document.getElementById('ubicaciones_items').selectedIndex].text;
	alert(myDates_desc);
	agregarElemento(myDates_desc, myDates, 'select_eventos', 'current_locations');
}

function checklogin() {
	var loginfrm = document.getElementById('loginbox');
	
	var frmuser = document.getElementById('frmuser');
	var frmpass = document.getElementById('frmpass');
	
	if((frmuser.value.length > 5) && (frmpass.value.length > 5)) {
		loginfrm.submit();
	} else {
		alert("Los campos de usuario y contraseña no pueden estar vacios.");
		frmuser.focus();
		return false;
	}
}


function agregarPasajero() {
	var num = document.getElementById('cant_pass');
	var contenedor = document.getElementById('pasajeros');

	// creamos los elementos
	var tabla = document.createElement('table');
	for(i=1 ; i < 9 ; i++) {
		var tr = document.createElement('tr');
		if(i == 1) {
			var td = document.createElement('td');
			var texto = document.createTextNode('Pasajero ' + num.value);
			td.setAttribute('colspan','2');
			td.appendChild(texto);
			tr.appendChild(td);
		} else if(i == 2) {
			var td = document.createElement('td');
			var td2 = document.createElement('td');
			var pregunta = document.createTextNode(String.fromCharCode(0x00bf)+'Es beb'+String.fromCharCode(0x00e9)+'? (0-2)');
			var chequeo = document.createElement('input');
			chequeo.setAttribute('type','checkbox');
			chequeo.setAttribute('name','bebe'+num.value);
			var select1 = document.createElement('select');
			select1.setAttribute('name','menores'+num.value);
			var adulto = new Option('Adulto','1',true,false);
			var menor = new Option('Ni'+String.fromCharCode(0x00f1)+'o','2',false,false);
			try {
				select1.add(adulto,null);
				select1.add(menor,null);				
			} 
			catch(ex) {
				select1.add(adulto);
				select1.add(menor);		
			}
			

			td.appendChild(select1);
			td2.appendChild(pregunta);
			td2.appendChild(chequeo);
			tr.appendChild(td);
			tr.appendChild(td2);
		} else if(i == 3) {
			var td = document.createElement('td');
			var td2 = document.createElement('td');
			
			var texto = document.createTextNode('Nombre(s) * (Obligatorio)');
			var input = document.createElement('input');
			input.setAttribute('type','text');
			input.setAttribute('name','name'+num.value);
			input.className = 'input1';
			td.appendChild(texto);
			td2.appendChild(input);
			tr.appendChild(td);
			tr.appendChild(td2);
		} else if(i == 4) {
			var td = document.createElement('td');
			var td2 = document.createElement('td');
			
			var texto = document.createTextNode('Apellido (*)');
			var input = document.createElement('input');
			input.setAttribute('type','text');
			input.setAttribute('name','lastname'+num.value);
			input.className='input1';
			
			td.appendChild(texto);
			td2.appendChild(input);
			
			tr.appendChild(td);
			tr.appendChild(td2);
			
		} else if(i == 5) {
			var td = document.createElement('td');
			var td2 = document.createElement('td');
			
			var texto = document.createTextNode("N"+String.fromCharCode(0x00fa)+"mero de pasaporte");
			var input = document.createElement('input');
			input.setAttribute('type','text');
			input.setAttribute('name','passport'+num.value);
			input.className='input1';
			
			td.appendChild(texto);
			td2.appendChild(input);
			
			tr.appendChild(td);
			tr.appendChild(td2);			
		
		} else if(i == 6) {
			var td = document.createElement('td');
			var td2 = document.createElement('td');

			var texto = document.createTextNode('N'+String.fromCharCode(0x00fa)+"mero de documento");
			var input = document.createElement('input');
			input.setAttribute('type','text');
			input.setAttribute('name','dni'+num.value);
			input.className='input1';			
			
			td.appendChild(texto);
			td2.appendChild(input);
			
			tr.appendChild(td);
			tr.appendChild(td2);		
		} else if(i == 7) {
			var td = document.createElement('td');
			var td2 = document.createElement('td');
			
			var texto = document.createTextNode('Pa'+String.fromCharCode(0x00ed)+"s de residencia");
			td.appendChild(texto);


			var select = document.createElement('select');
			//select.setAttribute('type','select');
			try {
				var option0 = new Option('Afganistan','1',false,false);
			} catch(ex) {
				var option0 = new Option('Afganistan','1');
			}
			select.appendChild(option0);

			td2.appendChild(select);			
			
			tr.appendChild(td);
			tr.appendChild(td2);
		
		} else if(i ==8) {
			var td = document.createElement('td');		
		}
		tabla.appendChild(tr);
	}
	
	// seteamos los atributos
	tabla.setAttribute('align','center');
	tabla.setAttribute('width','100%');
	
	// hacemos los appends
	contenedor.appendChild(tabla);
	num.value = parseInt(num.value) + 1;
	
}

function handleRep(){
	if(http.readyState == 4){ //Finished loading the response
		var response = http.responseText;
		var elem_actual = document.getElementById("elem_actual").value;
		document.getElementById('container_' + elem_actual).innerHTML = response;
	}
}


function agregarElemento(elemento,valor,select,destino) {
	var inputSelect = document.getElementById(select);
	var elemDestino = document.getElementById(destino);
	var elemDeleteLink = document.createElement('a');
	
	
	var newDeleteButton = document.createTextNode('[Eliminar]');
	var newElem = document.createElement('li');
	if (navigator.appName.indexOf('Microsoft') != -1) {
		var newOpt = new Option(elemento,valor);
		document.getElementById(select).add(newOpt);
		newOpt.setAttribute('selected','selected');
		newElem.id = destino + '_' + valor;
		elemDeleteLink.href = 'javascript:eliminarElemento(\''+valor+'\',\''+select+'\',\''+destino+'\');';
		//elemDeleteLink.onclick = 'javascript:eliminarElemento('+valor+','+select+','+destino+');';
		//alert(newElem.id);
	} else {
		var newOpt = new Option(elemento,valor,false,true);
		newOpt.setAttribute('selected','selected');
		document.getElementById(select).add(newOpt,null);
		newElem.setAttribute('id',destino+'_'+valor);
		elemDeleteLink.setAttribute('href','javascript:void(0);');
		elemDeleteLink.setAttribute('onclick','javascript:eliminarElemento(\''+valor+'\',\''+select+'\',\''+destino+'\');');
	}
	
	
	
	
	var newNodeText = document.createTextNode(elemento + ' ');
	newElem.appendChild(newNodeText);
	elemDeleteLink.appendChild(newDeleteButton);
	newElem.appendChild(elemDeleteLink);
	elemDestino.appendChild(newElem);
	//alert('Agregado \'' + elemento + '\' al listado de relaciones en '+select+'.');
	if(select == 'select_eventos') {
		ms_cal.resetSelections();
	}
}

function eliminarElemento(id,select,destino) {
	var elemDestino = document.getElementById(select);
	var elemList = document.getElementById(destino);
	var elemListItem = document.getElementById(destino+'_'+id);
	//alert(elemDestino.length);
	for(var i = elemDestino.length - 1; i >= 0; i--) {
		if(elemDestino.options[i].value == id) {
			//alert(elemDestino.options[i].text);
			elemDestino.removeChild(elemDestino.options[i]);
			//elemList.removeChild(elemListItem);
			elemListItem.parentNode.removeChild(elemListItem);
			//alert('eliminado '+ i);
		}
	}
}

var http_request = false;
function makePOSTRequest(url, parameters) {
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
        	// set type accordingly to anticipated content type
        //http_request.overrideMimeType('text/xml');
        http_request.overrideMimeType('text/html');
        }
    } else if (window.ActiveXObject) { // IE
        try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
        try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
        }
    }
    if (!http_request) {
        alert('Cannot create XMLHTTP instance');
        return false;
    }
    
    http_request.onreadystatechange = alertContents;
    http_request.open('POST', url, true);
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", parameters.length);
    http_request.setRequestHeader("Connection", "close");
    http_request.send(parameters);
}

function alertContents() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
        //alert(http_request.responseText);
        result = http_request.responseText;
        document.getElementById('pepe1').innerHTML = '';
        document.getElementById('pepe1').innerHTML = result;            
        } else {
        	alert('There was a problem with the request.');
        }
    }
}

function get(obj) {
	var artistas = processMultiElem(document.getElementById('frm_rel_artistas'));
	var contenidos = processMultiElem(document.getElementById('frm_rel_contenidos'));
	var canales = processMultiElem(document.getElementById('frm_rel_proveedores'));
	var oEditor = FCKeditorAPI.GetInstance('txt_esp');
	oEditor.UpdateLinkedField();
	var txt_esp = document.getElementById('txt_esp').value;
	var myForm = document.getElementById('content');
	var inputs1 = myForm.getElementsByTagName('input');
	var select1 = myForm.getElementsByTagName('select');
	var textarea1 = myForm.getElementsByTagName('textarea');

    var poststr = encodeURI ( artistas ) + encodeURI( contenidos ) + encodeURI( canales);
    for(i = 0; i < inputs1.length; i++) {
    	if(inputs1[i].type == 'radio') {
    		if(inputs1[i].checked) {
	    		poststr += '&' + inputs1[i].name + '=' + encodeURI(inputs1[i].value);
	    	}
    	} else {
    		poststr += '&' + inputs1[i].name + '=' + encodeURI(inputs1[i].value);
    	}
    }
    for(i = 0; i < textarea1.length; i++) {
    	poststr += '&' + textarea1[i].name + '=' + encodeURI(textarea1[i].value);
    }    
    for(i = 0; i < select1.length; i++) {
    	if(select1[i].multiple) {
    		//poststr += processMultiElem(select1[i]);
    	} else {
    		poststr += '&' + select1[i].name + '=' + encodeURI(select1[i].value);
    	}
    }
    poststr += '&txt_esp=' + escape(txt_esp);
    makePOSTRequest('pepe.php', poststr);
}

function processMultiElem(elem) {
	var oElemento = elem.options;
	var oElementoLargo = oElemento.length;
	var response_text = '';
	for(i = 0;i < oElementoLargo; i++) {
		response_text += elem.name + '[]='+ encodeURI(elem.options[i].value) + '&';
	}
	return response_text;
}

function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

function convertir() {
	var from = document.getElementById('from_currency').options[document.getElementById('from_currency').selectedIndex].value;
	var to = document.getElementById('to_currency').options[document.getElementById('to_currency').selectedIndex].value;
	var cantidad = document.getElementById('cant_currency').value;
	//alert(cantidad);
	if(cantidad == '') {
		alert('Debe ingresar una cantidad para realizar la conversion');
		document.getElementById('cant_currency').focus();
	}
	sndReqSitio('currency',from+'@'+to+'@'+cantidad);
	magicdiv = 'resultado_currency';
	document.getElementById(magicdiv).style.display = 'block';
	document.getElementById(magicdiv).innerHTML = '<img src=\"img/loading.gif\" width=\"16\" height=\"22\" align=\"absmiddle\"> Realizando conversi&oacute;n';
}

function validar_mail(t){
	//txt=document.getElementById('email_derecha').value;
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(t)){
		return (true);
	} else {
		alert("La dirección de email es incorrecta.");
		return (false);
	}
}


function recomendar(url){
	var url1 = 'index.php?id=popup&pid='+url;
	var win = window.open(url1,"","width=460,height=450,scrollbars=no,toolbar=no,menubar=no");
}

function doThePNGcrapAgain(){
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	
	if ((version >= 5.5) && (document.body.filters)) 
	{
	  for(var i=0; i<document.images.length; i++)
	  {
	 var img = document.images[i]
	 var imgName = img.src.toUpperCase()
	 if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
	 {
	var imgID = (img.id) ? "id='" + img.id + "' " : ""
	var imgClass = (img.className) ? "class='" + img.className + "' " : ""
	var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
	var imgStyle = "display:inline-block;" + img.style.cssText 
	if (img.align == "left") imgStyle = "float:left;" + imgStyle
	if (img.align == "right") imgStyle = "float:right;" + imgStyle
	if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
	var strNewHTML = "<span " + imgID + imgClass + imgTitle
	+ " style=\"z-index:1;" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
	+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
	+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
	img.outerHTML = strNewHTML
	i = i-1
	 }
	  }
	} 
}