// JavaScript Document
function notificarSimple(mensaje){
	var cerrar = ' <a href="javascript:;" onclick="new Effect.SlideUp(document.getElementById(\'notify\'), {duration:0.3})">Cerrar</a>';
	var noti = document.getElementById('notify');	
	noti.style.display = 'none';
	noti.innerHTML = '<p>'+mensaje+cerrar+'</p>';
	new Effect.SlideDown(noti, {duration: 0.2});
	
}

function notificar(mensaje, id, tipo_input){
	var elemento = document.getElementById(id);
	elemento.className = tipo_input+'error';
	var cerrar = ' <a href="javascript:;" onclick="new Effect.SlideUp(document.getElementById(\'notify\'), {duration:0.3})">Cerrar</a>';
	var noti = document.getElementById('notify');	
	noti.style.display = 'none';
	noti.innerHTML = '<p>'+mensaje+cerrar+'</p>';
	new Effect.SlideDown(noti, {duration: 0.2});
	elemento.focus();
}

function confirmar(text, action){
	var texto = text+'   <a href="javascript:;" onclick="'+action+';new Effect.SlideUp(document.getElementById(\'notify\'), {duration:0.3})">Si</a> ';
	texto += '<a href="javascript:;" onclick="new Effect.SlideUp(document.getElementById(\'notify\'), {duration:0.3})">No</a>';
	var noti = document.getElementById('notify');	
	noti.style.display = 'none';
	noti.innerHTML = '<p>'+texto+'</p>';
	new Effect.SlideDown(noti, {duration: 0.2});
}

function borrarMiAuto(id){
	confirmar('&iquest;Esta seguro que desea borrar la publicaci&oacute;n?', 'borrarPublicacion('+id+')');
}

function invertir(id){
	var obj = document.getElementById(id);
	var bool = document.getElementById('advanced_boolean');
	if (obj.style.display=='none'){
		obj.style.display = '';
		bool.value = 1;
	}
	else{
		obj.style.display = 'none';
		bool.value = 0;
	}
}

function invertirSimple(id){
	var obj = document.getElementById(id);
	if (obj.style.display=='none'){
		obj.style.display = '';
	}
	else{
		obj.style.display = 'none';
	}
}

//EMAIL VALIDATOR
	function isValidEmail(field) {
		var goodEmail = field.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
		if (goodEmail){
			return true;
		} else {
			return false;
		}
	}
// FIN EMAIL VALIDATOR

function isInteger (s)
   {
      var i;
      for (i = 0; i < s.length; i++)
      {
         var c = s.charAt(i);

         if (!((c >= "0") && (c <= "9"))) return false;
      }

      return true;
   }

function valida_comentario(id_publicacion, propietario){
	var noti = document.getElementById('notify');	
	noti.style.display = 'none';
	var nombre = document.getElementById('nombre');
	var email = document.getElementById('email');
	var mensaje = document.getElementById('mensaje');
	//var suscripcion = document.getElementById('suscripcion');
	//if(suscripcion.checked)
	//	suscripcion = 1;
	//else
		var suscripcion = 0;
	nombre.className = 'input';
	email.className = 'input';
	mensaje.className = 'textarea';
	
	if(nombre.value == 'nombre:' || nombre.value == ''){
		notificar('Por favor ingrese un nombre v&aacute;lido.', 'nombre', 'input_');
		return false;
	}
	if(email.value == 'email:' || email.value == '' || !isValidEmail(email.value)){
		notificar('Por favor ingrese un email v&aacute;lido.', 'email', 'input_');
		return false;
	}
	if(mensaje.value == ''){
		notificar('Por favor ingrese un mensaje.', 'mensaje', 'textarea_');
		return false;
	}
	
	comentar(id_publicacion, nombre.value, email.value, mensaje.value, propietario, suscripcion);	
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

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;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/*function cambiar_foto(foto){
	MM_swapImage('imageHolder','',foto,1);
}*/

function valida_crear_usuario(){
	var noti = document.getElementById('notify');	
	noti.style.display = 'none';
	var login = document.getElementById('login');
	login.className = 'input';
	var disponibilidad_login = document.getElementById('disponibilidad_login');
	var email = document.getElementById('email');
	email.className = 'input';
	var disponibilidad_email = document.getElementById('disponibilidad_email');
	var condiciones = document.getElementById('condiciones');
	condiciones.className = 'checkbox';
	
	
	if(login.value == "" || disponibilidad_login.className == 'disponibilidad_err'){
		notificar('Por favor ingrese su login.', 'login', 'input_');
		return false;
	}
	if(email.value == ""  || disponibilidad_email.className == 'disponibilidad_err'){
		notificar('Por favor ingrese su email (v&aacute;lido).', 'email', 'input_');
		return false;
	}
	if(condiciones.checked == false){
		notificar('Para realizar su registro, debe aceptar las condiciones.', 'condiciones', 'checkbox_');
		return false;
	}
	crear_usuario();
}
function valida_publicar(){
	var noti = document.getElementById('notify');	
	noti.style.display = 'none';
	var registro = document.getElementById('registro');
	var tipo_ = document.getElementById('tipo');
	var tipo = tipo_.selectedIndex;
	tipo_.className = 'select';
	var modelo = document.getElementById('modelo');
	modelo.className = 'input';
	var ano_ = document.getElementById('ano');
	var ano = ano_.selectedIndex;
	ano_.className = 'select';
	var precio = document.getElementById('precio');
	precio.className = 'input';
	var photo_status = $F('photo_status');

	var username = document.getElementById('username').value;
	
	if(username == 0){
		notificar('Por favor cree su cuenta de usuario.', 'login', 'input_');
		return false;
	}
	
	if(tipo == 0){
		notificar('Por favor elija un tipo de veh&iacute;culo.', 'tipo', 'select_');
		return false;
	}
	if(modelo.value == ''){
		notificar('Por favor ingrese el modelo de su veh&iacute;culo.', 'modelo', 'input_');
		return false;
	}
	if(ano == 0){
		notificar('Por favor elija el a&ntilde;o de su veh&iacute;culo.', 'ano', 'select_');
		return false;
	}
	if(precio.value == ''){
		notificar('Por favor ingrese el precio de su veh&iacute;culo.', 'precio', 'input_');
		return false;
	}
	if(isNaN(precio.value) || !isInteger(precio.value)){
		notificar('Por favor ingrese el precio de manera num&eacute;rica sin puntos ni comas.', 'precio', 'input_');
		return false;
	}
	if(photo_status == 'none'){
		notificarSimple('Por favor adjunte al menos una foto de su veh&iacute;culo.');
		return false;
	}
	if(photo_status == 'cargando'){
		notificarSimple('Espere un momento, se est&aacute; cargando la foto de su veh&iacute;culo.');
		return false;
	}
	
	var boton = $('boton_publicar');
	boton.innerHTML = '<p>Publicando... Espere un momento.</p>';
	publicar();
}

function navegar(criterio, valor){
	
	var tipo = document.getElementById('tipo_vehiculo');
	tipo.options[0].selected = true;
	var marca = document.getElementById('marca');
	marca.options[0].selected = true;
	var ano_desde = document.getElementById('ano_desde');
	ano_desde.options[0].selected = true;
	var ano_hasta = document.getElementById('ano_hasta');
	ano_hasta.options[ano_hasta.length-1].selected = true;
	var precio_desde = document.getElementById('precio_desde');
	precio_desde.options[0].selected = true;
	var precio_hasta = document.getElementById('precio_hasta');
	precio_hasta.options[precio_hasta.length-1].selected = true;
	
	var bool = document.getElementById('advanced_boolean');
	bool.value = 1;
	
	if(criterio == 'tipo'){
		for (var i=0;i<tipo.length;i++)
		{
			if (tipo.options[i].value == valor)
				tipo.options[i].selected=true;
		}
	}
	
	else if(criterio == 'marca'){
		for (var i=0;i<marca.length;i++)
		{
			if (marca.options[i].value == valor)
				marca.options[i].selected=true;
		}
	}
	ordenar('');
	bool.value = 0;
}

function cambiarCategoria(categoria){
	
	var tipos = document.getElementById('tipos');
	var marcas = document.getElementById('marcas');
	var concesionarias = document.getElementById('concesionarias');
	
	tipos.style.display = 'none';
	marcas.style.display = 'none';
	concesionarias.style.display = 'none';
	
	eval(categoria+'.style.display = "block"');
	
	document.getElementById('link_tipos').className = '';
	document.getElementById('link_marcas').className = '';
	document.getElementById('link_concesionarias').className = '';
	
	eval("document.getElementById('link_"+categoria+"').className = 'nav_menu_current'");
}

function cambiarLosMas(categoria){
	
	var recientes = document.getElementById('recientes');
	var buscados = document.getElementById('buscados');
	
	recientes.style.display = 'none';
	buscados.style.display = 'none';
	
	eval(categoria+'.style.display = "block"');
	
	var link_recientes = document.getElementById('link_recientes');
	link_recientes.className = '';
	var link_buscados = document.getElementById('link_buscados');
	link_buscados.className = '';
	eval("link_"+categoria+".className = 'nav_menu_current';");
}

function valida_registro(){
	var noti = document.getElementById('notify');	
	noti.style.display = 'none';
	var login = document.getElementById('login');
	login.className = 'input';
	var disponibilidad_login = document.getElementById('disponibilidad_login');
	var clave = document.getElementById('clave');
	clave.className = 'input';
	var clave2 = document.getElementById('clave2');
	clave2.className = 'input';
	var nombre = document.getElementById('nombre');
	nombre.className = 'input';
	var email = document.getElementById('email');
	email.className = 'input';
	var disponibilidad_email = document.getElementById('disponibilidad_email');
	var telefono = document.getElementById('telefono');
	telefono.className = 'input';
	var ciudad = document.getElementById('ciudad');
	ciudad.className = 'select';
	var nueva_ciudad = document.getElementById('nueva_ciudad');
	var nueva_ciudad_div = document.getElementById('nueva_ciudad_div');
	nueva_ciudad.className = 'input';
	var comuna = document.getElementById('comuna');
	comuna.className = 'select';
	var nueva_comuna = document.getElementById('nueva_comuna');
	var nueva_comuna_div = document.getElementById('nueva_comuna_div');
	nueva_comuna.className = 'input';
	var direccion = document.getElementById('direccion');
	direccion.className = 'input';
	var condiciones = document.getElementById('condiciones');
	condiciones.className = 'checkbox';
	
	if(condiciones.checked == false){
		notificar('Para realizar su registro, debe aceptar las condiciones.', 'condiciones', 'checkbox_');
		return false;
	}
	
	if(login.value == '' || disponibilidad_login.className == 'disponibilidad_err'){
		notificar('Por favor elija un login o nombre de usuario.', 'login', 'input_');
		return false;
	}
	if(clave.value == ''){
		notificar('Por favor ingrese su clave.', 'clave', 'input_');
		return false;
	}
	if(clave2.value == ''){
		notificar('Por favor re-ingrese su clave.', 'clave2', 'input_');
		return false;
	}
	if(nombre.value == ''){
		notificar('Por favor ingrese su nombre.', 'nombre', 'input_');
		return false;
	}
	if(email.value == '' || disponibilidad_email.className == 'disponibilidad_err'){
		notificar('Por favor ingrese su e-mail (v&aacute;lido).', 'email', 'input_');
		return false;
	}
	if(!isValidEmail(email.value)){
		notificar('Por favor ingrese un email v&aacute;lido.', 'email', 'input_');
		return false;
	}
	if(telefono.value == ''){
		notificar('Por favor ingrese su tel&eacute;fono.', 'telefono', 'input_');
		return false;
	}
	if(isNaN(telefono.value) || !isInteger(telefono.value)){
		notificar('Por favor ingrese su tel&eacute;fono sin puntos ni guiones.', 'telefono', 'input_');
		return false;
	}
	if(ciudad.selectedIndex == 0){
		notificar('Por favor ingrese su ciudad.', 'ciudad', 'select_');
		return false;
	}
	if(nueva_ciudad_div.style.display != 'none' && nueva_ciudad.value == ''){
		notificar('Por favor ingrese el nombre de su ciudad', 'nueva_ciudad', 'input_');
		return false;
	}
	if(comuna.selectedIndex == 0 && !comuna.disabled){
		notificar('Por favor ingrese su comuna.', 'comuna', 'select_');
		return false;
	}
	if(nueva_comuna_div.style.display != 'none' && nueva_comuna.value == ''){
		notificar('Por favor ingrese el nombre de su comuna', 'nueva_comuna', 'input_');
		return false;
	}	
	if(direccion.value == ''){
		notificar('Por favor ingrese su direcci&oacute;n.', 'direccion', 'input_');
		return false;
	}
	if(clave.value != clave2.value){
		notificar('La clave no calza con la clave ingresada en la repetici&oacute;n.', 'clave2', 'input_');
		return false;
	}
	registrar();
}

function setCiudad(){
	
	var indice = document.getElementById('ciudad').selectedIndex;
    var valor = document.getElementById('ciudad').options[indice].value;
	
	if(valor == 'OTRA'){
		document.getElementById('nueva_ciudad_div').style.display = '';
		document.getElementById('nueva_ciudad').focus();
		document.getElementById('comuna').disabled = true;
		document.getElementById('nueva_comuna_div').style.display = '';
		return false;
	}
	
	document.getElementById('nueva_ciudad_div').style.display = 'none';
	document.getElementById('nueva_comuna_div').style.display = 'none';
	document.getElementById('comuna').disabled = false;
	
	var comunas = document.getElementById('array_comunas').value.split("##");
	var ciudades = document.getElementById('array_ciudades').value.split("##");
	
	var ciudad = document.getElementById('ciudad');
	var comuna = document.getElementById('comuna');
	
	k=0;
	while(comuna.options[k]!=null){
		comuna.options[k]=null;
	}
	opcion=new Option("-Elija Comuna-","NO");
	comuna.options[0]=opcion;
	
	var j=1;
	for(i in ciudades){
		if(ciudades[i]==valor){
			if(comunas[i]!=comunas[i-1]){
				opcion=new Option(comunas[i],comunas[i]);
				comuna.options[j]=opcion;
				j++;
			}
		}
	}
	opcion=new Option("-OTRA-","OTRA");
	comuna.options[j]=opcion;
		
}

function setComuna(){
	
	var indice = document.getElementById('comuna').selectedIndex;
    var valor = document.getElementById('comuna').options[indice].value;
	
	if(valor == 'OTRA'){
		document.getElementById('nueva_comuna_div').style.display = '';
		document.getElementById('nueva_comuna').focus();
		return false;
	}	
	
	document.getElementById('nueva_comuna_div').style.display = 'none';
}

function miperfil_editar(elemento){
	invertirSimple(elemento+'_view');
	invertirSimple(elemento+'_edit');
}

function miperfil_guardar(elemento){
	var noti = document.getElementById('notify');	
	noti.style.display = 'none';
	var nombre = document.getElementById('nombre');
	nombre.className = 'input';
	var nombre_edit = document.getElementById('nombre_edit');
	var email = document.getElementById('email');
	email.className = 'input';
	var email_edit = document.getElementById('email_edit');
	var telefono = document.getElementById('telefono');
	telefono.className = 'input';
	var telefono_edit = document.getElementById('telefono_edit');
	var ciudad = document.getElementById('ciudad');
	ciudad.className = 'select';
	var nueva_ciudad = document.getElementById('nueva_ciudad');
	var nueva_ciudad_div = document.getElementById('nueva_ciudad_div');
	nueva_ciudad.className = 'input';
	var comuna = document.getElementById('comuna');
	comuna.className = 'select';
	var nueva_comuna = document.getElementById('nueva_comuna');
	var nueva_comuna_div = document.getElementById('nueva_comuna_div');
	nueva_comuna.className = 'input';
	var direccion = document.getElementById('direccion');
	direccion.className = 'input';
	var ubicacion_edit = document.getElementById('ubicacion_edit');
	
	if(nombre_edit.style.display!='none' && nombre.value == ''){
		notificar('Por favor ingrese su nombre.', 'nombre', 'input_');
		return false;
	}
	if(email_edit.style.display!='none' && email.value == ''){
		notificar('Por favor ingrese su e-mail.', 'email', 'input_');
		return false;
	}
	if(email_edit.style.display!='none' && !isValidEmail(email.value)){
		notificar('Por favor ingrese un email v&aacute;lido.', 'email', 'input_');
		return false;
	}
	if(telefono_edit.style.display!='none' && telefono.value == ''){
		notificar('Por favor ingrese su tel&eacute;fono.', 'telefono', 'input_');
		return false;
	}
	if(telefono_edit.style.display!='none' && (isNaN(telefono.value) || !isInteger(telefono.value))){
		notificar('Por favor ingrese su tel&eacute;fono sin puntos ni guiones.', 'telefono', 'input_');
		return false;
	}
	if(ubicacion_edit.style.display!='none' && ciudad.selectedIndex == 0){
		notificar('Por favor ingrese su ciudad.', 'ciudad', 'select_');
		return false;
	}
	if(ubicacion_edit.style.display!='none' && nueva_ciudad_div.style.display != 'none' && nueva_ciudad.value == ''){
		notificar('Por favor ingrese el nombre de su ciudad', 'nueva_ciudad', 'input_');
		return false;
	}
	if(ubicacion_edit.style.display!='none' && comuna.selectedIndex == 0 && !comuna.disabled){
		notificar('Por favor ingrese su comuna.', 'comuna', 'select_');
		return false;
	}
	if(ubicacion_edit.style.display!='none' && nueva_comuna_div.style.display != 'none' && nueva_comuna.value == ''){
		notificar('Por favor ingrese el nombre de su comuna', 'nueva_comuna', 'input_');
		return false;
	}	
	if(ubicacion_edit.style.display!='none' && direccion.value == ''){
		notificar('Por favor ingrese su direcci&oacute;n.', 'direccion', 'input_');
		return false;
	}
	miperil_guardarCambios(elemento);
}

function miperfil_validarCambioClave(){
	var noti = document.getElementById('notify');	
	noti.style.display = 'none';
	var nueva = $F('nuevaclave');
	var nueva2 = $F('nuevaclave2');
	nueva.className = 'input';
	nueva2.className = 'input';
	if(nueva == ''){
		notificar('Por favor ingrese su nueva clave.', 'nuevaclave', 'input_');
		return false;
	}
	if(nueva2 == ''){
		notificar('Por favor confirme su nueva clave.', 'nuevaclave2', 'input_');
		return false;
	}
	if(nueva != nueva2){
		notificar('La confirmaci&oacute;n de su clave no calza con su nueva clave.', 'nuevaclave2', 'input_');
		return false;
	}
	
	miperfil_cambioClave();
}

function validar_denunciar(id){
	var motivo = $('motivo_denuncia');
	motivo.className = 'input';
	if(motivo.value == ''){
		notificar('Para hacer efectiva una denuncia, debe explicar su motivo.', 'motivo_denuncia', 'input_');
		return false;
	}
	denunciar(id);
}

function edicion_marcarPrincipal(id){
	marcarImagen(id);
}

function valida_guardaCambios(){
	var noti = document.getElementById('notify');	
	noti.style.display = 'none';
	var tipo_ = document.getElementById('tipo');
	var tipo = tipo_.selectedIndex;
	tipo_.className = 'select';
	var modelo = document.getElementById('modelo');
	modelo.className = 'input';
	var ano_ = document.getElementById('ano');
	var ano = ano_.selectedIndex;
	ano_.className = 'select';
	var precio = document.getElementById('precio');
	precio.className = 'input';
	
	if(tipo == 0){
		notificar('Por favor elija un tipo de pieza.', 'tipo', 'select_');
		return false;
	}
	if(modelo.value == ''){
		notificar('Por favor ingrese el nombre de su pieza.', 'modelo', 'input_');
		return false;
	}
	if(precio.value == ''){
		notificar('Por favor ingrese el precio de su pieza.', 'precio', 'input_');
		return false;
	}
	if(isNaN(precio.value) || !isInteger(precio.value)){
		notificar('Por favor ingrese el precio de manera num&eacute;rica sin puntos ni comas.', 'precio', 'input_');
		return false;
	}
	
	var boton = $('boton_publicar');
	boton.innerHTML = '<p>Guardando sus cambios... Espere un momento.</p>';
	
	guardarCambios();
}

function setEstado(estado){
	if(estado == 'nuevo'){
		var ano = document.getElementById('ano');
		ano.options[1].selected = true;
		ano.disabled = true;
	}
	else{
		var ano = document.getElementById('ano');
		ano.options[0].selected = true;
		ano.disabled = false;
	}
}

function olvidePswd(){
	var div = document.getElementById('recuperacion');
	div.style.display = "";
}

function validaOlvidePswd(){
	var email = document.getElementById('rec_email');
	if (!isValidEmail(email.value)){
		notificar('Por favor ingrese un email v&aacute;lido para recuperar su clave.', 'rec_email', 'input_');
		return false;
	}
	enviarPswd(email.value);
	return true;
}
