﻿function utilidades() {
	this.contornoPoblacion = null;
	this.vectorGeometria = new Array();
	this.vectorPoblacion = null;
	this.fotosCarrusel = new Array();
}

utilidades.prototype.dibujaProvincia = function(cp){
	
	if(this.contornoPoblacion)
		map.removeOverlay(this.contornoPoblacion);
	
	GDownloadUrl("php/limitesProvincias.php?cp="+cp, function(data, responseCode) {
				  // To ensure against HTTP errors that result in null or bad data,
				  // always check status code is equal to 200 before processing the data
				  if(responseCode == 200) {
					    var xml = GXml.parse(data);
					    
					    var items = xml.documentElement.getElementsByTagName("marker");
					    
					    utilidadesOBJ.vectorPoblacion = items[0].getAttribute("limites");
			        
			        if (utilidadesOBJ.vectorPoblacion.length > 12){
					        var vectorGeometria = utilidadesOBJ.vectorPoblacion.split("|"); 
									var XY = new Array(); 
									var points = []; 
									
									//GLog.write("Total Puntos inicial: " + vectorGeometria.length);
									
									for (var i = 0; i < vectorGeometria.length; i++) 
									{ 
										XY = vectorGeometria[i].split(',');  
										points.push( new GLatLng(parseFloat(XY[1]),parseFloat(XY[0])));
										i+=4;
									} 
									//GLog.write("Total Puntos inicial: " + points.length);
									
									utilidadesOBJ.contornoPoblacion = new GPolygon(points,'#8cb600', 1, 1, '#c5ff02', 0.35);
									
									//cargo los iconos de las tiendas
									muestraTiendas('cp', cp);
									//Dibujo el contorno de la provincia
									map.addOverlay(utilidadesOBJ.contornoPoblacion);
									
									///Centramos el poligono en la pantalla
									var bounds=utilidadesOBJ.contornoPoblacion.getBounds();
							    // ===== determine the zoom level from the bounds =====
				          map.setZoom(map.getBoundsZoomLevel(bounds));
				          // ===== determine the centre from the bounds ======
				          map.setCenter(bounds.getCenter());
				          ///Fin dentrado del poligono el la pantalla
				          
	        		}else {
							    muestraTiendas('cp', cp, 'nombre_poblacion');
	        		}
				  } else if(responseCode == -1) {
				    alert("Data request timed out. Please try later.");
				  } else { 
				    alert("Request resulted in error. Check XML file is retrievable.");
				  }
				});

}

utilidades.prototype.noContextMenu = function (el) {
	if (el.addEventListener)
		el.addEventListener("contextmenu", function(ev){ev.preventDefault()}, true);
	else 
		el.contextmenu = function(){return false;};
}

utilidades.prototype.encodeMyHtml = function(string){
 
  encodedHtml = escape(string);
  encodedHtml = encodedHtml.replace(/\//g,"%2F");
  encodedHtml = encodedHtml.replace(/\?/g,"%3F");
  encodedHtml = encodedHtml.replace(/=/g,"%3D");
  encodedHtml = encodedHtml.replace(/&/g,"%26");
  encodedHtml = encodedHtml.replace(/@/g,"%40");
  
  /*
  if (parseFloat(navigator.appVersion.split('MSIE')[1]) > 6) { 
		// IE 7, mozilla, safari, opera 9
	  encodedHtml = encodedHtml.replace(/ñ/g,"%F1");
	  encodedHtml = encodedHtml.replace(/Ñ/g,"%D1");
	  encodedHtml = encodedHtml.replace(/á/g,"%E1");
	  encodedHtml = encodedHtml.replace(/é/g,"%E9");
	  encodedHtml = encodedHtml.replace(/í/g,"%ED");
	  encodedHtml = encodedHtml.replace(/ó/g,"%F3");
	  encodedHtml = encodedHtml.replace(/ú/g,"%FA");
	  encodedHtml = encodedHtml.replace(/Á/g,"%C1");
	  encodedHtml = encodedHtml.replace(/É/g,"%C9");
	  encodedHtml = encodedHtml.replace(/Í/g,"%CD");
	  encodedHtml = encodedHtml.replace(/Ó/g,"%D3");
	  encodedHtml = encodedHtml.replace(/Ú/g,"%DA");
	  encodedHtml = encodedHtml.replace(/ü/g,"%FC");
	  encodedHtml = encodedHtml.replace(/Ü/g,"%DC");
  }
  */
  return encodedHtml;
};

utilidades.prototype.reseteaRutas = function(){
	
	if (gdir.getNumRoutes() > 0) 
		gdir.clear();
		
	//Eliminamos los 2 marcadores del cambio de ruta
	for (var i=0; i<marcadorCambioRuta.length; i++) {
		map.removeOverlay(marcadorCambioRuta[i]);
	}
	map.closeInfoWindow();
	
	document.getElementById("toAddress").value = document.getElementById("fromAddress").value = "Introduzca su Dirección o C.P.";
	document.getElementById("consultaCliente").value = "Introduzca su Dirección o Código Postal";
	document.getElementById("directions").innerHTML = "";
	
};			    

utilidades.prototype.eMail = function(emailDestino,emailOrigen,nombre,telefono,asunto,message) {//alert("php/email.php?destinatarioEmail="+emailDestino+"&emisorEmail="+emailOrigen+"&nombre="+nombre+"&telefono="+telefono+"&subject="+asunto+"&message="+message);
	GDownloadUrl("php/email.php?destinatarioEmail="+emailDestino+"&emisorEmail="+emailOrigen+"&nombre="+nombre+"&telefono="+telefono+"&subject="+asunto+"&message="+message, function(data, responseCode) {
		if(responseCode == 200) { 
			 if(resizeObjeto){//Cerramos la ventana de envio de e-mail
		   	jAlertMuestraOcultaObjeto(resizeObjeto, false);
		   	jAlert("Mensaje enviado correctamente.", "e-Mail");	
		   } else
			 	jAlert("Mensaje enviado correctamente.", "e-Mail");	
		} else if(responseCode == -1) {
		    jAlert("Tiempo de espera agotado, inténtelo más tarde.", "Error");
		} else { 
				jAlert("Error inesperado.", "Error");
		}
	});
};

utilidades.prototype.checkEmail = function (emailDestino,emailOrigen,nombre,telefono,asunto,message, condicion) {
	
	if(!condicion && emailDestino == null){
		jAlert("Debe aceptar la Pol&iacute;tica de Privacidad","Politica de Privacidad");
		return;
	}
	
	if (condicion)
		asunto = 'Solicitud de Informacion';
	
	//alert("Destinatario: " + emailDestino+ " " + emailOrigen+ " " + nombre+ " " + telefono+ " " + asunto+ " " + message+ " " +  condicion);
	
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	if (emailDestino == null){ //E-mail pestana ayudanos a mejorar
		emailDestino = 'grupogali@grupogali.com,guzman.rejon@radmas.com';
		
		//subject = 'Mejora en el Visor ' + firma + ' Propuesta Por: ' + subject;
		
		if (!filter.test(emailOrigen)) {
			jAlert("Introduce tu dirección de correo correctamente", "e-Mail Incorrecto", "#emailAyudanos");
			return false;
		}
		
	}	else { //E-mail recomendando una tienda
		var emailDestinoCheck = emailDestino.split(',');
		for (var i = 0; i < emailDestinoCheck.length; i++) {
			if (!filter.test(emailDestinoCheck[i])) {
				jAlert("Una o más direcciones de correo son INCORRECTAS", "e-Mail Incorrecto", "#destinatarioEmail");
				return false;
			}
		}
		if (!filter.test(emailOrigen)) {
			jAlert("Introduce una dirección de correo origen válida", "e-Mail Incorrecto", "#emisorEmail");
			return false;
		}
		if (document.getElementById("mailConCopia") && document.getElementById("mailConCopia").className == 'ventana-activo1')
			emailDestino = emailDestino + "," + emailOrigen;
	}
	
	this.eMail(emailDestino,emailOrigen,nombre,telefono,asunto,message);
};

utilidades.prototype.anadirFavoritos = function() {

 title = "Grupo Gali"; 
 url = window.location;
 
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title);
	}else if(window.opera && window.print) { // Opera Hotlist
		return true; }
};

utilidades.prototype.comparaVectores = function(v1, v2) {
	var iguales = true;
	
	if (v1.length != v2.length)
		iguales = false;
	
	for (var i = 0; i < v1.length; i++) {
		if (v1[i] != v2[i])
			iguales = false;
	}
	return iguales;
}

utilidades.prototype.montarCarrusel = function() {
	
	var imagenes = null;
	var _imgMiniTamano = 110;
	var _src = null;
	
	if (ToolTipInstanceTabWindow.fotos_.length == 0)
		imagenes = new Array();
	else if(!utilidadesOBJ.comparaVectores(ToolTipInstanceTabWindow.fotos_, utilidadesOBJ.fotosCarrusel)){
		imagenes = ToolTipInstanceTabWindow.fotos_;
		utilidadesOBJ.fotosCarrusel = imagenes;
	}else 
		return;
	
	var _ul = document.getElementById("carruselFotos");
	
	//Borramos las fotos anteriores si existen
	_ul.innerHTML = '';
	
	$(_ul).addClass('galleria');
	
	for (var i = 0; i < 3; i++) {
		
		var _imgMini = new Image();
		_imgMini.name = i;
		
		if (!imagenes[i] || imagenes[i].length < 5){
			_src = "images/sinfoto1.jpg";
		}else
			_src = "images/fotos/" + imagenes[i];
			
		_imgMini.className = "thumb";
		 
		jQuery(_imgMini).load(function () {
		
		var _li = document.createElement('li');
		if (this.name==0)
			_li.className = "active";
			
		var w = Math.ceil( this.width / this.height * _imgMiniTamano );
		var h = Math.ceil( this.height / this.width * _imgMiniTamano );
					
		//alert("imagenes.length: " + imagenes.length + " N imagen: " + i + " Ruta: " + imagenes[i] + " " + this.width);
		
		if (_src != "images/sinfoto1.jpg") {
		if (w < h) {
			$(this).css({ height: 'auto', width: _imgMiniTamano, marginTop: -(h-_imgMiniTamano)/2 });
		} else {
			$(this).css({ width: 'auto', height: _imgMiniTamano, marginLeft: -(w-_imgMiniTamano)/2 });
		}
		}
		_li.appendChild(this);
		
		var _div = document.createElement('div');
		
		_div.className = 'fondoCarrusel';
		_div.style.backgroundImage= 'url(../images/Tien21/v-cabecera-fondo.png)';
		_div.style.backgroundRepeat= 'no-repeat';
    _div.style.backgroundPosition= 'center center'; 

		var _imgBig = document.createElement('img');
		_imgBig.style.marginLeft = 'auto';
		_imgBig.style.marginRight = 'auto';
		_imgBig.style.position = 'relative';
		_imgBig.src= this.src;  
	 /*
		if(parseInt(_imgBig.height) < 300){
			_imgBig.style.top = '50%'; 
		}
		*/
		_div.appendChild(_imgBig);
		
		_li.appendChild(_div);
		
		_ul.appendChild(_li);
		
		$(this).click(function(){
			$('#carruselFotos .active').removeClass('active');
			this.parentNode.className = 'active';
			//document.getElementById("VentanaWebbodyObj").firstChild.style.height = '1000px';
		});
		
		//Para la Patata de IE6
		if (!window.XMLHttpRequest) {
			$(this).mouseover(function(){
				if (this.parentNode.className == 'active')
					return;
				$(this).addClass('hover');
			});
			$(this).mouseout(function(){
				if (this.parentNode.className == 'active')
					return;
				$(this).removeClass('hover');
			});
		}
		}).error(function () {
				
				// Error handling
			  this.parentNode.html('<span class="error" style="color:red">Error en la carga de la imagen: '+_src+'</span>');
			
		}).attr('src', _src);
	}
	
};

utilidades.prototype.polPrivacidad = function() {
	windowTabsToolTip.headerButton1.onclick();
	windowPolPriv.Agrandar(windowPolPriv, "polPrivacidad");
	$("#ventanaPolPriv").fadeIn("fast");
	ajaxpage('polSeguridad.html', 'politicaPrivacidad');
	document.getElementById('politicaPrivacidad').style.display='block';
}

function ajaxpage(url, containerid){
	var page_request = false
	
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}	else
		return false
		
		page_request.onreadystatechange=function(){
			loadpage(page_request, containerid)
		}
		page_request.open('GET', url, true)
		page_request.send(null)
}

function loadpage(page_request, containerid){
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
		document.getElementById(containerid).innerHTML=page_request.responseText
}

