/*----------------------------
	Funciones basadas en AJAX.	
----------------------------------*/

/*
	Creacion de objeto ajax necesario para realizar las consultas por xmlhttprequest(consultas dinamicas)
*/
function objetoAjax()
{
	var xmlhttp=false;
	try {	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");	}
	catch(e)
	{
		try{   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");	} 
		catch(E){  xmlhttp = false;		}
	}

	if (!xmlhttp && typeof XMLHttpRequest!='undefined'){
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

function borrar_foto(id, id_product)
{
	if(confirm('¿Estas seguro de eliminar esta foto?'))
	{
		var ajax = objetoAjax();
		var element = document.getElementById('results');
		var url = '/admin/functions.php?action=borrar_foto&id='+ id +'&id_product='+ id_product;
		
		ajax.open("POST", url , true);
		
		ajax.onreadystatechange=function()
		{
			if(ajax.readyState==1)
			{
				element.innerHTML = '<center><img src="/admin/images/loading.gif" /></center>';
			}
			if(ajax.readyState==4)
			{
				element.innerHTML = ajax.responseText;
			}
		}
		ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		ajax.send(null);
		return false;
	}
}

/*-----------------------------------
		Fin funciones AJAX
-----------------------------------------*/

var fileIndex = 1; //esta variable probiene del archivo donde es llamado el javascript		
function addOne() {			//añade una tecla en el script crear_editar_ivr.php
	var link = document.getElementById('addOne');
	link.blur();
	document.getElementById('imagen_' + ++fileIndex).style.display = '';
	document.form.count.value = fileIndex;
	
	if (fileIndex >= document.form.foto_max.value) {
		link.style.display = 'none';
	}
}


function bodyUnload(){
	document.getElementById('content').style.display='none';
	document.getElementById('carga').style.display='';
}

function h_location(pagina){		
	window.location.href = pagina;	
}



/*
	muestra/oculta los elementos del html
*/
function show(elements , action){		
	var arr_ele = elements.split(',');
	var obj='';
	for(var i=0; i < arr_ele.length; i++){
		obj = document.getElementById(arr_ele[i]);
		if(action){
			obj.style.display = action;
		}
		else{
			obj.style.display = (obj.style.display == 'none')? '' : 'none';
		}
		
	}
}



function borrar(cad,elemento,tabla){				//borra elementos en la base de datos con confirmacion
	if(confirm("¿Esta seguro de eliminar "+ cad +"?")==true){
		document.form.borrar.value=elemento;
		document.form.tabla.value=tabla;
		document.form.submit();
	}
}

function face(elemento,accion){				//da valores a campos ocultos para colocar imagenes en portada
	document.form.ele.value=elemento;
	document.form.face.value=accion;
	document.form.submit();
}

function validateEmail(elementValue,element2){		//validacion de e-mail
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; 
	if(!emailPattern.test(elementValue)){
		document.getElementById(element2).src='images/icon-invalid.png';
	}
	else{
		document.getElementById(element2).src='images/icon-valid.png';
	}	
}


function comprueba_extension(formulario, archivo){		//comprueba que el archivo sea de la extension correcta
   extensiones_permitidas = new Array(".gsm", ".wav",".mp3");
   if (!archivo) {
        alert("No has seleccionado ningún archivo");
		return false;
   }
   else{
      //recupero la extensión de este nombre de archivo
      extension = (archivo.substring(archivo.lastIndexOf("."))).toLowerCase();
      //compruebo si la extensión está entre las permitidas
      permitida = false;
      for (var i = 0; i < extensiones_permitidas.length; i++){
         if (extensiones_permitidas[i] == extension) {
         permitida = true;
         break;
         }
      }
      if (!permitida){
         alert("Comprueba la extensión de los archivos a subir. \nSólo se pueden subir archivos con extensiones: " + extensiones_permitidas.join());
		 return false;
      }
	  else{
          //submito!
         alert ("Todo correcto. Se procedera a subir el archivo.");
         formulario.submit();
         return true;
      }
   } 
}


function validar_num(e) {				//valida que un campo sea numerico
    tecla = (document.all)?e.keyCode:e.which;
	if (tecla==8 || tecla==0 || tecla==44 || tecla==46 ) return true; //44 y 46 = coma y punto
    patron = /\d/; //la d es el patron para numeros y w es para alfanumericos
    te = String.fromCharCode(tecla);  // se pasa el valor numérico de la tecla pulsada a carácter. Si el código es 65 te valdrá "A", etc.
    if(!patron.test(te))  // si el valor de te coincide con el patrón la función devolverá true, si no coincide devolverá false y la pulsación de tecla se ignorará.
	alert ("Solo puedes introducir numeros");
	return patron.test(te);
} 




function slide_img(div,src_img){		//esta funcion crea un slide show con efecto lightbox requiere de prototype y scriptaculus
	var html='';
	document.getElementById(div).innerHTML = html;	
	
	var imgPreloader = new Image();
	imgPreloader.src = src_img;	
	
	imgPreloader.onload = (function(){
			var borderSize=0;
			// get current width and height
			var widthCurrent  = $(div).getWidth();
			var heightCurrent = $(div).getHeight();	
			
			// get new width and height
			var widthNew  = (imgPreloader.width  + borderSize * 2);
			var heightNew = (imgPreloader.height + borderSize * 2); 
			
			// scalars based on change from old to new
			var xScale = (widthNew  / widthCurrent)  * 100;
			var yScale = (heightNew / heightCurrent) * 100; 
			
				
			// calculate size difference between new and old image, and resize if necessary
			var wDiff = widthCurrent - widthNew;
			var hDiff = heightCurrent - heightNew; 
			
			if (hDiff != 0) new Effect.Scale('show', yScale, {scaleX: false, queue: 'front'}); 
			if (wDiff != 0) new Effect.Scale('show', xScale, {scaleY: false}); 
			
			html='<img id="show_img" style="display:none" align="absmiddle" src="' + src_img + '" />';
			document.getElementById(div).innerHTML = html;
			new Effect.Appear('show_img', {queue: 'end'});
	});
}

