// Namespace definition and Widget 

MapCity.Core.namespace('Site');
MapCity.Core.namespace('Site.Searcher');
MapCity.Core.namespace('Site.Map');
MapCity.Core.namespace('Site.Locale');
Site.Map;
Site.CurrentLanguage;
Site.poi;
Site.poiMarkers;
Site.CurrentCountry;
Site.CurrentCountryName='chile';
Site.CurrentSearcher;
Site.CurrentSearch=1;
Site.LastSearched='';
Site.curdir='';
Site.environment = new MapCity.Services.Geocoding.enviroment();
Site.photosbyextent = new MapCity.Services.Util.GetPhotoByExtent();
Site.photos = new MapCity.Services.Util.GetPhoto();
Site.searchPOI = new MapCity.Services.Geobusiness.SearchCommerce();
Site.comPbyextent = new MapCity.Services.Util.GetComunasByExtent();

Site.poiChecked='';
Site.photosLocation = 'http://fotos.mapcity.com/fachadas/';
Site.timerhideTOS;
Site.timercounter=0;
Site.ActiveChannelOption=[];
Site.ActiveChannel="";
Site.ThisPointId="";
Site.include;
Site.Backgrd="";
Site.LON = null;
Site.LAT = null;
Site.pa_nearly=null;

Site.USSN=false;
Site.ActiveSearch=false;

//******************************carga de librerias js *******************************

Site.load_news			=false;
Site.load_options		=false;
Site.load_phone			=false;
Site.load_commerce		=false;
Site.load_poi			=false;
Site.load_twitter		=false;
Site.load_printmap		=false;
Site.load_env			=false;
Site.certifica			=false;


//Site.load_news			=false;
//******************************carga de librerias js *******************************
Site.ChannelActive=new Array();//{};

Site.LinkPrint = ''; //enlaces imprimir mapa

Site.frame=1;
Site.linkear=1;
Site.news=4;
Site.get=MapCity.Core.get; 
Site.sel=MapCity.Core.select;
Site.query=MapCity.Core.query;
Site.each=MapCity.Core.each;
Site.dom=MapCity.Core.DomHelper;
Site.dom.useDom = true;
Site.qb=1;
Site.Ads=true;
Site.q;
Site.qC;

// Search Commerces global variables
Site.SearchCommercesbyExtend=true;
Site.SearchCommercesNum=100;
Site.SearchCommercesStopSearch=false;

// Setting Markers 
Site.AddressMarkers;
Site.CommerceMarkers;
Site.PhoneMarkers;
Site.AddressMarkersFitZoom;
Site.PhotoMarkers;
Site.POIMarkers;
Site.bounds;
Site.DigitalPoints;
Site.CurrentView = 'View_Channels';//'View_Start';

// Locale function load on MAPCITY CORE READY


Site.InitMap=function() {

			Site.Locale.get = function(key){
				
				if(Site.Locale.language
					&& Site.Locale.language[key])
				{
					//return 'áéàè'; //to check
					return Site.Locale.language[key];
				};
				
				//If key not exist, then return key
				return (key);
			};
			 
			 
			// Defining Widgets and functionalities
			
			
			// Setting and load map and layers
			Site.Map = {
					init: function(){
						//alert("1");
						var countrycity;
						var defaultzoom=8;
						
						switch (Site.CurrentCountry)
						{
							case 'ar':
									Site.CurrentCountryName='argentina';
									countrycity='argentina';
									
									break;
							case 'mx':
									Site.CurrentCountryName='mexico';
									countrycity='mexico'
									break;
							case 'pe':
									Site.CurrentCountryName='peru';
									countrycity='peru';
									defaultzoom=5;
									break;
							case 'br':
									Site.CurrentCountryName='saopaulo';
									countrycity='saopaulo';
									break;
							
							default:
								Site.CurrentCountryName='chile';
								countrycity='chile';
								break;
							
							}
						
						//alert("2");
						// Creating Map
						Site.Map.map = new MapCity.Maps.map('map',{
							country:countrycity
							,provider: 'mapcity'
							,controls: [
									new MapCity.Maps.Controls.ZoomBar()
									,new MapCity.Maps.Controls.ScaleLine()
									,new MapCity.Maps.Controls.Navigation({zoomWheelEnabled:true})
									,new MapCity.Maps.Controls.ArrowMapNorth({north: true})
									,new MapCity.Maps.Controls.ArrowMapSouth({south: true})
									,new MapCity.Maps.Controls.ArrowMapEast({east: true})
									,new MapCity.Maps.Controls.ArrowMapWest({west: true})
									
								,new MapCity.Maps.Controls.SwitchMapBar({
									vector: true
									,photo: true
									,guide: true
								})
								 ,new MapCity.Maps.Controls.ToolsBar({
								   measureline: true
								  ,measurepolygon: true
								  ,dragpan: true
								  ,zootomaxextent: false
								  ,zoomin: true
								  ,zoomout: true
								  ,infostreet: true
								  ,infogse: true
								})
							]
							});
							//alert("3");
							Site.Map.map.olMap.zoomTo(defaultzoom);
						 	//alert("4");
							
							
							
							// Definning layupdateNearbyers for the map

							Site.PhotoLayer = Site.Map.map.addLayer('PhotoLayer','marker'); 
							Site.RouteLayer = Site.Map.map.addLayer('RouteLayer','marker');
							Site.POILayer = Site.Map.map.addLayer('POILayer','marker'); 
							Site.PhoneLayer = Site.Map.map.addLayer('PhoneLayer','marker');
							Site.NewLayer = Site.Map.map.addLayer('NewLayer','marker'); 
							Site.CommerceLayer = Site.Map.map.addLayer('CommerceLayer','marker');
							Site.AddressSearchLayer = Site.Map.map.addLayer('AddressSearchLayer','marker');  	
							Site.RouteFromLayer= Site.Map.map.addLayer('RouteFromLayer','marker');  	
							Site.RouteToLayer= Site.Map.map.addLayer('RouteToLayer','marker');  	
							//alert("5");
							Site.Map.streetInfo = new MapCity.Services.Geocoding.streetInfoById();
							//alert("6");
							Site.layerMarkerCons = Site.Map.map.addLayer('PtoDigi','marker');//PTO DIGITAL
							//alert("7");
							
							Site.Map.map.registerEvent("moveend", function(e) {
									Site.updateNearby();
									var scale =11;
									
									//Esto arregla la vista satelital de Google
									if(Site.Map.map.olMap.getNumZoomLevels() == 18){
									scale = 13;
									}
									//Esto arregla la vista satelital de Google
									Site.GetDP(scale);
									
									//Show comuna label at map
									if(Site.Map.map.olMap.getScale()<85000)
										{Site.fncComunas();}
									else{
											var layerCapa = Site.Map.map.getLayer('lyrCapaComuna', 'marker');				
											if (layerCapa != undefined) {
												Site.Map.map.removeAllMarkers('lyrCapaComuna', 'marker');					
											} 
										}
									
									//if(Site.Map.map.getZoom() >= 11){
									if (Site.ActiveSearch==false){
										for(key in Site.ChannelActive){
											if(Site.ChannelActive[key] == true){
												/*llama canales*/
												
												Site.ActiveSwitch("chk"+key,true);
												Site.OpenChannel(key);
											}
										}
									}
									// Visualize lat, lon on status bar every time move the map
									//lonlat=Site.Map.map.getCenter();
									//Site.putHTML('status','lat: '+lonlat.lat+', lon: '+lonlat.lon+' - ');									
									//Site.Map.map.getScale() <= 15000)
									//Site.Tsr('m');
									
							});
							//alert("8");
							Site.Map.CenterZoom = function(lon,lat,zoom){
									try{Site.ShowLoading('loadingglobal',true);}catch(err){}
									
									var lonlat = new MapCity.Maps.LonLat(lon, lat);
									Site.Map.map.setCenter(lonlat,zoom);
								
									try{Site.ShowLoading('loadingglobal',false);}catch(err){}
								}	
								//alert("9");
								var la = Site.Map.map.olMap.getNumLayers();
					}

			}
			
				
				Site.Searcher.Widgets = {
						init: function(){
				
				
					   //*******************************************************************
						// ONE LINE SEARCH
						//*******************************************************************
							Site.searchUnaLinea = new MapCity.Widgets.SearchComboBox({
								input: 'search_global_address_commerce_person'
								,action: 'search_global_but'
								,limit: 7
								,width: 285
								,country: Site.CurrentCountryName
								,before: function(){
										try{document.getElementById('FrontBarSite').style.display='none';}catch(err){}																	
									
									
								}
								,actionCallback: function(json,product,service){
								

								
								}
							});
							
				
						//*******************************************************************
						// SEARCH BY PHONE AND PERSON
						//*******************************************************************
				
							Site.searchPersonas = new MapCity.Widgets.SearchPersonComboBox({
								names: 'search_by_person_name'
								,lastName: 'search_by_person_surname1'
								,motherMaidenName: 'search_by_person_surname2'
								,phone: 'search_by_phone_phone'
								,action: 'search_by_phone_but'
								,limit: 999
								,widthNames: 70
								,widthLastName: 107
								,widthMotherMaidenName: 107
								,widthArea: 100
								,widthPhone: 140
								,before: function(){
									Site.ShowLoading('loadingsearch',true);
								try{document.getElementById('FrontBarSite').style.display='none';}catch(err){}																	
								}
								,actionCallback: function(json,product,service){
								
							
								
								var total = 0;
									
									try{total=json.totalCount;}catch(err){total=0}
									
									
									
								
								
								Site.switchView('View_PhoneList');
								document.getElementById('barra_tabs_portada').style.display='none';	
									
									
									
									if (total==0) // If there are no results
											{	
												Site.putHTML('PhoneListTitle', Site.Locale.get('tit_Phonenotfound'));
												Site.putHTML('PhoneList','<div class="boxMessage"><div class="boxContent" /><div id="cannotfindphone" />'+
																										Site.Locale.get('err_cannotfindphone')+'</div>');
												
												Site.ShowObject('PhoneList',true);
												
												Site.ShowLoading('loadingsearch',false);
												
								
											}else{
													
													
													var address = json.searchstreet;
													
													Site.SearchPhones(json,product,service,'PhoneList');
											
													Site.ShowLoading('loadingsearch',false);
													Site.ShowObject('trash4',true);
													
												
											}
								
								}
							});
						
	
				
 
				   			// If press ENTER search the route
							new MapCity.Core.KeyNav(MapCity.Core.get('search_by_route_addr_from'), {
							"enter" : function(e){
									Site.ShowLoading('loadingsearch',true);
									Site.searchRuta1Separado.search();
									Site.searchRuta2Separado.search();
									Site.ShowLoading('loadingsearch',false);
								
								},
								scope : this
							});
				   
				   
							new MapCity.Core.KeyNav(MapCity.Core.get('search_by_route_inter_from'), {
							"enter" : function(e){
									Site.ShowLoading('loadingsearch',true);
									Site.searchRuta1Separado.search();
									Site.searchRuta2Separado.search();
									Site.ShowLoading('loadingsearch',false);
								
								},
								scope : this
							});
				   
					   new MapCity.Core.KeyNav(MapCity.Core.get('search_by_route_addr_to'), {
							"enter" : function(e){
									Site.ShowLoading('loadingsearch',true);
									Site.searchRuta1Separado.search();
									Site.searchRuta2Separado.search();
									Site.ShowLoading('loadingsearch',false);
								
								},
								scope : this
							});
				   
							new MapCity.Core.KeyNav(MapCity.Core.get('search_by_route_inter_to'), {
							"enter" : function(e){
									Site.ShowLoading('loadingsearch',true);
									Site.searchRuta1Separado.search();
									Site.searchRuta2Separado.search();
									Site.ShowLoading('loadingsearch',false);
								
								},
								scope : this
							});
						   
						
						//*******************************************************************
						// SEARCH  ROUTE
						//*******************************************************************
						   Site.searchRuta1Separado = new MapCity.Widgets.AdvancedSearchComboBox({
								street: 'search_by_route_addr_from'
								,intersection: 'search_by_route_inter_from'
								,action: 'search_by_route_but'
								,limit: 7
								,widthStreet: 160
								,widthNumber: 50
								,widthDistrict: 100
								,widthIntersection: 100
								,country: Site.CurrentCountryName
								,before: function(){
									Site.ShowLoading('loadingsearch',true);
									Site.ShowObject('RouteLiteralBox', false);
									
								}
								,actionCallback: function(json,product,service){
											var total = json.totalCount;
											Site.switchView('View_RouteList');
								try{document.getElementById('FrontBarSite').style.display='none';}catch(err){}																			
										
											if (total==0) // If there are no results
											{
													html=Site.Searcher.Route_html_list_start;
													html+=Site.Searcher.Route_html_list_titleFROM('',Site.Locale.get('lbl_from').toUpperCase(),'');
													html+=Site.Searcher.Route_html_list_item(0,'address0',
															Locale.get('lbl_noaddressfound'),'');
													html+=Site.Searcher.Route_html_list_end;
													//Inject list to ul
													//Site.get(ul).dom.innerHTML=html;
													Site.putHTML('RouteListFROM',html);
													Site.ShowLoading('loadingglobal',false);
											}else{
												
													Site.ShowObject('trash2',true);
													var address = json.searchstreet;
													Site.SearchAddressforRoute(json,product,service,'RouteListFROM');
													Site.ShowLoading('loadingsearch',false);
											}
									}
							});
						  
						   
							/* BUSQUEDA DE RUTA DIRECCION 2*/
							Site.searchRuta2Separado = new MapCity.Widgets.AdvancedSearchComboBox({
								street: 'search_by_route_addr_to'
								,intersection: 'search_by_route_inter_to'
								,action: 'search_by_route_but'
								,limit: 7
								,widthStreet: 160
								,widthNumber: 50
								,widthDistrict: 100
								,widthIntersection: 100
								,country: Site.CurrentCountryName
								,before: function(){
								
									Site.ShowLoading('loadingsearch',true);
								try{document.getElementById('FrontBarSite').style.display='none';}catch(err){}																	
								
								}
								,actionCallback: function(json,product,service){
											var total = json.totalCount;
											Site.switchView('View_RouteList');
								document.getElementById('barra_tabs_portada').style.display='none';												
											if (total==0) // If there are no results
											{
												Site.putHTML('RouteListTitle', Site.Locale.get('tit_addressnotfound'));
												Site.putHTML('RouteListTO','<div class="boxMessage"><div class="boxContent" /><div id="cannotfindaddress" />'+
																										Site.Locale.get('err_cannotfindaddress')+'</div>');
												Site.ShowObject('RouteListTO',true);
												Site.ShowLoading('loadingsearch',false);
											}else{
													Site.ShowObject('trash2',true);
													var address = json.searchstreet;
													Site.SearchAddressforRoute(json,product,service,'RouteListTO');
													Site.ShowLoading('loadingsearch',false);
											}
								}
							});
							
						
						//*******************************************************************
						// SEARCH COMMERCE
						//*******************************************************************
						
						Site.Searcher.Widgets.commerce = new MapCity.Widgets.CommerceSearchComboBox({
							commerceClass: 'search_by_commerce_item'
							,commerce: 'search_by_commerce_name'
							,action: 'search_by_commerce_but'
							,limit: Site.SearchCommercesNum
							,widthStreet: 153
							,widthNumber: 50
							,widthDistrict: 100
							,widthIntersection: 153
							,widthCommerceClass:200
							,widthCommerce: 150
							,limitGlobal: 4
							,searchGlobal: true
							,searchByExtent:{
										'map': Site.Map.map,
										'active': Site.SearchCommercesbyExtend		
							}
							,before: function(){
								Site.ShowLoading('loadingsearch',true);
								try{document.getElementById('FrontBarSite').style.display='none';}catch(err){}								
								if (Site.Map.map.getZoom()<=9)
									Site.Map.map.olMap.zoomTo(11);
							
								
								
							}
							,actionCallback: function(json,product,service){
								
									var total = 0;
									
									try{total=json.totalCount;}catch(err){}
								
									Site.switchView('View_CommerceList');
								document.getElementById('barra_tabs_portada').style.display='none';										
									
									if (total==0) // If there are no results
											{	
												Site.putHTML('CommerceListTitle', Site.Locale.get('tit_commercenotfound'));
												Site.putHTML('CommerceList','<div class="boxMessage"><div class="boxContent" /><div id="cannotfindcommerce" />'+
																										Site.Locale.get('err_cannotfindcommerces')+'</div><br><br><br><br> ');
												
												Site.ShowObject('CommerceList',true);
												
												Site.ShowLoading('loadingsearch',false);
												Site.ShowObject('trash3',false);
								
											}else{
													
													var address = json.searchstreet;
													
													Site.SearchCommerces(json,product,service,'CommerceList');
											
													Site.ShowLoading('loadingsearch',false);
													Site.ShowObject('trash3',true);
											}
							}
							,addressFailureCallback: function(json,product,service){
								Site.ShowObject('trash3',false);
							
							}
							,actionGetPage: function(total,pagina){
								
								
							}
						});
						
						//*******************************************************************
						// CLASSIC SEARCH 
						//*******************************************************************
						
						Site.Searcher.Widgets.advanced = new MapCity.Widgets.AdvancedSearchComboBox({
									street: 'search_by_address_addr'
									,number: 'search_by_address_num'
									,district: 'search_by_address_pobl'
									,intersection: 'search_by_address_inter'
									,action: 'search_by_address_but'
									,limit: 100
									,widthStreet: 160
									,widthNumber: 75
									,widthDistrict: 160
									,widthIntersection: 160
									,country: Site.CurrentCountryName
									,force_mapcity:false   // IMPORTANT!!! IF MAPCITY DOES...
									,before: function(){
											Site.ShowLoading('loadingsearch',true);
											try{document.getElementById('FrontBarSite').style.display='none';}catch(err){}
											
									}
									,actionCallback: function(json,product,service){
											
											
												var total = json.totalCount;
												
										
											
											Site.switchView('View_AddressList');
											
											//alert(product+'/'+service);
											
											if (total==0) // If there are no results
											{
														//Site.Map.map.removeAllFeatures();
													//Site.Map.map.removeAllMarkers();
												
												
												
												Site.putHTML('ItemListTitle', Site.Locale.get('tit_addressnotfound'));
												Site.putHTML('ItemList','<div class="boxMessage"><div class="boxContent" /><div id="cannotfindaddress" />'+
																										Site.Locale.get('err_cannotfindaddress')+'</div>');
												
												Site.ShowObject('ItemList',true);
												
												Site.ShowLoading('loadingsearch',false);
												
													
								
											}else{
													
														Site.ShowObject('trash1',true);
													var address = json.searchstreet;
													Site.SearchAddress(json,product,service,'ItemList');
													
													
													//MapCity.Core.select('a[href=http://www.google.com/intl/en_ALL/help/terms_maps.html]').setStyle('display','none');
													
													
													
													Site.ShowLoading('loadingsearch',false);
												
											}
										
									}
						}); // END CLASSIC SEARCH
						
						// Execute at the end of ONREADY
				} // END INIT FUNCTION
			}// END WIDGETS

			Site.Map.CenterandZoom = function(lon,lat,zoom,i){
				Site.LON = lon;
 				Site.LAT = lat;
				Site.ShowLoading('loadingglobal',true);
					
					var lonlat = new MapCity.Maps.LonLat(lon, lat);
					Site.Map.map.setCenter(lonlat,zoom);
				
				  Site.AddressMarkers[i].showPopup();
				
				Site.ShowLoading('loadingglobal',false);
				}
				
			Site.Map.CenterandZoomRoute = function(lon,lat,zoom){
				Site.ShowLoading('loadingglobal',true);
					var lonlat = new MapCity.Maps.LonLat(lon, lat);
					Site.Map.map.setCenter(lonlat,zoom);
					Site.ShowLoading('loadingglobal',false);
				}
				
				
			Site.Map.CenterandZoomCommerce = function(lon,lat,zoom,i){
				Site.ShowLoading('loadingglobal',true);
					
					var lonlat = new MapCity.Maps.LonLat(lon, lat);
					Site.Map.map.setCenter(lonlat,zoom);
				
				  Site.CommerceMarkers[i].showPopup();
				
				Site.ShowLoading('loadingglobal',false);
				}
			Site.Map.CenterandZoomPhone = function(lon,lat,zoom,i){
				Site.ShowLoading('loadingglobal',true);
					
					var lonlat = new MapCity.Maps.LonLat(lon, lat);
					Site.Map.map.setCenter(lonlat,zoom);
				
				  Site.PhoneMarkers[i].showPopup();
				
				Site.ShowLoading('loadingglobal',false);
				}
			
			// FUNCTION CREATE ADDRESS MARKER
			Site.Map.CreateIconMarker = function(id, lon,lat,icon_path,int_w_iconsize, 
												 					  int_h_iconsize,Site_layer,text_popupcontent, bool_showpopup,offx, offy){
						
						var lonlat = new MapCity.Maps.LonLat(lon, lat);
						
						// Calculating offset
						
						calculateOffset = function(ofx,ofy) {
									return new MapCity.Maps.Pixel(ofx, ofy); };
						
						// Creating Offset
						var icon = new MapCity.Maps.Icon( 
								icon_path
								,new MapCity.Maps.Size(int_w_iconsize,int_h_iconsize),calculateOffset(offx,offy));
					
						//icon.imageDiv.style.cursor = "pointer";
						
						Site.AddressMarkers[id]=Site.Map.map.addPopUpMarker( 
								Site_layer
								,lonlat 
								,'<div class="popupAddress">'+text_popupcontent+'<div class="popupSocialButtons"><br>'+Site.SocialButtons()+'</div></div><div id="addressmarker'+id+'"></div>'
								,icon 
								,true 
								,true 
								,MapCity.Maps.PopUp.FramedBubble
								,bool_showpopup);
						
				}
				
			
				
			// FUNCTION CREATE COMMERCE MARKER
			Site.Map.CreateCommerceMarker = function(id, lon,lat,icon_path,int_w_iconsize, 
													 							int_h_iconsize,Site_layer,text_popupcontent, bool_showpopup,offx, offy){
						
						var lonlat = new MapCity.Maps.LonLat(lon, lat);
						
						// Calculating offset
						
						calculateOffset = function(ofx,ofy) {
									return new MapCity.Maps.Pixel(ofx, ofy); };
						
						// Creating Offset
						var icon = new MapCity.Maps.Icon( 
								icon_path
								,new MapCity.Maps.Size(int_w_iconsize,int_h_iconsize),calculateOffset(offx,offy));
					
						
						Site.CommerceMarkers[id]=Site.Map.map.addPopUpMarker( 
								Site_layer
								,lonlat 
								,'<div class="popupCommerce">'+text_popupcontent+'<br>'+Site.SocialButtons()+'</div><div id="commerceMarkers'+id+'"></div>'
								,icon 
								,true 
								,true 
								,MapCity.Maps.PopUp.FramedBubble
								,bool_showpopup);
						
				}
			// FUNCTION CREATE PHONE MARKER
			Site.Map.CreatePhoneMarker = function(id, lon,lat,icon_path,int_w_iconsize, 
												  						 int_h_iconsize,Site_layer,text_popupcontent, bool_showpopup,offx, offy){
						
					
						
						var lonlat = new MapCity.Maps.LonLat(lon, lat);
						
						// Calculating offset
						
						calculateOffset = function(ofx,ofy) {
									return new MapCity.Maps.Pixel(ofx, ofy); };
						
						// Creating Offset
						var icon = new MapCity.Maps.Icon( 
								icon_path
								,new MapCity.Maps.Size(int_w_iconsize,int_h_iconsize),calculateOffset(offx,offy));
					
						
						Site.PhoneMarkers[id]=Site.Map.map.addPopUpMarker( 
								Site_layer
								,lonlat 
								,'<div class="popupPhone">'+text_popupcontent+'<br>'+Site.SocialButtons()+'</div><div id="PhoneMarkers'+id+'"></div>'
								,icon 
								,true 
								,true 
								,MapCity.Maps.PopUp.FramedBubble
								,bool_showpopup);
						
				}
				
				// FUNCTION CREATE PHONE MARKER
			Site.Map.CreatePhotoMarker = function(id, lon,lat,icon_path,int_w_iconsize, 
												  						int_h_iconsize,Site_layer,text_popupcontent, bool_showpopup,offx, offy){
						
						var lonlat = new MapCity.Maps.LonLat(lon, lat);
						
						// Calculating offset
						
						calculateOffset = function(ofx,ofy) {
									return new MapCity.Maps.Pixel(ofx, ofy); };
						
						// Creating Offset
						
						var icon = new MapCity.Maps.Icon( 
								icon_path
								,new MapCity.Maps.Size(int_w_iconsize,int_h_iconsize),calculateOffset(offx,offy));
						
						icon.imageDiv.style.border = '2px Solid #c7c7c7';
					
						
						Site.PhotoMarkers[id]=Site.Map.map.addPopUpMarker( 
								Site_layer
								,lonlat 
								,'<div class="popupPhoto">'+text_popupcontent+'<br>'+Site.SocialButtons()+'</div><div id="PhotoMarkers'+id+'"></div>'
								,icon 
								,true 
								,true 
								,MapCity.Maps.PopUp.FramedBubble
								,bool_showpopup);
						
				}
				
				
				
			//FUNCTION DRAWSTREET
			// Draws a line
			Site.Map.drawStreet = function(j, str_street){
				
				Site.ShowLoading('loadingglobal',true);
				
				Site.Map.map.removeAllFeatures();
				
				Site.Map.streetInfo.get(
					{idStreet: Site.q.searchstreet[j].idStreet},
					function(json){
								 var StreetClass =  {fillColor: "#F00000",
														fillOpacity: 0.5,
														strokeColor: "#F00000",
														strokeOpacity: 0.5,
														strokeWidth: 8,
														pointRadius: 0.5,
														pointerEvents: "visiblePainted",
														cursor: "pointer",
														zIndex: 10};
				
								var feat=Site.Map.map.addFeatureWKT(null,json.streetinfobyid[0].wkt,StreetClass);
								
								Site.LastSearched= str_street;
								
									
								Site.bounds=feat.geometry.getBounds();
								Site.Map.map.zoomToExtent(Site.bounds);
								Site.ShowLoading('loadingglobal',false);
					}
				);
				
			};
			
			
			//FUNCTION DRAW DISTRICT
			Site.Map.drawDistrict = function(j){
				Site.ShowLoading('loadingglobal',true);
				Site.Map.map.removeAllFeatures();
				var feat=Site.Map.map.addFeatureWKT(null,Site.q.searchdistrict[j].wkt);
					Site.bounds=feat.geometry.getBounds();
					Site.Map.map.zoomToExtent(Site.bounds);
				Site.ShowLoading('loadingglobal',false);
				}
			

			
				
			Site.DrawRoute = function(){
				if(Site.drawnRoute==false){
					
						Site.drawnRoute=true;
						Site.ShowLoading('loadingglobal',true);
						
						
						var route = new  MapCity.Services.Geocoding.GetRoute();
													route.get({
															'target': Site.RouteToIdStreet
															,'targetpoint': Site.RouteToLon+' ' + Site.RouteToLat 
															,'source': Site.RouteFromIdStreet
															,'sourcepoint': Site.RouteFromLon + ' ' + Site.RouteFromLat
														,'transit': Site.RouteTransit
														 }
															,function(json, product, service){		
																Site.route=json;
																
																Site.Map.map.removeAllFeatures();
																
																Site.Map.drawRoute(json,'');
																
																Site.ShowLoading('loadingglobal',false);
																				
															}
														);
				}
				};	
				
				
		
				
				
			
			//FUNCTION DRAWROUTE
			// Draws a line
			Site.Map.drawRoute = function(json, str_street){
				
				tot=json.totalCount;
				
				if(tot>0)
				{
						Site.ShowLoading('loadingglobal',true);
						
						var RouteClass =  {fillColor: "#F00000",
																fillOpacity: 0.5,
																strokeColor: "#F00000",
																strokeOpacity: 0.5,
																strokeWidth: 8,
																pointRadius: 0.5,
																pointerEvents: "visiblePainted",
																cursor: "pointer",
																zIndex: 10};
												
						i=json.totalCount-1;
						//for (var i=0;i<json.totalCount;i++){
						// Draw route
						Site.Map.map.addFeatureWKT(null,json.getroute[i].wkt, RouteClass);
							//		}
						i=0;			
						
						Site.tellRoute(json);
						
						
						var startlonlat = new MapCity.Maps.LonLat(Site.RouteFromLon, Site.RouteFromLat);
						var endlonlat = new MapCity.Maps.LonLat(Site.RouteToLon, Site.RouteToLat);
						
						Site.FitZoomTwoPoints(startlonlat,endlonlat);
						Site.ShowLoading('loadingglobal',false);
						Site.drawnRoute=false;
						//var lonlat = new MapCity.Maps.LonLat(lon, lat);
				}else{
					Site.ShowObject('RouteLiteralBox', false);
					Site.ShowLoading('loadingglobal',false);
				}
				
			
			};
			
			
			var starttable='<table cellspacing="20" border="0" width="100%">';
			var startline='<tr>'
			var column_left='<td class="table_underline" width="18" align="left" valign="top">***</td>';
			var column_center='<td class="table_underline" align="left" valign="top">***</td>';
			var column_right='<td style="color:gray;" class="table_underline" width="45" align="right" valign="top">***</td>';
			var endline='</tr>'
			var endtable='</table>';
			
			 
			Site.tellRoute=function(json){
					
					// compossing literal route
				
					var tellingroute='';
					var distance=0;
					var totaldistance=0;
					var direction='';
					var orientation='';
					var street='';
					var spl;
					var turn='';
					var turn_orientation='';
					var firstline=false;
					var arrow='';
					
					var routeliteral=starttable;
					
					for (var i=0;i<json.totalCount-1;i++){
						
						street = json.getroute[i].girocalle.toString();
						
						turn_orientation = json.getroute[i].giro.toString();	
						
						if(turn_orientation.indexOf(',')==-1){ // First line
							
								tellingroute =Site.Locale.get('route_depart')+ street;
								
								firstline=true;
							
						}else{  // Other lines
								spl=turn_orientation.split(',');
								turn = spl[0];
								orientation= spl[1];
								if(spl[0]==0){direction=Site.Locale.get('route_ahead');arrow='/img/arrows/arrow-top.png';};
								if(spl[0]==-1){direction=Site.Locale.get('route_turnleft');arrow='/img/arrows/arrow-left.png';};
								if(spl[0]==1){direction=Site.Locale.get('route_turnright');arrow='/img/arrows/arrow-right.png';};
								
								
								if(laststreet!=street){  // CHANGING STREET
										routeliteral=routeliteral.replace('NEXTSTREET',street);
										routeliteral=routeliteral.replace('DISTANCE',Site.calc_distance(distance));
										totaldistance+=parseInt(distance);
										
										if(firstline==true){
												tellingroute=(tellingroute+ Site.Locale.get('route_to') +street).replace('ORIENTATION', Site.Locale.get(orientation));
												routeliteral += Site.addLinetotellRoute('',tellingroute,Site.calc_distance(distance),'/img/blank.gif');
												firstline=false;
												distance=parseInt(json.getroute[i].largocalle);
										}; //end if
										
										//if(nextstreetchange==false){
										var rand=Math.floor(Math.random()*2);
										var tostring;
										if(rand==0)tostring=Site.Locale.get('route_continue1'); 
										if(rand==1)tostring=Site.Locale.get('route_continue2'); 
										if(rand==2)tostring=Site.Locale.get('route_continue3');
										
										tellingroute = direction + Site.Locale.get('route_trought') + street + tostring + 'NEXTSTREET';
										routeliteral+=Site.addLinetotellRoute('',tellingroute,'DISTANCE',arrow);
										
										tellingroute='';
										distance=0;
											
								};
							
						}; //End If
						
						distance += parseInt(json.getroute[i].largocalle);
						laststreet=street;
						
						
						
					}; // For End
					
					routeliteral=routeliteral.replace('NEXTSTREET',Site.RouteToText.replace('/',' ' +Site.Locale.get('lbl_with')+' '));
					routeliteral=routeliteral.replace('DISTANCE',Site.calc_distance(parseInt(distance)));
					totaldistance+=parseInt(distance);
					
					routeliteral+=endtable;
					
					// stablish header
					var routetype;
					if(Site.RouteTransit==true){routetype=Site.Locale.get('route_type_car');}else{routetype=Site.Locale.get('route_type_walking');};
					
					routeliteral='<b>'+Site.Locale.get('lbl_from')+':</b> '+Site.RouteFromText+'<br><b>'+Site.Locale.get('lbl_to')+':</b> '+Site.RouteToText.replace('/',' ' +Site.Locale.get('lbl_with')+' ')+'<br><br>'+routeliteral;
					routeliteral='<b>'+Site.Locale.get('route_pathsteps')+' ' +routetype+'...</b><br><br>'+routeliteral+'<br>';
					routeliteral+=Site.Locale.get('lbl_totaldistance') + Site.calc_distance(parseInt(totaldistance))+'<br>';
					routeliteral+=Site.Locale.get('lbl_timeroute') + Site.calc_time(totaldistance,Site.RouteTransit);
					routeliteral+='<br><br>';
					Site.putHTML('RouteLiteral',routeliteral);	
					Site.ShowObject('RouteLiteralBox',true);		
						
				};
			
			Site.calc_time=function(distance,type){
					var vel;
					var typ;
					if(type){vel=35;typ=Site.Locale.get('route_type_car')}else{vel=5;typ=Site.Locale.get('route_type_walking')};
					
					var distunitsvalue = 1; 
					var speedunitsvalue = 0.277777777777777777777777777777777777;
					var hours=0;
					var minutes=0;
					var seconds=0;
					var result;
					
					//  calculate time in seconds    
					seconds = (distance * distunitsvalue) / (vel * speedunitsvalue);
					//  convert to hours, minutes, seconds    
					hours = parseInt(seconds / 3600);
					seconds = seconds - (hours * 3600);
					minutes= parseInt(seconds / 60);
					seconds = parseInt(seconds - (minutes* 60));
					if(hours==0){
						result=minutes+Site.Locale.get('lbl_minutes')+' ' +typ;
					}else{
						result=	hours+ Site.Locale.get('lbl_hours')+minutes+Site.Locale.get('lbl_minutes')+' ' +typ;
						}
					
					return result;
				
				
				}
			
			
			
			Site.calc_distance = function(distance){
					    if(distance>999){
								return (distance/1000).toFixed(2)+' km';
						}else{
								return distance+ ' m';
						};
				}
			
			
			Site.addLinetotellRoute=function(logo,tellingroute,distance,arrow){
						
						var rl='';
						rl+=startline;
						
						rl+=column_left.replace('***','<img src="'+arrow+'">');
						rl+=column_center.replace('***',tellingroute );
						rl+=column_right.replace('***',distance);
						rl+=endline;
	
						return rl;
				
				};
			
			
			MapCity.Maps.setPopupNormal();
			// Initialize Map
			Site.Map.init();
			// initialize Widgets!!
			Site.Searcher.Widgets.init();
			
			Site.SetHash(Site.CurrentSearch);
			
		

}; // 


// FUNCTION ONLOAD. 
// Things to do when start the app
Site.onLoad = function(){
		Site.resizeApp(); 
		
		
		
		// Open initially the View_AddressList
		var cursearch=Site.GetHash('t');
		
		
		
		
		if(cursearch==null)
			cursearch==1;
			
		Site.chmenu(Site.CurrentSearch=cursearch);
		
		
		// if address fromtraditional is comming... 
		var fromtraditional=Site.GetHash('fromtraditional');
		
		if(fromtraditional!=null){
				fromtraditional=fromtraditional.replace(/_/g," ");
				document.getElementById('search_by_address_addr').value=fromtraditional;
				document.getElementById('search_by_address_addr').className='x-form-text x-form-field';
				setTimeout("Site.Searcher.Widgets.advanced.search();",1000);
	
		};

		Site.InitMap();
		
		
		document.getElementById("mapcontent").style.right = "184px";

		

		Site.DoOnLoad();
	
	

		
		//Site.EndInitializing();  
		if (Site.load_env==false) {
								Site.include('js/results/env.js');
								Site.load_env=true;	
		}
		

		

		if (Site.load_printmap==false) {
				Site.include('js/printsend.js');
				Site.load_printmap=true;
				var linkprint = "utilities/printmap/?l=es&amp;p=";
				if (Site.IsInternetExplorer==false){			
					setTimeout('Site.InitBanner();	document.getElementById("printlink").style.cursor="pointer";',2000);//			
				}else{
					
					setTimeout('Site.InitBanner();',3000);				
					setTimeout('document.getElementById("printlink").style.cursor="pointer";',2000);														
				}
		}
 	Site.include('js/social/rating.js');
	
    $.post("/ws/interface/MapcitySocial.site.php",{ method:"config",field:"banner_geocontextual"} ,function(data)  {		
		if (data==1)  setTimeout("Site.NoModal('bannermap');",5000);

    });
	
	setTimeout("Site.ChangeBackground('default');",0);
	
	if (Site.IsInternetExplorer()==false){
		
		var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome');
		var is_safari = navigator.userAgent.toLowerCase().indexOf('safari/');
		var is_opera = navigator.userAgent.toLowerCase().indexOf('opera');		
		
		if (is_chrome>-1){
			//$("#loading").remove();
			setTimeout("var d1 = document.getElementById('loading').parentNode;var d2=document.getElementById('loading');d1.removeChild(d2);",10);
			
			
		}else if (is_opera>-1){
			setTimeout('$("#loading").remove();',1000);			
						
		}else if (is_safari>-1 || is_opera>-1){
			setTimeout('$("#loading").remove();',2000);						
		}else{			
			setTimeout('$("#loading").remove();',2500);			
		}
	}else{
		setTimeout('$("#loading").remove();',1500);
	}
	$("#buttonprint").show(0);
	
	//ChangeBarRight();
//	$("#divBanner").hide();
//	$("#colright").hide();// HIDE RIGHT COLUMN
//	document.getElementById("mapcontent").style.right = "0px";	
	
}

Site.HideTermsofUse=function(){
	// hide TOS 10 times
	clearTimeout(Site.timerhideTOS);
	MapCity.Core.select('div[class=olLayerGoogleCopyright]').setStyle('display','none');
	Site.timerhideTOS=setTimeout("Site.HideTermsofUse();",400); 
	
	Site.timercounter+=1;
	if(Site.timercounter>=10){clearTimeout(Site.timerhideTOS);}
		
}





Site.DoOnLoad=function(){
	
	
	//if (!MapCity.Core.isIE){
		
		/*		var getaddrfromhash=Site.GetHash('a');
				if(getaddrfromhash){
					  document.getElementById('search_by_address_addr').value= getaddrfromhash.replace(/_/g," ");
					
					  //Site.Searcher.Widgets.advanced.search();
				}else{
					Site.switchView("View_Start");
					
				}*/
				
				
				var getaddrfromhash=Site.GetHash('a');
		   		var getpa=Site.GetHash('pa');
				if(getaddrfromhash!=null){
						document.getElementById('search_by_address_addr').value=getaddrfromhash.replace(/_/g," ");
						
						document.getElementById('search_by_address_addr').className='x-form-text x-form-field';
						// Search the referred address in 1 second
						setTimeout("Site.Searcher.Widgets.advanced.search();",1000);
						
						
						if(getpa!=null){Site.pa_nearly=getpa};
						
						
			
				}else{
					Site.switchView("View_Channels");//View_Start
					Site.showChannels();
				};
				
				
				
				
				

						//	 Site.putHTML('OptionsButton', '<a href="#" onmouseout="ChangeButtonReturn(\'OptionsButton\',0);"   onmouseover="ChangeButtonReturn(\'OptionsButton\',1);"  onclick="Site.switchView(\''+Site.CurrentView+'\');" class="Volver"><img border="0" id="OptionsButton_img" src="img/but/btn-volver-off.png"><a>');    
//       					 Site.putHTML('OptionsTitle',Site.Locale.get('tit_Options'));
	}

Site.ClearForm = function(str_input){
	
		q = Site.query('input.search_by_address'); Site.each(q, function(el){el.value = '';alert('');});

	}


	
// FUNCTION SWITCHVIEW
Site.switchView = function(str_view){
	
if (str_view=='View_Channels') {
	Site.ShowActiveChannels();
	ChangeTheme();
}

	
	
	// Change style all the div objects starting with View_ to dispay:none
	MapCity.Core.select('div[id^=View_]').setStyle('display','none');
	
	
	// Modify with of all comboboxes to rectify origin fail
	if(str_view=='View_PhoneList'){
		MapCity.Core.select('div[id^=ext-gen]').setStyle('width','68px');
	}else{		
		MapCity.Core.select('div[id^=ext-gen]').setStyle('width','180px');
	 }

	Site.CurrentView =str_view;
	// showObjects required in str_view parameter
	Site.ShowObject(str_view,true);
	
	}

// ACTIONS WHEN RESIZE WINDOW
// Needed for compatibilize app with IE6
Site.resizeApp = function() {
	var h = Site.viewport.getHeight();
	var w = Site.viewport.getWidth();
	
	//REDIMENSIONA EL BANNER INFERIOR DEL SITIO SI ES QUE ESTA VISIBLE
	var wscr = $(window).width();
	if(document.getElementById('bgnomodal')!=null  && wscr>900){
			
			var hscr = $(window).height();
			
			var wcnt = $('#bgnomodal').width();
			var hcnt = $('#bgnomodal').height();			
			
			Site.visibleColleft=(document.getElementById('leftpanelContent').style.display=='none')?false:true;
			
			var lcol=(Site.visibleColleft==true)?291:0;
			var rcol=(Site.visibleColRight==true)?172:0;
			
			var ldiv=7;
			var rdiv=7;
			
			var paneles = lcol+rcol+ldiv+rdiv; //left, right y divisores
			
			wscr2 = wscr-paneles; //espacio del mapa

			// obtener posicion central
			var mleft = (( wscr2 - wcnt ) / 2)+(lcol+ldiv+rdiv);
			var mtop = ( hscr - hcnt ) / 2;
			
			// estableciendo posicion
			$('#bgnomodal').css("left", mleft+'px');
			$('#bgnomodal').css("bottom", '25px');				
	}
	
	
	
	
	//S.resizeAds(); Must be implemented
	
	// If IE6 then resize the map
	if (MapCity.Core.isIE6){
		
			try{Site.get('map').setStyle('width', eval(w-298)+'px');}catch(err){}	
			try{Site.get('map').setStyle('left','298px');}catch(err){}
			
			//Fix the Map position in height and top
			try{Site.get('map').setStyle('height',eval(h-43)+'px');}catch(err){}
			try{Site.get('map').setStyle('top','43px');}catch(err){}
			
			try{Site.get('BottomContent').setStyle('width',eval(w-298)+'px');}catch(err){}
			
			// Very importants!! See into VIEWS!!!
			try{Site.get('AddressListContent').setStyle('height',eval(h-210-48)+'px');}catch(err){}
			try{Site.get('ItemDetailArea').setStyle('height',eval(h-210-48)+'px');}catch(err){}
			try{Site.get('CommerceListContent').setStyle('height',eval(h-210-48)+'px');}catch(err){}
			try{Site.get('RouteListContent').setStyle('height',eval(h-210-48)+'px');}catch(err){}
			try{Site.get('PhoneListContent').setStyle('height',eval(h-210-48)+'px');}catch(err){}
			try{Site.get('NewListArea').setStyle('height',eval(h-210-48)+'px');}catch(err){}
			try{Site.get('PhotoListArea').setStyle('height',eval(h-210-48)+'px');}catch(err){}		
			try{Site.get('POIArea').setStyle('height',eval(h-210-48)+'px');}catch(err){}
			try{Site.get('StartArea').setStyle('height',eval(h-210-48)+'px');}catch(err){}
			
	}
	

	
}

//FUNCTION VIEWPORT 
//GET WIDTH AND HEIGHT FROM CURRENT WINDOW
Site.viewport = {
	getWidth: function(){
	    if( typeof( window.innerWidth ) == 'number' ) {
	    	return window.innerWidth; //Non-IE
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	    	return document.documentElement.clientWidth; //IE 6+ in 'standards compliant mode'
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	    	return document.body.clientWidth; //IE 4 compatible
	  }
	}
	,getHeight: function(){
	    if( typeof( window.innerWidth ) == 'number' ) {
	        	return window.innerHeight; //Non-IE
	      } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
	        	return document.documentElement.clientHeight; //IE 6+ in 'standards compliant mode'
	      } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
	        	return document.body.clientHeight; //IE 4 compatible
	      }
	}
};

//FUNCTION SHOW/HIDE SEARCHLOADING
// Show/Hide Search loading 
Site.ShowLoading = function(str_loading_id,bool_stat){

	try{

			if(bool_stat==true){
				try{Site.get(str_loading_id).setDisplayed('block');}catch(err){}
			}else{
				try{Site.get(str_loading_id).setDisplayed('none');}catch(err){}
			}


	}catch(err){}
	
}

//FUNCTION SHOW/HIDE OBJECT
Site.ShowObject = function(str_objectid,bool_stat){
	if(bool_stat==true){
		try{Site.get(str_objectid).setDisplayed('block');}catch(err){}
	}else{
		try{Site.get(str_objectid).setDisplayed('none');}catch(err){}
	}
}


Site.SetHash=function(i){
	if(i==null || i=='')
		i=1;
		
	var p = window.location.hash;
	p = p.split("#");
	p = p[1];
	if(p){
		p = p.split(":");
		if(p[1])
			window.location.hash='#t='+i+':'+p[1];
		else
			window.location.hash='#t='+i;
	}
	else		
		window.location.hash='#t='+i;
}

Site.GetHash=function(str_param){
	var ret=null;
	var p = window.location.hash;		
	p=p.split("#");
	p = p[1];
	if(p){
		p = p.split(":");
		for(var i=0;i<p.length;i++){
			if(p[i]){
				p1 = p[i].split("=");
				if(p1[0]==str_param){
						ret=p1[1];
				}
			}
		}
	}
	
	return ret;
	
	}

Site.PutHashonSearch= function(addr){
	
	Site.SetHash(Site.CurrentSearch);
	
	var p = window.location.hash;
	
	
	p = p.split("#");
	p = p[1];
	if(p){
		p = p.split(":");
		if(p[0])
			window.location.hash='#'+p[0]+':a='+addr;
	}

};




// FUNCTION CHANGE SEARCH MENU
Site.chmenu = function(selectedmenu,bool_nochangeview){	


//alert("selectedmenu:"+selectedmenu+" bool_nochangeview: "+bool_nochangeview);
if (selectedmenu>1)	document.getElementById('FrontBarSite').style.display='none';
	if(selectedmenu==0  || selectedmenu==null || selectedmenu>5)
		{
			
			selectedmenu=1
		
		
		}
		
	
	Site.SetHash(selectedmenu);
	for(i = 1; i <= 5; i++)
	{
		element = document.getElementById(i);
		if(i == selectedmenu)
			try{element.className = "checked";}catch(err){}
		else
			try{element.className= '';}catch(err){}
	}
		  
	
	/* hide forms and show the selected one*/
	document.getElementById('search_by_address').style.display="none";
	document.getElementById('search_by_route').style.display="none";
	document.getElementById('search_by_commerce').style.display="none";
	document.getElementById('search_by_phone').style.display="none";
	document.getElementById('search_global').style.display="none";
	if (selectedmenu==1){
		document.getElementById('search_by_address').style.display="block";
		Site.CurrentSearch = 1;
		Site.switchView('View_AddressList');}
		
		
	if (selectedmenu==2){
/*		if (Site.load_route==false) {
				Site.include('js/results/route.js');
				Site.load_route=true;		
				setTimeout('document.getElementById("search_by_route").style.display="block";Site.CurrentSearch = 2;if(bool_nochangeview!=true) Site.switchView("View_RouteList");',500);

		}else{

			document.getElementById('search_by_route').style.display="block";
			Site.CurrentSearch = 2;	
			if(bool_nochangeview!=true) Site.switchView('View_RouteList');
		}*/
		document.getElementById("search_by_route").style.display="block";
		Site.CurrentSearch = 2;
		if(bool_nochangeview!=true) Site.switchView("View_RouteList");
		
	}
			
			
	if (selectedmenu==3){
//		if (Site.load_commerce==false) {
//			Site.include('js/results/comm.js');
//			setTimeout('document.getElementById("search_by_commerce").style.display="block";Site.CurrentSearch = 3;if(bool_nochangeview!=true)Site.switchView("View_CommerceList");',1500);
//			Site.load_commerce=true;
//			
//		}else{
			document.getElementById('search_by_commerce').style.display="block";
			Site.CurrentSearch = 3;
			if(bool_nochangeview!=true)	Site.switchView('View_CommerceList');
		//}			

	}
			
			
	if (selectedmenu==4){
//		if (Site.load_phone=false) {
//			Site.include('js/results/options.js');
//			Site.load_phone=true;	
//			setTimeout('Site.CurrentSearch = 4;document.getElementById("search_by_phone").style.display="block";Site.switchView("View_PhoneList");',500);			
//
//		}else{
//			Site.CurrentSearch = 4;
			document.getElementById('search_by_phone').style.display="block";		
			Site.switchView('View_PhoneList');
		//}
	}
		
		
	if (selectedmenu==5){
		Site.CurrentSearch = 5;
		document.getElementById('search_global').style.display="block";
		
		Site.switchView('View_NewList');}
}

Site.AddressMarkersFitZoom = function(){
	if(Site.AddressMarkers){
		Site.bounds = new OpenLayers.Bounds();
		for(var z=0; z<Site.AddressMarkers.length; z++)
			if(Site.AddressMarkers[z])
				Site.bounds.extend(Site.AddressMarkers[z].lonlat);
		Site.bounds.toBBOX();
		Site.Map.map.zoomToExtent(Site.bounds);
	}
};


Site.PhoneMarkersFitZoom = function(){
	if(Site.PhoneMarkers){
		Site.bounds = new OpenLayers.Bounds();
		for(var z=0; z<Site.PhoneMarkers.length; z++)
			if(Site.PhoneMarkers[z])
				Site.bounds.extend(Site.PhoneMarkers[z].lonlat);
		Site.bounds.toBBOX();
		Site.Map.map.zoomToExtent(Site.bounds);
	}
};


Site.CommercesFitZoom = function(maxfit){
	if(Site.CommerceMarkers){
		Site.bounds = new OpenLayers.Bounds();
		
		if(Site.CommerceMarkers.length<=maxfit){
			maxfit=Site.CommerceMarkers.length;}
		
		for(var z=0; z<maxfit; z++)
			if(Site.CommerceMarkers[z])
				Site.bounds.extend(Site.CommerceMarkers[z].lonlat);
		Site.bounds.toBBOX();
		Site.Map.map.zoomToExtent(Site.bounds);
	}
};


Site.FitZoomTwoPoints = function(firstpoint,secondpoint){
		
		Site.bounds = new OpenLayers.Bounds();
		Site.bounds.extend(firstpoint);
		Site.bounds.extend(secondpoint);
		Site.bounds.toBBOX();
		Site.Map.map.zoomToExtent(Site.bounds);
	
	}
	

	


// SHOW TEXT AT THE OBJECT ID FROM PHP LANGUAGE DEFINITION PAGE
Site.get_lbl = function(str_lbl, str_id, lang){
	Site.ShowLoading('loadingglobal',true);
	var ret='';
	MapCity.Core.Ajax.request({url:'/do/',
							 method:'GET', 
							 success: function(response,opts){Site.putHTML(str_id,response.responseText);
							 Site.ShowLoading('loadingglobal',false);},
							 params: {act: 'get_lbl', val: str_lbl, l: lang}});
	return ret;
	
}

// FUNCTION PUT HTML INTO OBJECT ID
Site.putHTML = function(str_objectid,html_content){
	try{Site.get(str_objectid).dom.innerHTML= (html_content);}catch(err){}
	//Site.get(str_objectid).dom.innerHTML= ('áéíóúàèìòùñÑ');
}


// THIS FUNCTION DOES NOT RUN!!!
Site.addHTML = function(str_objectid,html_addcontent){
	
	Site.get(str_objectid).dom.innerHTML =Site.get(str_objectid).value+ html_addcontent;
	
	
	}




// function clear layers
Site.clearLayer = function(str_layername){
	
	
	switch(str_layername){
		
		//CLEANING Address SearchLayer and lists...
		case 'AddressSearchLayer':
				Site.Map.map.removeAllFeatures();
				Site.AddressSearchLayer.removeAllMarkers();
				Site.PhotoLayer.removeAllMarkers();
				Site.switchView('View_AddressList');
				Site.putHTML('ItemList','');
				Site.putHTML('ItemListTitle','');
				Site.ShowObject('trash1',false);
				Site.ShowLoading('loadingglobal',false);
				
				break;
				
		case 'RouteLayer':
				Site.Map.map.removeAllFeatures();
				Site.RouteFromLayer.removeAllMarkers();
				Site.RouteToLayer.removeAllMarkers();
				Site.switchView('View_RouteList');
				Site.putHTML('RouteListFROM','');
				Site.putHTML('RouteListTO','');
				Site.putHTML('RouteItemFROM','');
				Site.putHTML('RouteItemTO','');
				Site.putHTML('RouteListTitle','');
				Site.putHTML('RouteLiteralBox','');
				Site.ShowObject('trash2',false);
				Site.ShowLoading('loadingglobal',false);
				
				break;
				
		case 'CommerceLayer':
				Site.CommerceLayer.removeAllMarkers();
				Site.switchView('View_CommerceList');
				Site.putHTML('CommerceList','');
				Site.putHTML('CommerceListTitle','');
				Site.ShowObject('trash3',false);
				Site.ShowLoading('loadingglobal',false);
				
				break;
				
		case 'PhoneLayer':
				Site.PhoneLayer.removeAllMarkers();
				Site.switchView('View_PhoneList');
				Site.putHTML('PhoneList','');
				Site.putHTML('PhoneListTitle','');
				Site.ShowObject('trash4',false);
				Site.ShowLoading('loadingglobal',false);
				
				break;
		case 'PhotoLayer':
					Site.PhotoLayer.removeAllMarkers();
					Site.ShowLoading('loadingglobal',false);
				
					break;
		case 'POILayer':
					Site.POILayer.removeAllMarkers();
					Site.ShowLoading('loadingglobal',false);
					break;
						
					
		
		
		}
	
	}


// FUNCTION SHOWPHOTOLIST
Site.showPhotoList = function(){
	
	Site.putHTML('PhotoListTitle',Site.Locale.get('lbl_PhotosZone'));
	Site.putHTML('PhotoListButton', 
				 		 '<a href="#" onclick="Site.switchView(\''+Site.CurrentView+'\', true);"><img border="0" src="/img/but/'+
						 Site.Locale.get('lbl_back')+'"><a>');
	Site.putHTML('PhotoListList',Site.Searcher.html_shadow);
	//Site.ShowLoading('loadingglobal',true);
	
	//Site.ShowObject('View_PhotoList',true);
	//Site.ShowLoading('loadingglobal',false);
	Site.switchView('View_PhotoList',true);
	Site.getPhotos(0,20,'s', '',true, 'PhotoListPhotoEnvironment');
	}

// FUNCTION SHOWOPTIONS
/*Site.showOption = function(str_viewtoreturn){
	
	Site.putHTML('lbl_Options',Site.Locale.get('lbl_Options'));
	
	//Site.ShowLoading('loadingglobal',true);
	
	//Site.ShowObject('View_Options',true);
	//Site.ShowLoading('loadingglobal',false);
	Site.switchView('View_Options',true);
	Site.getPhotos(0,30,'s', '',true, 'OptionsPhotoEnvironment');
	}*/


 ltrim = function(s) {

	try{return s.replace(/^\s+/, "")}catch(err){return s}
  
}

rtrim = function(s) {
	
	try{  return s.replace(/\s+$/, "")}catch(err){return s}
   
}

trim = function (s) {
   return rtrim(ltrim(s));
}


// HIDE LOADING CODE. IT MUST BE CALLED FROM: BODY ONLOAD 
Site.hideLoading = function(){Site.get('loading').setVisible(false,true);}



Site.updateNearby = function(){
	var z = Site.Map.map.getZoom();
	if(z>6){
		//S.getEntornoFotos(0);
//		Site.getPOI();
//		Site.clickPOI();
		//S.getPublicidad();
	}
}


Site.pause = function(millis) 
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); } 
while(curDate-date < millis);
} 

Site.SocialButtons = function(){
	return '';
	/*
	return '<img onclick="alert(\''+ Site.Locale.get('lbl_coming_soon')+'\');" title="'+ 
				Site.Locale.get('lbl_coming_soon')+'" src="/img/baloon.jpg">  <img onclick="alert(\''+ 
				Site.Locale.get('lbl_coming_soon')+'\');" title="'+ Site.Locale.get('lbl_coming_soon')+
				'" src="/img/sharethis.gif">  <img onclick="alert(\''+ Site.Locale.get('lbl_coming_soon')+'\');" title="'+ 
				Site.Locale.get('lbl_coming_soon')+'" src="/img/favoritesinactive.gif">';
	*/
	}


function showLightbox() {
  document.getElementById('over').style.display='block';
  document.getElementById('fade').style.display='block';
}
function hideLightbox() {
  document.getElementById('over').style.display='none';
  document.getElementById('fade').style.display='none';
}
/////////////////////////////////////////////	INCLUDES DENTRO DE JS
Site.include=function(){
    return function(Src){
        var sc=document.createElement('script');
        sc.type='text/javascript';
        sc.src=Src;
        document.getElementsByTagName('body')[0].appendChild(sc);
        sc=null;
    }
}();

///////////////////////////////////

Site.fncComunas=function() {

   var extent = Site.Map.map.getExtent();

           Site.comPbyextent.get({
                   xmin: extent.left
                   ,xmax: extent.right
                   ,ymin: extent.bottom
                   ,ymax: extent.top
                   }
                   ,function(json){
                       //alert(json.comunasbyextend[0].FOTO)
                       eval("var layerCapa = Site.Map.map.getLayer('lyrCapaComuna', 'marker');");

                       if (layerCapa != undefined) {
                           eval("Site.Map.map.removeAllMarkers('lyrCapaComuna', 'marker');");
                           //eval("var layerCapa = Site.Map.map.getLayer('lyrCapaComuna', 'marker');");

                       }/*else {
                           eval("var layerCapa = Site.Map.map.addLayer('lyrCapaComuna', 'marker');")


                       }*/
                       eval("var layerCapa = Site.Map.map.addLayer('lyrCapaComuna', 'marker');")
                       for(var x = 0;x<json.totalCount;x++){
                       var w = json.comunasbyextend[x].NOMBRE.length * 25;
                       var h = 50 ;

                       var lonlat = new MapCity.Maps.LonLat(json.comunasbyextend[x].LONGITUD, json.comunasbyextend[x].LATITUD);
                       var icon = new MapCity.Maps.Icon(
                       json.comunasbyextend[x].FOTO,
                       new MapCity.Maps.Size(w,h));

                       var size = new MapCity.Maps.Size(w,h);


                       var marker = new MapCity.Maps.Marker(
                                   lonlat
                                   ,icon
                       );

                       icon.imageDiv.style.cursor = "pointer";
                       //icon.imageDiv.title=json.nombre_pyme;
                       Site.Map.map.addMarker(layerCapa,marker);

                       /*OpenLayers.Event.observe(icon.imageDiv,'click',function(e){
                           Site.popupPuntoPyme(json,i);
                       Event.stop(e);
                       });*/
                       }

                   });
}
