var callBackArr = new Array();
var mapNumber = 0;
var childMapNumber = -1;
var mapCreated = false;
var currentChild;
var mapIndex = 0;
var childIndex = 0;
var arrMap;
var map;
var provinciaCorrente;
var provinciaPrecedente;

$(document).ready(function() { });

function initializeMap()
{
	arrMap = $(".googlemap");
	if(arrMap.length > 0)
	{
		mapNumber = arrMap.length;
		childMapNumber = $(arrMap[0]).children('span').length;
		mapIndex = 0;
		childIndex = 0;
		createEmptyMap();
	}
}

function mapSearch()
{
	if(jQuery.trim($("#mapsearch").val()) == '') return;
	$(".google-map-content-box span").remove();
	var dataString = "provincia="+$("#mapsearch").val();
	provincia = $("#mapsearch").val();
	jQuery.ajax({
	   type: "POST",
	   url: "procedure/checkProvincia.php",
	   data: dataString,
	   cache: false,
	   async: false,
	   success: function(xml)
	   {
		   if(jQuery(xml).find('address').text() == "not found")
		   { 
			   map.clearOverlays();
			   openGenericAlert('genericAlert', 'Attenzione!', 'Non sono presenti<br>punti vendita nella<br>provincia cercata', 'OK');
		   }
		   else
		   {
			   jQuery(xml).find('address').each(function()
			   {
				  /* 
				  var info = $(this).attr("info");
				  var tel = $(this).attr("tel");
				  var loc = $(this).attr("loc");
				  var cliente = $(this).attr("cliente");
				  var arrAppoggio = $(this).text().split(",");
				  var lat = arrAppoggio[0];
				  var long = arrAppoggio[1];
				  */
				  var info = $(this).find("info").text();
				  var tel = $(this).find("tel").text();
				  var loc = $(this).find("loc").text();
				  var cliente = $(this).find("cliente").text();
				  var arrAppoggio = $(this).attr("latlong").split(",");
				  var lat = arrAppoggio[0];
				  var long = arrAppoggio[1];
				  
				  $(".google-map-content-box").children(".googlemap").append("<span cliente='"+cliente+"' loc='"+loc+"' tel='"+tel+"' info='"+info+"' lat='"+lat+"' long='"+long+"' link='' icon='img/maker_map.png'></span>");
				});
			   add(provincia);
		   }
	   }
	});
}

//funzioni utilizzate per la login nell'area riservata
function onClickMapSearch(e)
{
	var keycode;
	if (window.event) 
		keycode = window.event.keyCode;
	else if (e) 
		keycode = e.which;
	else 
		return true;

	if (keycode == 13)
		mapSearch();
	else
		return true;
}
function add(provincia)
{
	provinciaCorrente = provincia;
	map.clearOverlays();
	var ll = new GLatLng(40.9284934, 12.1974462);
	map.setCenter(ll, 6);
	$('.infomap').remove();
	arrMap = $(".googlemap");
	if(arrMap.length > 0)
	{
		mapNumber = arrMap.length;
		childMapNumber = $(arrMap[0]).children('span').length;
		mapIndex = 0;
		childIndex = 0;
		if(childMapNumber > 0)
		{
			childIndex=0;
			createSingleMap(mapIndex, childIndex);
			provinciaPrecedente = provincia;
		}
	}
}

function createEmptyMap()
{
	$(arrMap[mapIndex]).parents(".google-map-content").css("display", "block").css("visibility", "hidden");
	
	var ll = new GLatLng(40.9284934, 12.1974462);
	var childMap = $(arrMap[mapIndex]).children('div');
	var tmpMap = new GMap2(childMap[0]);
	
	if($(arrMap[mapIndex]).attr('zoom') != null && $(arrMap[mapIndex]).attr('zoom') != "undefined") tmpMap.setCenter(ll, parseInt($(arrMap[mapIndex]).attr('zoom')));
	else tmpMap.setCenter(ll, 10);
	
	var addControl = true; // true per abilitare i controlli
	if($(arrMap[mapIndex]).attr('control') != null && $(arrMap[mapIndex]).attr('control') != "undefined" && parseInt($(arrMap[mapIndex]).attr('control'), 10) == 0) addControl = false;
	if(addControl) 
	{
		var topRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(40, 220));
		tmpMap.addControl(new DomusZoom(), topRight);		
	}
			
	tmpMap.disableScrollWheelZoom();
	tmpMap.disableDoubleClickZoom();	
	map = tmpMap;
	mapCreated = true;
	
	$(arrMap[mapIndex]).parents(".google-map-content").css("display", "none").css("visibility", "visible");
}

function createSingleMap(mapInd, childInd)
{
	if(childIndex == childMapNumber)
	{
		for(var i = (childMapNumber-1); i >= 0; i--) 
			$(arrMap[mapIndex]).children('span:eq('+i+')').remove();
		$(arrMap[mapIndex]).css("visibility", "visible");
		mapIndex = mapIndex	+ 1;
		if(mapIndex == mapNumber) return;
		mapCreated = false;
		childIndex = 0;
		childMapNumber = $(arrMap[mapIndex]).children('span').length;
		if(childMapNumber == 0) 
		{
			return;
		}
	}
	
	currentChild = $(arrMap[mapIndex]).children('span:eq('+childIndex+')');
	
	var isNetwork = 0;
	if($(currentChild).attr("isnetwork") != null && $(currentChild).attr("isnetwork") != "undefined") isNetwork = $(currentChild).attr("isnetwork");
	
	var defaultIconType = 0;
	if($(currentChild).attr("defaulticontype") != null && $(currentChild).attr("defaulticontype") != "undefined") defaultIconType = $(currentChild).attr("defaulticontype");
	
	var icon = null;
	if($(currentChild).attr("icon") != null && $(currentChild).attr("icon") != "undefined") icon = $(currentChild).attr("icon");
	
	var iconLink = null;
	if($(currentChild).attr("link") != null && $(currentChild).attr("link") != "undefined") iconLink = $(currentChild).attr("link");
	
	var titleLink = null;
	if($(currentChild).attr("title") != null && $(currentChild).attr("title") != "undefined") titleLink = $(currentChild).attr("title");
	
	if ($(currentChild).attr("lat") != null && $(currentChild).attr("lat") != "" && $(currentChild).attr("lat") != undefined && $(currentChild).attr("lat") != "undefined")
	{
		//alert("b" + $(currentChild).attr("lat") + "||" + $(currentChild).attr("long"))
		createMarker(arrMap[mapIndex], parseFloat($(currentChild).attr("lat")), parseFloat($(currentChild).attr("long")), icon, iconLink, titleLink, defaultIconType, isNetwork, $(currentChild).attr("info"), $(currentChild).attr("cliente"), $(currentChild).attr("loc"), $(currentChild).attr("tel"));
	}else if ($(currentChild).html() != null && $(currentChild).html() != "" && $(currentChild).html() != undefined && $(currentChild).html() != "undefined")
	{				
		var addr = $.trim($(currentChild).html());
		var clientGeocoder = new GClientGeocoder();
		callBackArr.push({myDiv: currentChild, myAddr: addr, ico: icon, lnk: iconLink, title: titleLink, defIcon: defaultIconType, isNet: isNetwork});
		clientGeocoder.getLocations(addr , checkLocationSearch);
	}else
	{
		childIndex = childIndex + 1;
		createSingleMap(mapIndex, childIndex);
	}
}

function checkLocationSearch(response)
{
	var status = response['Status'];
	if (status['code'] == 200)
	{
		var placemark = new Array();
		placemark = response['Placemark'];
		var pl = placemark[0];
		var addrDet = pl['address'];
		var divObj = getDivObjMap(addrDet);
		//alert(addrDet);
		if(divObj != null)
		{
			createMarker(divObj.myDiv, pl.Point.coordinates[1], pl.Point.coordinates[0], divObj.ico, divObj.lnk, divObj.title, divObj.defIcon, divObj.isNet);
		}else
		{
			childIndex = childIndex + 1;
			createSingleMap(mapIndex, childIndex);
		}
	}else
	{
		//@@@ indirizzo non trovato!
	}
}

function getDivObjMap(addr)
{
	for(var i = 0; i < callBackArr.length; i++)
	{
		//alert(jQuery.trim(callBackArr[i].myAddr) + "||" + jQuery.trim(addr).toUpperCase())
		if(jQuery.trim(callBackArr[i].myAddr) == jQuery.trim(addr).toUpperCase())
		 return callBackArr[i];
			
	}
	return null;
}

// We define the function first
function DomusZoom() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
DomusZoom.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
DomusZoom.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var zoomInDiv = document.createElement("a");
  zoomInDiv.setAttribute('id', 'domusZoomIn');
  container.appendChild(zoomInDiv);
  GEvent.addDomListener(zoomInDiv, "click", function() {
    map.zoomIn();
  });

  //separatori
  var zoomStep;
  for(var s = 0; s < 6; s++)
  {
	  zoomStep = document.createElement("div");
	  zoomStep.setAttribute('id', 'domusStep_'+s) 
	  container.appendChild(zoomStep);
	  jQuery("#domusStep_"+s).addClass('domusStep');
  }
  
  var zoomOutDiv = document.createElement("a");
  zoomOutDiv.setAttribute('id', 'domusZoomOut') 
  container.appendChild(zoomOutDiv);
  GEvent.addDomListener(zoomOutDiv, "click", function() {
    map.zoomOut();
  });

  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
DomusZoom.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

function createMarker(pDivObj, pLat, pLong, pIcon, pLink, pTitle, pDefIcon, pIsNetwork, pInfo, pcliente, ploc, ptel)
{
	var ll = new GLatLng(parseFloat(pLat), parseFloat(pLong));
	
	if(!mapCreated)
	{
		var childMap = $(arrMap[mapIndex]).children('div');
		map = new GMap2(childMap[0]);
		
		if($(arrMap[mapIndex]).attr('zoom') != null && $(arrMap[mapIndex]).attr('zoom') != "undefined") map.setCenter(ll, parseInt($(arrMap[mapIndex]).attr('zoom')));
		else map.setCenter(ll, 10);
		
		var addControl = true;
		if($(arrMap[mapIndex]).attr('control') != null && $(arrMap[mapIndex]).attr('control') != "undefined" && $(arrMap[mapIndex]).attr('control') == "0") addControl = false;
		if(addControl) map.addControl(new DomusZoom());
				
		map.disableScrollWheelZoom();
		map.disableDoubleClickZoom();	
		mapCreated = true;
	}
	var ll = new GLatLng(pLat, pLong);
	
	var icon = new GIcon();

	var label = null;
	
	if(pIcon == null)
	{
		//ICONA DI DEFAULT
		if(pIsNetwork == 0)
		{
			if(pDefIcon == 0){icon.image = "/domusweb/asset/img/gmapplaceholder.gif";}
			else{icon.image = "/domusweb/asset/img/gmapplaceholder_grey.gif";}
			label = new ELabel(new GLatLng(pLat, pLong), '<div>'+pTitle+'</div>', "iconLabelText", new GSize(6, -28),100,true);
		}else
		{
			if(pDefIcon == 0) icon.image = "/domusweb/asset/img/gmapplaceholdernetwork.gif";
			else icon.image = "/domusweb/asset/img/gmapplaceholder_greynetwork.gif";
			label = new ELabel(new GLatLng(pLat, pLong), '<div>'+pTitle+'</div>', "iconLabelText", new GSize(-8, -28),100,true);
		}
		//icon.iconSize = new GSize(55, 59);
		icon.iconSize = new GSize(160, 64);
		//icon.iconAnchor = new GPoint(27, 34);
		icon.iconAnchor = new GPoint(18, 65);
	}else
	{
		var iconType = 0;
		if($(arrMap[mapIndex]).attr('icontype') != null && $(arrMap[mapIndex]).attr('icontype') != "undefined") iconType = parseInt($(arrMap[mapIndex]).attr('icontype'));
		icon.image = pIcon;
		if(iconType == 0)
		{
			 icon.iconSize = new GSize(70, 32);
			 icon.iconAnchor = new GPoint(35, 34);
		}else if(iconType == 1) 
		{
			icon.iconSize = new GSize(50, 60);
			//icon.shadowSize = new GSize(60, 53);
			icon.iconAnchor = new GPoint(27, 18);
			//icon.shadow = "/domusweb/asset/img/bkg_icon_map_article.png";
			icon.shadowSize = new GSize(50, 60);
		}
	}
	//icon.iconAnchor = new GPoint(3, 57);
	var marker;
	if(pLink != null)
	{
		marker = new GMarker(ll, icon, false);
		marker.mapIndex = mapIndex;
		marker.markerIndex = childIndex;
		GEvent.addListener(marker, "click", function()
		{
			//window.location.href = pLink;
		});
		
		GEvent.addListener(marker, "mouseover", function() 
		{
		  var zind = GOverlay.getZIndex(marker.getPoint().lat());
			if(provinciaCorrente != provinciaPrecedente)
			{
				marker.mapIndex = 0;
				childIndex = 0;
			}		  
			
			var topMaker = $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("img:eq("+(marker.markerIndex)+")").offset().top;
			var leftMaker = $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("img:eq("+(marker.markerIndex)+")").offset().left;
			var rightMaker = $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("img:eq("+(marker.markerIndex)+")").offset().right;
			
			var widthMaker = $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("img:eq("+(marker.markerIndex)+")").css('width');
			var heightMaker = parseInt($(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("img:eq("+(marker.markerIndex)+")").css('height').replace("px",""));
			
			var heightInfo =  parseInt($(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("#info_"+marker.markerIndex).css('height').replace("px",""));
			
			var topWrapper = $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("img:eq("+(marker.markerIndex)+")").parent().parent().offset().top;
			var leftWrapper = $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("img:eq("+(marker.markerIndex)+")").parent().parent().offset().left;
		  //alert(leftWrapper)
		  $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("img:eq("+(marker.markerIndex-1)+")").css('z-index', 100000000);
		  
		  $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("#info_"+marker.markerIndex).css('top', topMaker-topWrapper-heightInfo-15+'px');
		  $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("#info_"+marker.markerIndex).css('left', leftMaker-leftWrapper+'px');
		  $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("#info_"+marker.markerIndex).css('right', rightMaker+'px');
		  
		  $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("#info_"+marker.markerIndex).css('display', 'inline');
		  $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("#info_"+marker.markerIndex).children().css('display', 'inline');
		  $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("#info_"+marker.markerIndex).children().children().css('display', 'inline');
		});
		GEvent.addListener(marker, "mouseout", function() 
		{
		  var zind = GOverlay.getZIndex(marker.getPoint().lat());
		  $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+marker.markerIndex).css('z-index', zind);
		  $(arrMap[marker.mapIndex]).children("div").children("div").children("div").children("div").children("#info_"+marker.markerIndex).css('display', 'none');
		});
	}else marker = new GMarker(ll, icon, true);

	map.addOverlay(marker);

	/* Verifico che sia necessario inserire la label (solo per le icon map di default) */
	if(label != null)
		map.addOverlay(label);
	
	if(iconType == 1) 
	{
		//alert($(arrMap[mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+childIndex).attr("id"))
		if(pTitle != null) $(arrMap[mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+childIndex).attr('title', pTitle);
		
		$(arrMap[mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+childIndex).css('display', 'inline');
		$(arrMap[mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+childIndex).css('margin-left', '3px');
		$(arrMap[mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+childIndex).css('margin-top', '3px');
		$(arrMap[mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+childIndex).attr('nameSegnalino', "mtgt_unnamed_"+childIndex);
		
		var tmpStyleWrapMaker = $(arrMap[mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+childIndex).attr('style');
		
		var topMaker = $(arrMap[mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+childIndex).css('top');
		var leftMaker = $(arrMap[mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+childIndex).css('left');
		var widthMaker = $(arrMap[mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+childIndex).css('width');
		var heightMaker = $(arrMap[mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+childIndex).css('height');
		//alert(topMaker + "||" + leftMaker + "||" + widthMaker + "||" + heightMaker)
		
		$(arrMap[mapIndex]).children("div").children("div").children("div").children("div").append('<div class="infomap" name="infomap'+childIndex+'" id="info_'+childIndex+'" style="'+tmpStyleWrapMaker+' margin:0px; position:relative; float:left; width:198px; height:126px; display:none; top:'+topMaker+200+'"><div class="content_info"><span class="info_cliente"><br>'+pcliente+'<br><br></span><span class="info_cliente_txt">'+ploc+'<br>'+pInfo+'<br>tel: '+ptel+'</span></div></div>');
		//$(arrMap[mapIndex]).children("div").children("div").children("div").children("div").children("#mtgt_unnamed_"+childIndex).wrap('<div style="'+tmpStyleWrapMaker+' border:2px solid red; margin:0px; position:relative"></div>');
	}
	
	childIndex = childIndex + 1;
	createSingleMap(mapIndex, childIndex);
}
