/*
* javier hacer trim en las funciones
*/
//Trim ambas direcciones
String.prototype.trim = function() {
    return this.replace(/^s+|s+$/g,'');
   }
    //Trim izquierda
    String.prototype.ltrim = function() {
    	return this.replace(/^s+/g,'');
    }
    
    //Trim Derecha
    String.prototype.rtrim = function() {
    	return this.replace(/s+$/g,'');
    }


 //ultimo caracter de la cadena que no sea espacio en blanco
 String.prototype.lastChar = function() {
  
  if (this.length > 0){
    return this.charAt(this.length -1);
  } else {
    return '';
  } 
}



  /**
  *
  * añade un tag al textbox
  * 
  * @param item: 		nombre del item
  * @param value:		valor nuevo
  * 
  */
  function add_tag(item, value)
  {
    
    var tagItem = $(item);
    
    var patron = '/' + value + ',/';
    var content = new String(tagItem.value);
   
    if (content.match(value) != value)
    {
        //si no hay nada en el texto a introducir
       	if ((content.lastChar() == ' ') && (content.length > 0))
       	{
       	 tagItem.value +=  value + ', ';	
       	}
        else if ((content.length == 0)  
        		|| (content.trim() == '')
        		|| (content.lastChar() == ','))
        {
        	
            tagItem.value += value + ', ';
        }
        else 
        {
            tagItem.value += ', ' + value + ', ';
        }
    }
  }
  
 /**
  * cambia la visivilidad de un elemento
  * 
  * @param elem : item que queremos cambiar de estado un <div> un <p> .... 
  */ 
 function changeElemView(elemet)
 {
 	try
	{
		var elem = document.getElementById(elemet);
		
		if (elem.style.visibility == 'visible')
		{
			elem.style.visibility = 'hidden';	
		}
		else
		{
			elem.style.visibility = 'visible';
		}
		
	}
	catch(err)
	{
	//Handle errors here
	}
 }
 
 /**
  * oculta un elemento
  * 
  * @param elemt:		id del elemento que queremos ocultar 
  */
 function hideElem(elemet)
 {
 	try
	{
		var elem = document.getElementById(elemet);
		
		elem.style.visibility = 'hidden';	
	}
	catch(err)
	{
	//Handle errors here
	}
 }
 
  /**
  * muestra un elemento
  * 
  * @param elemt:		id del elemento que queremos mostrar
  */
 function showElem(elemet)
 {
 	try
	{
		var elem = document.getElementById(elemet);
		
		elem.style.visibility = 'visible';
	}
	catch(err)
	{
	//Handle errors here
	}
 }
 
 /**
  * devuelve el valor de un item
  * @param elem 
  */
 function getItemValue(elemet)
 {
 	var ret;
 	
 	try
	{
		var elem = document.getElementById(elemet);
		
		ret = elem.value;
		
	}
	catch(err)
	{
	//Handle errors here
	}
	
	return ret;
 }
 

 
 /*
  * 
  */
 function AJAX(){
 	
 }
// respuesta de la peticion
AJAX.prototype._response = null;
/*
 * ejecuta un get
 * @param url: url a la que hacemos la peticion
 */
AJAX.prototype.setGet = function (url){
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	req.open("GET", url, true);
	req.onreadystatechange = update; 
	req.send(null);
}
/*
 * update por defecto
 */
AJAX.prototype.update = function (){
	if (req.readyState == 4) 
	{
		if (req.status == 200) 
		{
			this._response = req.responseText;
		}
	}
}

/**
 * Archivo JavaScript con utilidades comunes
 */

var net = new Object();

net.READY_STATE_UNINITIALIZED=0; 
net.READY_STATE_LOADING=1; 
net.READY_STATE_LOADED=2; 
net.READY_STATE_INTERACTIVE=3; 
net.READY_STATE_COMPLETE=4; 

// ==== Cargador contenidos básico ============================================
// Constructor
net.CargadorContenidos = function(url, funcion, funcionError) {
	this.url = url;
	this.req = null;
	this.onload = funcion;
	this.onerror = (funcionError) ? funcionError : this.defaultError;
	this.cargaContenidoXML(url);
}

net.CargadorContenidos.prototype = { 
	cargaContenidoXML: function(url) {
		if (window.XMLHttpRequest) {
			this.req = new XMLHttpRequest(); 
		} else if (window.ActiveXObject) {
			this.req = new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		
		if(this.req) { 
			try {
				var loader = this; 
				this.req.onreadystatechange = function() { 
					loader.onReadyState.call(loader); 
				} 
				this.req.open('GET', url, true);
				this.req.send(null);
			} catch (err) { 
				this.onerror.call(this);
			} 
		}
	},

	onReadyState: function() {
		var req = this.req; 
		var ready = req.readyState; 
		if (ready == net.READY_STATE_COMPLETE) { 
			var httpStatus = req.status; 
			if(httpStatus == 200 || httpStatus == 0) { 
				this.onload.call(this);
			}
			else { 
				this.onerror.call(this);
			} 
		} 
	}, 

	defaultError: function() { 
		alert("Se ha producido un error al obtener los datos." 
				+ "\n\nreadyState:" + this.req.readyState 
				+ "\nstatus: " + this.req.status 
				+ "\nheaders: " + this.req.getAllResponseHeaders()); 
	} 
}

// ==== Cargador contenidos completo ==========================================
// Constructor
net.CargadorContenidosCompleto = function(url, funcion, funcionError, metodo, parametros, contentType, sincrona) {
	this.url = url;
	this.req = null;
	this.onload = funcion;
	this.onerror = (funcionError) ? funcionError : this.defaultError;
	this.cargaContenidoXML(url, metodo, parametros, contentType, sincrona);
}

net.CargadorContenidosCompleto.prototype = { 
	cargaContenidoXML: function(url, metodo, parametros, contentType, sincrona) {
		if (window.XMLHttpRequest) {
			this.req = new XMLHttpRequest(); 
		} else if (window.ActiveXObject) {
			this.req = new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		
		if(this.req) { 
			try {
				var loader = this;
				this.req.onreadystatechange = function() { 
					loader.onReadyState.call(loader); 
				} 
				
				this.req.open(metodo, url, (sincrona===false)?false:true);
				
				if(contentType) {
					this.req.setRequestHeader("Content-Type", contentType);
				}
				this.req.send(parametros);
			} catch (err) { 
				this.onerror.call(this);
			} 
		}
	},

	onReadyState: function() {
		var req = this.req; 
		var ready = req.readyState; 
		if (ready == net.READY_STATE_COMPLETE) { 
			var httpStatus = req.status; 
			if(httpStatus == 200 || httpStatus == 0) { 
				this.onload.call(this);
			}
			else { 
				this.onerror.call(this);
			} 
		} 
	}, 

	defaultError: function() { 
	//	alert("Se ha producido un error al obtener los datos:" 
	//			+ "\n\nreadyState:" + this.req.readyState 
	//			+ "\nstatus: " + this.req.status 
	//			+ "\nheaders: " + this.req.getAllResponseHeaders()); 
	} 
}

// ==== Utilidad para eventos =================================================
var EventUtil = new Object();

EventUtil.addEventHandler = function(elTarget, tipoEvento, funcion) {
	if(elTarget.addEventListener) { // navegadores DOM
		elTarget.addEventListener(tipoEvento, funcion, false);
	} else if(elTarget.attachEvent) { // Internet Explorer
		elTarget.attachEvent("on"+tipoEvento, funcion);
	} else { // resto de navegadores
		elTarget["on"+tipoEvento] = funcion;
	}
};

EventUtil.removeEventHandler = function(elTarget, tipoEvento, funcion) {
	if(elTarget.removeEventListener) { // navegadores DOM
		elTarget.removeEventListener(tipoEvento, funcion, false);
	} else if(elTarget.detachEvent) { // Internet Explorer
			elTarget.detachEvent("on"+tipoEvento, funcion);
	} else { // resto de navegadores
			elTarget["on"+tipoEvento] = null;
	}
};

EventUtil.getEvent = function() {
	if(window.event) { // Internet Explorer
		return this.formatEvent(window.event);
	} else { // navegadores DOM
		return EventUtil.getEvent.caller.arguments[0];
	}
};

EventUtil.formatEvent = function(elEvento) {

		elEvento.charCode = (elEvento.type=="keypress") ? elEvento.keyCode : 0;
		elEvento.eventPhase = 2;
		elEvento.isChar = (elEvento.charCode > 0);
		elEvento.pageX = elEvento.clientX + document.body.scrollLeft;
		elEvento.pageY = elEvento.clientY + document.body.scrollTop;
		elEvento.preventDefault = function() {
			this.returnValue = false;
		};
		if(elEvento.type == "mouseout") {
			elEvento.relatedTarget = elEvento.toElement;
		} else if(elEvento.type == "mouseover") {
			elEvento.relatedTarget = elEvento.fromElement
		}
		elEvento.stopPropagation = function() {
			this.cancelBuble = true;
		};
		elEvento.target = elEvento.srcElement;
		elEvento.time = (new Date).getTime();
		
	elEvento.isAlphanumeric = (elEvento.keyCode >= 48 && elEvento.keyCode <= 57 ) ||  ( elEvento.keyCode >= 65 && elEvento.keyCode <= 90 );
	return elEvento;
}




function googlemap_big ()
{
	var box = document.getElementById('googlemap');
	var res = box.offsetHeight + 50;
	box.style.height = res+'px';
}

function googlemap_small ()
{
	var box = document.getElementById('googlemap');
	var res = box.offsetHeight - 50;
	if (res <= 290) res = 290;
	box.style.height = res+'px';
}

function showDiv (div_name)
{
	eO = document.getElementById(div_name).style;
	eO.visibility = "visible";
	eO.display = "block";
}

function hiddenDiv (div_name)
{
	eO = document.getElementById(div_name).style;
	eO.visibility = "hidden";
	eO.display = "none";
}
/*
* cambia el estado de un elemento de visible a no visible
* @param item_id: id del elmento que queremos cambiar 
*/
function changeState(item_id)
{	
	var itemElem = $(item_id);
	
	elemStyle = itemElem.style;
	if (elemStyle.visibility == "visible"){
		elemStyle.visibility = "hidden"; 
	}
	else {
		elemStyle.visibility = "visible";			
	}		
}



//var ajax = new AJAX();


function showMutualFavs()
{
	Effect.Fade('noMutualFavs');
	setTimeout ("Effect.Appear('mutualFavs', { duration: 2.0 })", 830);
}

function showNoMutualFavs()
{
	Effect.Fade('mutualFavs');
	setTimeout ("Effect.Appear('noMutualFavs', { duration: 2.0 })", 830);
}



// SBUX STORES----------------------------------------

function v2vSbuxStoresVisibility()
{
	if (document.sbuxStoresOnMapForm.sbuxStoresOnMapCheck.checked == false)
	{
		v2vRemoveSbuxStoresFromMap();
	}
	else
	{
		v2vSbuxStores(0,0,0);
	}
}



function v2vRemoveSbuxStoresFromMap()
{
	for (var i=0; i< sbuxMarker.length; i++) 
	{
		map.removeOverlay(sbuxMarker[i]);
	}
}

function v2vSbuxStores(x, y, zoomLevel) 
{
	var url = "v2v/ajax-SbuxStores.php?x=" + x + "&y=" + y + "&zoomLevel=" + zoomLevel;
	
	if (window.XMLHttpRequest) 
	{
		req1 = new XMLHttpRequest();
	} 
	else if (window.ActiveXObject) 
	{
		req1 = new ActiveXObject("Microsoft.XMLHTTP");
	}

	req1.open("GET", url, true);
	req1.onreadystatechange = v2vSbuxStoresCallback;
	req1.send(null);
}

function v2vSbuxStoresCallback() 
{
	if ((req1.readyState == 4) && (req1.status == 200))
	{
		v2vSbuxStoresAct();
	}
}
		
function v2vSbuxStoresAct() 
{	
	//map.clearOverlays();
	var items = req1.responseXML.getElementsByTagName("item");
	if (items.length > 0) 
	{			
		sbuxMarker = new Array(items.length);
		for (var i=0; i<items.length; i++) 
		{		
			var node = items[i];
			var StoreName = node.getElementsByTagName("StoreName")[0].firstChild.nodeValue;
			var Latitude = node.getElementsByTagName("Latitude")[0].firstChild.nodeValue;
			var Longitude = node.getElementsByTagName("Longitude")[0].firstChild.nodeValue;
			var html1Title = node.getElementsByTagName("html1Title")[0].firstChild.nodeValue;
			var htmldata1 = node.getElementsByTagName("htmldata1")[0].firstChild.nodeValue;
			var html2Title = node.getElementsByTagName("html2Title")[0].firstChild.nodeValue;
			var htmldata2 = node.getElementsByTagName("htmldata2")[0].firstChild.nodeValue;
			var markercolor = 'green';
			sbuxMarker[i] = v2vCreateMarkerTabs(StoreName, Latitude, Longitude, htmldata1, htmldata2, markercolor, html1Title, html2Title);
			map.addOverlay(sbuxMarker[i]);			
		}				
	}	
}

function v2vCreateMarkerTabs(storename, latitude, longitude, html1, html2, markercolor, html1Title, html2Title) 
{
        var icon = new GIcon();
        icon.image = "images_v2v/marker_" + markercolor + ".png";
        icon.shadow = "images_v2v/marker_shadow.png";
        icon.iconSize = new GSize(12, 20);
        icon.shadowSize = new GSize(22, 20);
        icon.iconAnchor = new GPoint(6, 20);
        icon.infoWindowAnchor = new GPoint(5, 1);
	var posn = new GLatLng(latitude, longitude);
	var marker = new GMarker(posn, icon);

	GEvent.addListener(marker, "click", function() 
	{
		marker.openInfoWindowTabsHtml([new GInfoWindowTab(html1Title, html1), new GInfoWindowTab(html2Title, html2)]);
	});
	return marker;
}




function showTip(me)
{
    eO = document.getElementById(me).style;
    eO.visibility = "visible";
    eO.display = "block";
}
function hideTip(me)
{
    eO = document.getElementById(me).style;
    eO.visibility = "hidden";
    eO.display = "none";
}
