//API NDC para controlar el map de negocios del caribe.
//variable definition 

var centerLatitude = -66.1376953125;
var centerLongitude = 18.310203344724197;
var startZoom = 10;
var mapList = ["maps", "satellite", "hybrid"];
var map;
var classRowResult = 1;
var classRow = 1;
var oState = {mapType: "map", clickType: "position"};


var oDataBusiness = new Object; 
oDataBusiness.aDataHolder = [];
oDataBusiness.aDataTitle = [];


var deselectCurrentBusiness = function(){}; 
var deselectCurrentList 	= function(){}; 
var deleteListSearch        = function(){};

function stringSearch()
{
	if(location.search && location.search != "")
	{
		searchResults(location.search);
	}
}

function init_map()
{
   $("#info_panel").hide();
   if(GBrowserIsCompatible())

   {

        map = new GMap2(document.getElementById("map"));
        map.addControl(new GSmallMapControl());
        var location = new GLatLng(centerLongitude, centerLatitude ); 
		map.setCenter(location, startZoom);		
		GEvent.addListener(map, 'click', mapclick);		
		
		stringSearch();
		
   }
     
}


function unload_map_api()
{

    GUnload();

}

function mapclick(overlay, latlng)
{

	var latitude = latlng.lat();
	var longitude = latlng.lng();
	
	switch (oState.clickType){
		
		case "position" :
			map.openInfoWindow(latlng, document.createTextNode("Lat: " + latitude + ", Lng: " + longitude ));
			break;
			
		case "satellite" :
			map.showMapBlowup(new GLatLng(latitude, longitude), 3, G_SATELLITE_MAP);
			break;
			
			
	}
			
}
function refreshCssSearchList()
{
	var thisClass;
	var nodes = document.getElementById("searchList").getElementsByTagName("div");
	
	if(nodes.length > 0)
	{
		for(i = 0; nodes.length; i++)
		{
			thisClass = (classRowResult == 1)?'even40':'odd40';
			nodes[i].className = thisClass;
			nodes[i]["class"] = thisClass;
			classRowResult = (classRowResult == 1)? 2:1;			
		}
		
		node[0].className = 'curList';
		deselectCurrentList = function(){node[0].className = nodes[0]["class"];};
	}			
	
}

//esta funcion se ejecuta cuando se borran todos los resultados
function initializeSearch(name)
{
	var myObj = oDataBusiness.aDataHolder[oDataBusiness.aDataHolder.length -1];
	var pos = oDataBusiness.aDataHolder.length -1;
	var listResult = document.createElement('div');	
	var thisClass = (classRowResult == 1)?'even40':'odd40';
	
	var closeButtom = document.createElement('img');
	closeButtom.src = '/assets/images/close.gif';
	closeButtom.className = 'close';
	closeButtom.title = 'Eliminar resultado';
		
	listResult.className = thisClass;
	classRowResult = (classRowResult == 1)? 2:1;
	listResult.title = 'Criterio de búsqueda: ' + document.getElementById('input_string').value;
	listResult["class"] = thisClass;
	
	var focusList = function(){
									map.closeInfoWindow();
									deselectCurrentList();
									listResult.className = 'curList';
									deselectCurrentList = function() {listResult.className = listResult["class"];};
									deleteListSearch();
									graphicPoint(pos);
									deleteListSearch =  function() {var obj = oDataBusiness.aDataHolder[pos];
																		for(id in obj)
																		{
																			if(obj[id].hide){
																			obj[id].hide();
																			}
																		}
	
																	}
									return false;
									
									
								}
	var deleteList = function(){
									var itemNode;
									listResult.parentNode.removeChild(listResult);									
									if(document.getElementById('searchList').getElementsByTagName('div').length > 0){
										itemNode = document.getElementById('searchList').firstChild;									
										itemNode.onclick();
										refreshCssSearchList();
																				
									}
									
									if(document.getElementById('searchList').getElementsByTagName('div').length == 0)
									{
										oDataBusiness.aDataHolder = [];
										oDataBusiness.aDataTitle = [];
										map.closeInfoWindow();
										map.clearOverlays();
										$("#info_panel").hide();
									}																																				
									return false;
									
		
								}
								
	listResult.onclick = focusList;
	
	closeButtom.onclick = deleteList;
	
	var numero = oDataBusiness.aDataTitle.length + 1;
	
	oDataBusiness.aDataTitle.push(name +' '+ numero.toString());
	listResult.innerHTML = '<p><strong>' + (oDataBusiness.aDataTitle[oDataBusiness.aDataTitle.length -1]) +'</strong></p>';
	listResult.appendChild(closeButtom);
	
	if(document.getElementById('searchList').getElementsByTagName('div').length > 0)
	{
		var itemRef = document.getElementById('searchList').firstChild;
		document.getElementById('searchList').insertBefore(listResult, itemRef);
		
	}else{
		document.getElementById('searchList').appendChild(listResult);
	}
	
	listResult.onclick();	
	graphicPoint(pos);
	
}

function initializePoint(pointData)
{
			
			var point = new GPoint(parseFloat(pointData.latitud[0]),parseFloat(pointData.longitud[0]));
			var marker = new GMarker(point, iconBusiness);
			var visible = false;
	
			
			var listItem = document.createElement('div');
			var thisClass = (classRow == 1)?'even':'odd';
			listItem.className = thisClass;
			classRow = (classRow == 1)? 2:1;	
					
			var html = '<div><img class="img_logo" src="' + pointData.logo +'" />' + 
                			 '<p class="name_biz">' + pointData.nombre + '</p>' +
                			 '<p class="description_biz">' + pointData.descripcion +'</p>';
															  
			html = (pointData.id)? html + '<p class="description_biz"><a href="http://bizface.negociosdelcaribe.com/?biz_id=' + pointData.id +'" target="_blank" >ver más</a></p>' : html;
			
			html+= '</div>';
			
			pointData.show = function() {
											if (!visible) {
 													document.getElementById('resultSearchList').appendChild(listItem);
 													map.addOverlay(marker);
 													visible = true;
 											}
 										}
 			pointData.hide = function() {
 											if (visible) {
 													document.getElementById('resultSearchList').removeChild(listItem);
 													map.removeOverlay(marker);
 													visible = false;
 											}
 										}
										
									
			
			listItem.innerHTML = '<img class="img_logo" src="' + pointData.logo +'" />' + 
                		 		 '<p class="name_biz">' + pointData.nombre + '</p>' +
                		 		 '<p class="description_biz">' + pointData.descripcion +'</p>';
								 
								 
			var focusPoint = function(){
									deselectCurrentBusiness();
									listItem.className = 'curObject';
									deselectCurrentBusiness = function() {listItem.className = thisClass;};
									marker.openInfoWindowHtml(html);
									map.panTo(point);
									return false;
								}
								
			
	
			listItem.onclick = focusPoint;
			GEvent.addListener(marker, 'click', focusPoint);
			
			pointData.show();				
			

}


function graphicPoint(position)
{
	
	var groupPoint = oDataBusiness.aDataHolder[position];
	deleteListSearch(position);
	for(index = 0; index < groupPoint.length; index++)
	{
		initializePoint(groupPoint[index]);		
	}
}

function searchResults(parameters)
{
	var url;
	if(location.search !=""){
		url = 'http://mapas.negociosdelcaribe.com/test/test.php' + parameters;
	}
	if(document.getElementById("input_string").value != ""){
		url = 'http://mapas.negociosdelcaribe.com/test/test.php?search=' + escape(parameters);
	}
	
	
	var request = GXmlHttp.create();
	request.open('GET',url, true);
	request.onreadystatechange = function() {
  	if (request.readyState == 4) {
		
		var data = [];
		data.push(eval("(" + request.responseText + ")"));
		if(data[0].length > 0){
				oDataBusiness.aDataHolder.push(eval("(" + request.responseText + ")"));		
				initializeSearch("Resultado");
				$("#info_panel").show();
				data = null;
				mensajeOut('','');
		}
		else{
				mensajeOut('Su b&uacute;squeda no arroj&oacute; resultado alguno. Por favor, intente buscar con otras palabras.', 'infoText');
		}
		
		
	}else{
		
				mensajeOut('Cargando datos...', 'infoLoading');
		
	}
	}
	request.send(null);	
}

function changeTypeMap(type)
{
		for(index =0; index < mapList.length; index++)
		{
			var ids = mapList[index];
			var lis = document.getElementById(ids);
			var attribute = lis.getAttribute("id");
			if(attribute == type)
			{
				lis.firstChild.style.background = "url(assets/images/" + attribute +"2.jpg) no-repeat center 2px";
				lis.firstChild.style.backgroundColor = "#FF9900" ;
				lis.firstChild.style.fontWeight = "bold";
			}else{
				lis.firstChild.style.background = "url(assets/images/" + attribute +".jpg) no-repeat center 2px";
				lis.firstChild.style.backgroundColor = "#EFF1F8";
				lis.firstChild.style["fontWeight"] = "normal";
			}
			
		}
		
		switch(type)
		{
			case "maps" :
				map.setMapType(G_NORMAL_MAP);
				break;
			case "satellite":
				map.setMapType(G_SATELLITE_MAP);
				break;
			case "hybrid":
				map.setMapType(G_HYBRID_MAP);
				break;
				
		}	
		
}

function mensajeOut(mText,clase)
{
		var mensajeText = document.getElementById('message');
		mensajeText.innerHTML = mText;
		mensajeText.className = clase;
}

window.onload 	= init_map;
window.onunload = unload_map_api;
