var all_items = new Array();
var map;
var home_center;
var home_zoom;
var select_marker_api;
var marker_counter;
var geonames_marker_counter;
var geonames_center_lat;
var geonames_center_lng;
var global_media_url;
var global_base_url;
var global_pano_media_url;
var hotels_marker_counter;
var SIGNAL = 0;
var STREET_VIEW_ACTIVED = false;
var previous_tag = null;
var previous_username = null;
var previous_json_items = 0;
var tag_view = null;
var user_view = null;

/* 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////                   

            -> This function is hacked for the intialization of the apis:
            -> google needs the points to be added last
            -> multimap needs an original point to add. AutocenterAndZoom seems not to work 
            -> freeearth does not suppor setZoom                       

/////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/

function load_mabs_map(api, size, map_sat_hyb_ge, controlcm, controlcs, controlct, color, minlat, maxlat, minlong, maxlong, place_zoom){
    /*
        This function is hacked for the intialization of the apis:
            -> google needs the points to be added last
            -> multimap needs an original point to add. AutocenterAndZoom seems not to work 
            -> freeearth does not suppor setZoom
    */
    select_marker_api = api //neccesary for Nearest items in single_item_view to call select_item(id) 
    map = new Mapstraction('map',api);
	//map.debug = true;
    pan = true;
    
    if ((home_zoom != null) || (home_zoom != 0)){ zoom = home_zoom; }else{ zoom = size;}
    scale = true;
    map_type = true;
    
    if (controlcm == null || controlcm == 0){ pan = false; zoom = '';} else { pan = true;}
    if (controlcs == null || controlcs == 0){ scale = false; } else { scale = true; }
    if (controlct == null || controlct == 0){ map_type = false; } else { map_type = true; }
	if ((api == 'multimap')|| (api == 'mapquest')) {init_point = new LatLonPoint(0,0);map.setCenterAndZoom(init_point,2);}
	if ((size != null  ) && (zoom != '')){map.addControls({ pan: true, zoom: 'large', overview: false, scale: scale, map_type: map_type}); }
	else{map.addControls({ pan: pan , zoom: zoom , overview: false, scale: scale, map_type: map_type});}
	if ((api != 'multimap')||(api != 'mapquest') || (cover_center == null)){map.autoCenterAndZoom();}
	if ((api !='mapquest')&& (api != 'freeearth')){
	    if (map.getZoom() < 1){
            map.setZoom(1);	
    	}
    }
    
    if (place_zoom != undefined)
    {
        load_mabs_items_to_place(api, color, minlat, maxlat, minlong, maxlong, place_zoom);
    }
    else
    {
        load_mabs_items(api, color);        
    }
    
    if (api == 'google')
	{
	    map.maps[map.api].enableScrollWheelZoom();
	     // size is a number we must parse it 
	     size = parseInt(size);  
	     // else in item view we could'nt do zoom , because zoom is undefined
	     if (size > 0){
	         map.setZoom(size);
         }  
         
	     if (map_sat_hyb_ge == "m"){
               map.setMapType(Mapstraction.ROAD);
          }
         else if (map_sat_hyb_ge == "s"){
              map.setMapType(Mapstraction.SATELLITE);      
          }
         else if (map_sat_hyb_ge == "h"){
               map.setMapType(Mapstraction.HYBRID); 
          }
         else if (map_sat_hyb_ge == "ge"){
               // ########################################################
               // Mapstraction functions called directly 
               //#######################################################
               map.setMapType(Mapstraction.ROAD);
               map.maps[map.api].setMapType(G_SATELLITE_3D_MAP);
          }
        else{
               map.setMapType(Mapstraction.ROAD); 
               map.maps[map.api].addMapType(G_SATELLITE_3D_MAP);
          }
          if (map_sat_hyb_ge == "moon"){
               map.addControls({ pan: true, zoom: 'large', overview: false, scale: true, map_type: false});
               //map.maps[map.api].addMapType(G_MOON_VISIBLE_MAP);
               //map.maps[map.api].setMapType(G_MOON_VISIBLE_MAP);
               map.maps[map.api].removeMapType(G_NORMAL_MAP);
               map.maps[map.api].removeMapType(G_SATELLITE_MAP);
               map.maps[map.api].removeMapType(G_HYBRID_MAP);
               //map.maps[map.api].setMapType(G_MOON_MAP_TYPES);
               //map.setMapType(Mapstraction.HYBRID); 
               map.maps[map.api].addMapType(G_MOON_VISIBLE_MAP);
               map.maps[map.api].setMapType(G_MOON_VISIBLE_MAP);
         }     
        map.add_google_ads();  
	}
	
	
    $("#pastearea").click( function(){
        this.focus();
        this.select();
    });
}

function load_mabs_items(api, color){
	all_items_length = all_items.length;
	marker_counter = all_items_length;
   
	for (i=0; i< all_items_length; i++)	{
		temp = all_items[i] //.pop();
		
		if (temp instanceof Marker){
			map.addMarkerWithData(temp);
		}
		else if (temp instanceof Polyline) 
		{
			if (api!= 'freeearth')	{
			    map.addPolyline(temp);
			 }
		}
        else if (temp instanceof Polygon){
			if (api!= 'freeearth'){
			    // DON'T EXIST ADDPOLYGON in Mapstraction 
			    map.addPolyline(temp); 
            }
		}
	}
	if (home_center != null) {map.setCenterAndZoom(home_center,home_zoom); }
	else {map.autoCenterAndZoom();}
}

function load_mabs_items_to_place(api, color, minlat, maxlat, minlong, maxlong, zoom){
	all_items_length = all_items.length;
	marker_counter = all_items_length;
   
	for (i=0; i< all_items_length; i++)	{
		temp = all_items[i] //.pop();
		
		if (temp instanceof Marker){
			map.addMarkerWithData(temp);
		}
		else if (temp instanceof Polyline) 
		{
			if (api!= 'freeearth')	{
			    map.addPolyline(temp);
			 }
		}
        else if (temp instanceof Polygon){
			if (api!= 'freeearth'){
			    // DON'T EXIST ADDPOLYGON in Mapstraction 
			    map.addPolyline(temp); 
            }
		}
	}
	
    bounds = new BoundingBox(minlat,minlong,maxlat,maxlong);
    map.setBounds( bounds );
    if (zoom != 0)
    {
        map.setZoom(zoom);
    }
}

function load_mabs_kml(api,size,url){
    load_mabs_map(api, size);
    map.removeAllMarkers();
    map.removeAllPolylines();
    GLog.write('remove all');
    map.addOverlay("http://tagzania2.cs/kmldata/user/txus");
}


// ==================== common function for all API calls =====================
//=============================================================================

function gebi(id) {return document.getElementById(id);}

function json(url, querystring){
  var jstag=document.createElement("script");
  jstag.setAttribute("type", "text/javascript");
  jstag.setAttribute("src", url+'?'+querystring);
  document.getElementsByTagName("head")[0].appendChild(jstag);
}

//========================= bubble action ============================================
function item_openbubble(id){
    map.markers[id].openBubble();
}      

function item_closebubble(){    
    map.maps[map.api].closeInfoWindow();
}    

//==============================================================

var SAVE_ICON_SIZE = ''; // only needed in search view

function select_item(id){

    iconUrl = map.markers[id].iconUrl; 
    new_icon_url = iconUrl.replace("placemarkers_small_grey", "placemarkers");
    map.markers[id].proprietary_marker.setImage(new_icon_url); 
}      

function deselect_item(id){
    
    icon_url = map.markers[id].iconUrl;
    map.markers[id].proprietary_marker.setImage(icon_url); 
}              


function select_item_geobus(id){

    iconUrl = map.markers[id].iconUrl;
    new_icon_url = iconUrl.replace("placemarkers_big", "placemarkers_big_grey");
    map.markers[id].proprietary_marker.setImage(new_icon_url); 
}      

function deselect_item_geobus(id){
    
    icon_url = map.markers[id].iconUrl;
    map.markers[id].proprietary_marker.setImage(icon_url); 
}             

function select_place_geobus(id_icon, id_place){
    iconUrl = map.markers[id_icon].iconUrl;
    map.polylines[id_place].proprietary_polyline.setFillStyle({color:"ff6600"}); 
    new_icon_url = iconUrl.replace("placemarkers_big", "placemarkers_big_grey");
    map.markers[id_icon].proprietary_marker.setImage(new_icon_url); 
}      

function deselect_place_geobus(id_icon, id_place){
    icon_url = map.markers[id_icon].iconUrl;
    map.polylines[id_place].proprietary_polyline.setFillStyle({color:"#cccccc"});
    map.markers[id_icon].proprietary_marker.setImage(icon_url); 
}             
/* 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////                       VISIBILITY FUNTIONS                       /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/

function marker_visible(count){ 
    SIGNAL = 0;
    //GEvent.clearListeners(map.maps[map.api], "dragend");
    removeTagzaniaElementsListener();
    all_counter = map.markers.length - 1; 
    
    for(i=0; i< count ; i++){
        map.markers[i].show();
    }
    
    all_poly_counter = map.polylines.length; 
    for(i = 0; i < all_poly_counter ;i++){
        map.polylines[i].show();
    }
     
    for(i= all_counter; i >= count ; i--){
         map.removeMarker(map.markers[i]);
    }

    all_poly_counter = map.polylines.length; 
    for(i= 0; i < all_poly_counter ;i++){
       map.polylines[i].proprietary_polyline.show();
    }
    map.autoCenterAndZoom();
    GEvent.clearListeners(map.maps[map.api], "dblclick");
}



function marker_invisible(near){
    all_poly_counter = map.polylines.length; 
    for(i = 0; i < all_poly_counter ;i++){
       map.polylines[i].hide();
    }
    
    all_counter = map.markers.length - 1; 
    if (near == true){
        // only used in near views
        for(i=0; i<= all_counter; i++){
            map.markers[i].hide();
        }
    }else{
        for(i=1; i<= all_counter; i++){
            map.markers[i].hide();
        }
    }
    
    
}



/* 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////                       SEARCH VIEW ITEM VISIBLE CONTROL                        /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/


function search_marker_visible(tz_visible_counter, tz_search_polygon_counter ){ 
    GEvent.clearListeners(map.maps[map.api], "dragend");
    all_counter = map.markers.length; 
    item_counter = tz_visible_counter;
     
    all_counter = map.markers.length; 
    for(i = 0; i < all_counter ;i++){
        map.markers[i].hide();
     }
    
    for(i= 0; i < item_counter ;i++){
       map.markers[i].show();
    }
    
    all_poly_counter = map.polylines.length; 
    for(i= 0; i < all_poly_counter ;i++){
       map.polylines[i].proprietary_polyline.show();
    }
    
    center_points = map.markers.slice(0,item_counter);
    map.centerAndZoomOnMarkers( center_points );
}

Mapstraction.prototype.centerAndZoomOnMarkers = function(markers)
{
    var bounds = new GLatLngBounds(markers[0].proprietary_marker.getPoint(), markers[0].proprietary_marker.getPoint());
    var i;
    for (i=1; i<markers.length; i++) {
        bounds.extend(markers[i].proprietary_marker.getPoint());
    }
    var lat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2.0;
    var lng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2.0;
    if(bounds.getNorthEast().lng() < bounds.getSouthWest().lng()){
      lng += 180;
    }
    var center = new GLatLng(lat,lng)
    map.maps[map.api].setCenter(center, map.maps[map.api].getBoundsZoomLevel(bounds)-1);
}


function search_marker_invisible(tz_visible_counter, user_visible_counter, user_search_polygon_counter){
     all_counter = map.markers.length; 
     for(i = user_visible_counter; i < all_counter  ;i++){
        map.markers[i].hide();
     }
     
     all_poly_counter = map.polylines.length; 
          
     for(i = user_search_polygon_counter; i < all_poly_counter ;i++){
        map.polylines[i].hide();
     }
     
     total_counter = tz_visible_counter + user_visible_counter;
    center_points = map.markers.slice(tz_visible_counter,total_counter);
    map.centerAndZoomOnMarkers( center_points );
}


function search_geonames_visible( ){ 
    GEvent.clearListeners(map.maps[map.api], "dragend");
    all_counter = map.markers.length; 
    
    for(i= 0; i < all_counter ;i++){
       map.markers[i].show();
    }
    all_poly_counter = map.polylines.length; 
    for(i= 0; i < all_poly_counter ;i++){
       map.polylines[i].proprietary_polyline.show();
    }
    map.autoCenterAndZoom();
}


function search_hotels_visible(){ 
    //GEvent.clearListeners(map.maps[map.api], "dragend");
    
    all_counter = map.markers.length; 
    item_counter = all_counter - geonames_marker_counter - hotels_marker_counter;
    
    for(i = 1; i < all_counter ;i++){
        map.markers[i].hide();
     }
     
    
    for(i= 0; i < item_counter ;i++){
        map.markers[i].show();
    }
    
    start_counter = all_counter - hotels_marker_counter;
    for(i= start_counter; i < all_counter ;i++){
        map.markers[i].show();
    }
    
    all_poly_counter = map.polylines.length; 
    for(i= 0; i < all_poly_counter ;i++){
       map.polylines[i].proprietary_polyline.hide();
    }
    
    center_points = map.markers.slice(0,item_counter);
    hotels_points = map.markers.slice(start_counter, all_counter);
    
    //map.centerAndZoomOnMarkers( hotels_points );
}



/* 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////                       GEONAMES API                        /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/

function getGeonames(search_value, media_url, geonames_username) {
  global_media_url = media_url  
  gebi('places_geonames').innerHTML='<img src="'+media_url+'/img/loader.gif" ></img>';
  url = 'http://ws.geonames.net/searchJSON';
  qs = 'maxRows=10&q='+ search_value +'&callback=getGeonamesOk&username='+ geonames_username;
  
  //$.ajax and getJSOn don't function to geonames for geonames json data structure! 
  json(url,qs);
  return false;
}       

function getGeonamesOk(geonames) {
  gebi('places_geonames').innerHTML='';
  geonames_marker_counter = geonames.geonames.length;
  if (geonames.geonames.length > 0){
      for (i = 0; i < geonames.geonames.length; i++) {
        
        lat = geonames.geonames[i].lat;
        lng = geonames.geonames[i].lng;
        geonameId = geonames.geonames[i].geonameId;
        place_name = geonames.geonames[i].name;
        link_place_name = place_name.replace(" ", "%20");
        country_name = geonames.geonames[i].countryName;
        link_country_name = country_name.replace(" ", "%20");
        admin_name = geonames.geonames[i].adminName1;
        link_admin_name = admin_name.replace(" ", "%20");
        //that charge in /search/tzsearch_geonames.html
        //text = '<ul id="searchnavlist"><li><span><a class="location_link" href="/near/'+ lat+'/'+lng+'/'+geonameId+'/'+place_name +'/' + country_name + '/' +admin_name +' >'+ place_name+' ('+country_name+ ')</a></span> </li></ul>';
       text = '<ul id="searchnavlist"><li><span><a class="location_link" href="/near/'+ lat+'/'+lng+'/?place_name='+link_place_name +'&country_name=' + link_country_name + '&admin_name=' +link_admin_name +'>'+ place_name+' ('+country_name+ ')</a></span> </li></ul>';
       $(text).appendTo('#places_geonames');
       var temp;
       //alert("hastera doa:" + lat + " // " + lng);
        temp = new Marker(new LatLonPoint(parseFloat(lat),parseFloat(lng)));
        
        temp.setInfoBubble('<div ><h3><a class="location_link" href="/near/'+ lat+'/'+lng+'/?place_name='+link_place_name +'&country_name=' + link_country_name + '&admin_name=' +link_admin_name +' >'+ place_name+' ('+country_name+ ')</a></h3></div>');
        
        temp.setIcon(global_media_url + 'img/placemarkers_small/search.png', [19, 24], [9, 22]);
        
        temp.setShadowIcon(global_media_url + 'img/placemarkers_small/shadow.png', [27, 34]);
        temp.setLabel(place_name+' ('+country_name+ ')');
        
        map.addMarker(temp);
        map.autoCenterAndZoom();
      }
  }
  else{
      //if don't have results pass to nearest tagzania results
      toggleTab("nearest_places");
  }    
      geonames_center_lat = geonames.geonames[0].lat;
      geonames_center_lng = geonames.geonames[0].lng;
      
}



/* 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////                       TAGZANIA PANORAMIO API                       /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/


function getPanoramioOk(photos) {
    all_counter = map.markers.length-1; 
    marker_counter =  all_counter;
    gebi('photos_panoramio').innerHTML='';
   
    all_counter = map.markers.length; 
    marker_counter =  all_counter;
    
    for (i = 0; i < photos.photos.length; i++){
       obj = gebi('photos_panoramio');
       a = document.createElement('a');
       counter = marker_counter + i;
       a.href = "javascript:void(0);map.markers["+counter+"].openBubble()";
       a.onclick = "javascript:void(0);map.markers[i].openBubble()";
       p = document.createElement('span');
       title = photos.photos[i].photo_title;
       photo_title = title.toLowerCase();
       sometext = document.createTextNode(photo_title);
       p.appendChild(sometext);
       
       img = document.createElement('img');
       photo_url = photos.photos[i].photo_file_url.replace(/small/, "thumbnail")
       img.src=photo_url; //photos.photos[i].photo_file_url;    
       img.title = photos.photos[i].photo_title;
       
       obj.appendChild(a);       
       
       a.appendChild(img);
       a.appendChild(p); 
       
       createMarker(photos.photos[i], i);
    }
  
}

function getPanoramio(media_url, not_center) {
  item_closebubble();
  global_pano_media_url = media_url;
  if (not_center == null ){
      if ( home_center != null ){map.setCenterAndZoom(home_center,home_zoom);}
  }  
  bounds = map.maps[select_marker_api].getBounds();
  sw = bounds.getSouthWest();
  ne = bounds.getNorthEast();
  minlat = sw.lat();
  minlng = sw.lng();
  maxlat = ne.lat();
  maxlng = ne.lng();
    /*
      == PANORAMIO==
    for "order" you can use:
        * popularity
        * upload_date
    for "set" you can use:
        * public (popular photos)
        * full (all photos)
    for "size" you can use:
        * original
        * medium (default value)
        * small
        * thumbnail
        * square
        * mini_square
    */
  gebi('photos_panoramio').innerHTML= '<img src="'+media_url+'/img/loader.gif" ></img>';
  url = 'http://www.panoramio.com/map/get_panoramas.php';
  qs = 'order=popularity&set=public&from=0&to=20&minx='+minlng+'&miny='+minlat+'&maxx='+maxlng+'&maxy='+maxlat+'&size=small&callback=getPanoramioOk';
  json(url,qs);
}      

function createMarker(photo, i){
    temp = new Marker(new LatLonPoint( photo.latitude,photo.longitude));
    photo_url_to_post = photo.photo_file_url.replace(/small/, "medium")
    photo_url_to_bubble = photo.photo_file_url.replace(/small/, "medium")
    temp.setInfoBubble('<div class="bubble_panoramio" ><div  class ="clearfix"><img  src ="http://www.panoramio.com/img/panoramio-marker.png" heigth="10" weigth="10"> ' + photo.photo_title +'</div><a href="'+photo.photo_url+'" ><img src ="'+ photo_url_to_bubble + '" width = "' +photo.width+ '"  height = "'+photo.height+'"></img></a><p><a class="b_title" href="'+photo.photo_url +'"> <span>link</span></a> | <a class="b_title" href=\"/near/' + photo.latitude + '\/'+photo.longitude+'"><span>Search nearby</span></a> | <a class="b_title" href="/post?lat='+ photo.latitude +'&long='+photo.longitude+'&resources='+photo_url_to_post+'&title='+photo.photo_title+'"><span>add</span></a></p></div>');
 	photo.photo_file_url = photo.photo_file_url.replace(/small/, "mini_square")
	temp.setIcon(photo.photo_file_url,[44,44], [16,16]);
	map.addPanoramioMarker(temp);    
}
Mapstraction.prototype.addPanoramioMarker = function(marker) {
  var map = this.maps[this.api];
  marker.mapstraction = this;
  marker.api = this.api;
  marker.map = this.maps[this.api];
  if(this.loaded[this.api] === false) {
    self = this;
    this.onload[this.api].push( function() { self.addPanoramioMarker(marker); } );
    return;
  }

  var gpin = marker.toPanoramio();
  marker.setChild(gpin);
  map.addOverlay(gpin);
  this.markers.push(marker); 
};

Marker.prototype.toPanoramio = function() {
	
	var func_icon = new GIcon();
        func_icon.image = this.iconUrl;
        func_icon.iconSize = new GSize(44, 44);
        func_icon.shadowSize = new GSize(41, 30);
        func_icon.iconAnchor = new GPoint(6, 20);
        func_icon.infoWindowAnchor = new GPoint(5, 1);
        var options = {};
        options.icon = func_icon;
      var gmarker = new GMarker( this.location.toGoogle(),options);
	
  if(this.infoBubble){
    var theInfo = this.infoBubble;
    var event_action;
    if(this.hover) {
      event_action = "mouseover";
    }
    else {
      event_action = "click";
    }
    GEvent.addListener(gmarker, event_action, function() {
      gmarker.openInfoWindowHtml(theInfo, {maxWidth: 100});
    });
  }
	
  if(this.hoverIconUrl){
    GEvent.addListener(gmarker, "mouseover", function() {
      gmarker.setImage(this.hoverIconUrl);
    });
    GEvent.addListener(gmarker, "mouseout", function() {
      gmarker.setImage(this.iconUrl);
    });
  }
	
  if(this.infoDiv){
    var theInfo = this.infoDiv;
    var div = this.div;
    var event_action;
    if(this.hover) {
      event_action = "mouseover";
    }
    else {
      event_action = "click";
    }
    GEvent.addListener(gmarker, event_action, function() {
      document.getElementById(div).innerHTML = theInfo;
    });
  }
	
  return gmarker;
};



/* 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////                       GEONAMES HOTELS API                       /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/

function getHotelsOk(hotels) {
  
    
  item_closebubble();
  all_counter = map.markers.length-1; 
  iconUrl = $("#selected_hotel_icon").val();   
  gebi('hotels_geonames').innerHTML='';
 
  bounds = map.maps[select_marker_api].getBounds();
  sw = bounds.getSouthWest();
  ne = bounds.getNorthEast();
  minlat = sw.lat()
  minlng = sw.lng()
  maxlat = ne.lat()
  maxlng = ne.lng()
  near_icon_size = [19,24]
  near_icon_shadow_size = [24,30]
  near_icon_anchor = [9,22]
  center_lat = (minlat+maxlat) /2;
  center_lng = (minlng + maxlng) /2;
  
  
  all_counter = map.markers.length; 
  marker_counter =  all_counter;
  icon_base_url = global_media_url + "/img/placemarkers_small/" 
 
 hotels_marker_counter = hotels.hotels.length;
 if (hotels.hotels.length > 0)
 {
  for (i = 0; i < hotels.hotels.length; i++){
     counter = all_counter + i ;
     text = '<ul><li class="item POINT clearfix" id="tzitem_'+counter+'"><a class="item_placemarker location_link" onclick = "map.markers['+counter+'].openBubble()" href="javascript:map.markers['+counter+'].openBubble()" ><img src="'+icon_base_url+'hotel.png">'+hotels.hotels[i].hotelName+' ('+hotels.hotels[i].placeName + ') '+ '</a></li></ul>';
     $(text).appendTo('#hotels_geonames');
     temp = new Marker(new LatLonPoint( hotels.hotels[i].lat, hotels.hotels[i].lng));
     temp.setInfoBubble('<div class="bubble"><a href="'+hotels.hotels[i].bookingURLs[0].bookingURL+'" >'+hotels.hotels[i].hotelName + '<p><img src ="'+hotels.hotels[i].imageURL + '" width= "80" heigth = "80"></img></p></a><p>'+hotels.hotels[i].address +' (' +hotels.hotels[i].placeName +')</p><p><a href="'+hotels.hotels[i].bookingURLs[0].bookingURL+'" >See this hotel </a> | <a class="b_title" href=\"/near/' + hotels.hotels[i].lat + '\/'+hotels.hotels[i].lng +'">Search nearby</a> | <a class="b_title" href="/post?lat='+ hotels.hotels[i].lat +'&long='+hotels.hotels[i].lng +'&title='+hotels.hotels[i].hotelName +'">add</a></p></div>');
     temp.setIcon(icon_base_url + 'hotel.png', near_icon_size, near_icon_anchor);
     temp.setShadowIcon(icon_base_url +'shadow.png', near_icon_shadow_size);
     map.addMarker(temp);
  }
  link_text = '<p class="meta_author" /><p><em><a href="http://www.booking.com/searchresults.html?aid=316513&latitude=' + center_lat +'&longitude=' + center_lng + '&radius=50" onmousedown="pageTracker._trackPageview(\'/Events/tzitem/more_hotels_near_button\');">More hotels near</a></em><br></p>';
  $(link_text).appendTo('#hotels_geonames');
  
 }
 search_hotels_visible();
 
}

function getHotels(media_url) {
  
  global_media_url = media_url
  gebi('hotels_geonames').innerHTML='<img src="'+media_url+'/img/loader.gif" ></img>';
  bounds = map.maps[select_marker_api].getBounds();
  sw = bounds.getSouthWest();
  ne = bounds.getNorthEast();
  minlat = sw.lat()
  minlng = sw.lng()
  maxlat = ne.lat()
  maxlng = ne.lng()
  center_lat = (minlat+maxlat) /2;
  center_lng = (minlng + maxlng) /2;
  
  window.location = "http://www.booking.com/searchresults.html?aid=316513&latitude=" + center_lat +"&longitude=" + center_lng + "&radius=50"

  //url = 'http://ws5.geonames.org/findNearbyHotelsJSON' //'http://www.panoramio.com/map/get_panoramas.php';
  //qs = 'lat='+center_lat+'&lng='+center_lng+'&username=luistxo&callback=getHotelsOk' //'order=popularity&set=public&from=0&to=20&minx='+minlng+'&miny='+minlat+'&maxx='+maxlng+'&maxy='+maxlat+'&size=thumbnail&callback=getPanoramioOk';
  //http://ws.geonames.org/hotelsBBox?north=44.1&south=-9.9&east=-22.4&west=55.2
  /*
  url = 'http://ws5.geonames.org/hotelsBBoxJSON';
  qs = 'north=' + maxlat +'&south='+ minlat +'&east='+ maxlng +'&west='+ minlng + '&username=luistxo&callback=getHotelsOk';
  json(url,qs);
  */
}       

function addPanoramioListener(){
    GEvent.clearListeners(map.maps[map.api], "dragend");
    GEvent.addListener(map.maps[map.api], "dblclick", function(){ getPanoramio(global_pano_media_url, true); });
}
function addHotelsListener(){  
    GEvent.clearListeners(map.maps[map.api], "dragend");
    GEvent.addListener(map.maps[map.api], "dragend", function(){  getHotels(global_media_url); });
}


/* 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////                       STREET VIEW                        /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/


function get_street_view()
{
    //p=map.markers[3].proprietary_marker;
   // var p = new GLatLng(40.4165,-3.7025); 
  bounds = map.maps[select_marker_api].getBounds();
  sw = bounds.getSouthWest();
  ne = bounds.getNorthEast();
  minlat = sw.lat();
  minlng = sw.lng();
  maxlat = ne.lat();
  maxlng = ne.lng();
  center_lat = (minlat+maxlat) /2;
  center_lng = (minlng + maxlng) /2; 
  if (STREET_VIEW_ACTIVED != true)
  {
     if (GBrowserIsCompatible()) 
     { 
        STREET_VIEW_ACTIVED = true;
        map.maps[map.api].addOverlay(new GStreetviewOverlay()); 
        geocoder = new GClientGeocoder(); 
        var svc = new GStreetviewClient();                           
        var latlong = new GLatLng(center_lat,center_lng);   
        svc.getNearestPanorama(latlong, function(reply){
                    if (reply.code = 200) { 
                            
                            if (reply.Location) {
                                 var html = "<div class=\"header\"><b>"+reply.Location.description+"</div></b>" + "<div class=\"bubble_street_view\"><embed src=\"http://maps.google.com/mapfiles/cb/googlepano.040.swf\" quality=\"high\" bgcolor=\"#EFEFEF\" style=\"width: 100%; height: 270px;\" wmode=\"opaque\" swliveconnect=\"false\" id=\"googlepano\" allowscriptaccess=\"always\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" scale=\"noscale\" salign=\"lt\" flashvars=\"panoId="+reply.Location.panoId+"&amp;directionMap=N:N,W:W,S:S,E:E,NW:NW,NE:NE,SW:SW,SE:SE&amp;yaw=350.08435065836153&amp;zoom=0&amp;browser=3&amp;serverURLPrefix=http://cbk0.google.com/cbk&amp;pitch=10.983050525042998&amp;viewHeight=0.616426117417295\" align=\"middle\"></embed></div>" + "<div class=\"footer\">Copyright: "+reply.Data.copyright+"<br></div>" ; 
                                 var pp = new GLatLng(parseFloat(reply.Location.lat),parseFloat(reply.Location.lng)); 
                                 item_closebubble();
                                 map.maps[map.api].openInfoWindowHtml(pp,html);}
                            else { }
                    } else { GLog.write("Error : "+reply.code);}
                } );            
     }
     else { alert("Sorry, the Google Maps API is not compatible with this browser");STREET_VIEW_ACTIVED = false;}
    
     var svc = new GStreetviewClient(); 
     GEvent.addListener(map.maps[map.api],"click",function(overlay,latlong) 
     { 
        if (latlong){ 
            svc.getNearestPanorama(latlong, function(reply){
                    if (reply.code = 200) { 
                            
                            if (reply.Location) {
                                 var html = "<div class=\"header\"><b>"+reply.Location.description+"</div></b>" + "<div class=\"bubble_street_view\"><embed src=\"http://maps.google.com/mapfiles/cb/googlepano.040.swf\" quality=\"high\" bgcolor=\"#EFEFEF\" style=\"width: 100%; height: 270px;\" wmode=\"opaque\" swliveconnect=\"false\" id=\"googlepano\" allowscriptaccess=\"always\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" scale=\"noscale\" salign=\"lt\" flashvars=\"panoId="+reply.Location.panoId+"&amp;directionMap=N:N,W:W,S:S,E:E,NW:NW,NE:NE,SW:SW,SE:SE&amp;yaw=350.08435065836153&amp;zoom=0&amp;browser=3&amp;serverURLPrefix=http://cbk0.google.com/cbk&amp;pitch=10.983050525042998&amp;viewHeight=0.616426117417295\" align=\"middle\"></embed></div>" + "<div class=\"footer\">Copyright: "+reply.Data.copyright+"<br></div>" ; 
                                 var pp = new GLatLng(parseFloat(reply.Location.lat),parseFloat(reply.Location.lng)); 
                                 map.maps[map.api].openInfoWindowHtml(pp,html);}
                            else { }
                    } else { GLog.write("Error : "+reply.code);}
                } );}
     });
   } 
}




/* 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////                       TAGZANIA JSON FUNCTION                        /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/


function getTagzaniaElements(bbox, zoom) {
  
  remove_before_tzitems();
  
  if (tag_view == null){ remove_previous_json_items();}
 
  if (user_view == null){ remove_previous_json_items(); }
  else{ username = previous_username; }
  
  /*
  if ((tag != '' || tag != null) && (username != '' || username != null)){ 
      // only for user view
      if (tag){previous_tag = tag;}  
      else{if (previous_tag){tag=previous_tag;}}
      if (username){previous_username = username;}
      else{if (previous_username){previous_username=previous_username;}}
  }
  else
  {
      //only tag and point view
      if (tag){previous_tag = tag; previous_username = null;}
      else{ 
          if (previous_tag){tag=previous_tag;} 
      }    
      if (username){previous_username = username;previous_tag = null;}
      else{if (previous_username){previous_username=previous_username;}}
  }
  */
  
  item_closebubble();
  gebi('tagzania_list').innerHTML='';
  
  if (bbox){
      
      bbox = bbox.split(',');
      minlat = parseFloat(bbox[0]);
      minlng = parseFloat(bbox[1]);  
      maxlat = parseFloat(bbox[2]);
      maxlng = parseFloat(bbox[3]);   
      bounds =  new BoundingBox(minlat, minlng, maxlat, maxlng);
      
      bounds =  minlat + ',' +minlng + ',' + maxlat + ',' + maxlng ;
      //map.maps[select_marker_api].setBounds(bounds);
      var lat = (maxlat + minlat) / 2;
      var lng = (maxlng + minlng) / 2;
      var center = new GLatLng(lat,lng);
      
      map.maps[select_marker_api].setCenter(center, zoom);
       
  }else{
      bounds = map.maps[select_marker_api].getBounds();
      sw = bounds.getSouthWest();
      ne = bounds.getNorthEast();  
      minlat = sw.lat();
      minlng = sw.lng();
      maxlat = ne.lat();
      maxlng = ne.lng();
  }
  
      
  if (zoom){zoom_level = zoom;}
  else{zoom_level = map.maps[select_marker_api].getZoom();}
  
  bounds = replaceAll(String(bounds),'(','');
  bounds = replaceAll(String(bounds),')','');
      
  new_url = window.location.href + 'bbox=' + bounds + '&zoom='+ zoom_level;// + '&username='+ previous_username + '&tag=' + previous_tag;
  
  new_hash = '#bbox=' + bounds + '&zoom='+ zoom_level;// + '&username='+ previous_username + '&tag=' + previous_tag;
 
 
  window.location.hash = new_hash;
  
  $("#permalink").attr('href', window.location.href);
  
  refresh_links_href(new_hash);  
  
  bbox="" +minlng+','+minlat+','+maxlng+','+maxlat + ""
  url =  global_base_url + '/json/?bbox='+minlat+','+minlng+','+maxlat+','+maxlng; 
  
  if (((previous_tag != null)&&(previous_tag != '')) && ((previous_username != null)&&(previous_username != '')))
  { 
      $.getJSON(url,{username:previous_username, tag:previous_tag}, getTagzaniaElementsOK); 
  }
  else
  {
      if (previous_username != null) 
      {
          $.getJSON(url,{username:previous_username}, getTagzaniaElementsOK); //getTagzaniaElementsUsernameOK
      }
      else if (previous_tag != null)
      {
          $.getJSON(url,{tag:previous_tag}, getTagzaniaElementsOK);
      }
      else
      {
          $.getJSON(url, getTagzaniaElementsOK);
      }
  }
  return false;
}       

function getTagzaniaElementsOK(data) {  
  
    if ( data.count > 0 )
    {
      item_closebubble();
      all_counter = map.markers.length-1; 
      bounds = map.maps[select_marker_api].getBounds();
      sw = bounds.getSouthWest();
      ne = bounds.getNorthEast();
      minlat = sw.lat()
      minlng = sw.lng()
      maxlat = ne.lat()
      maxlng = ne.lng()
      near_icon_size = [19,24]
      near_icon_shadow_size = [24,30]
      near_icon_anchor = [9,22]
      center_lat = (minlat+maxlat) /2;
      center_lng = (minlng + maxlng) /2;
      $.each(data.items, function(i,item){
                  
                  counter = map.markers.length; 
                  marker_counter =  all_counter;
                  icon_base_url = global_media_url + "img/placemarkers_small_grey/" 
                  description = escape(item.extended.substr(0,30));
                  description = description.replace('%20', ' ');
                  
                  if (description == 'null'){description = '';}
                  
                  title = item.title.replace("'", "\\'");
                  image = item.resources_img;
                  
                  if (image == 'null'){image = '';}
                  
                  text = '<ul><li class="item ' + item.item_type +' clearfix" id="tzitem_'+counter+'"><a class="item_placemarker" href="javascript:item_openbubble('+counter+');" onmouseover="select_item('+counter+')" onmouseout="deselect_item('+counter+')"><img src="'+icon_base_url+item.icon+'.png">' +title + '</a></li></ul>'
                  $(text).appendTo("#tagzania_list");
                  
                  create_tagzania_element(item, icon_base_url, title, description, image);
                  
                  previous_json_items = previous_json_items +1;
              });
    }
    else
    {
        //advise
        
        text = '<ul><li"><p>There\'s no points here</p><a href="#" onclick = "javascript:tagzaniaZoomOut();">zoom out</a></li></ul>'
        $(text).appendTo("#tagzania_list");
    }
}

/*
function getTagzaniaElementsUsernameOK(data) {  
    
    if ( data.count > 0 )
    {
          item_closebubble();
          all_counter = map.markers.length-1; 
          bounds = map.maps[select_marker_api].getBounds();
          sw = bounds.getSouthWest();
          ne = bounds.getNorthEast();
          minlat = sw.lat()
          minlng = sw.lng()
          maxlat = ne.lat()
          maxlng = ne.lng()
          near_icon_size = [19,24]
          near_icon_shadow_size = [24,30]
          near_icon_anchor = [9,22]
          center_lat = (minlat+maxlat) /2;
          center_lng = (minlng + maxlng) /2;
          
          //div_text = '<div id="tagzania_list_'+ previous_username +'" class="fieldset"></div>' 
          //$(div_text).appendTo("#user_items_" + previous_username);
                      
          $.each(data.items, function(i,item){
                      counter = map.markers.length; 
                      marker_counter =  all_counter;
                      icon_base_url = global_media_url + "img/placemarkers_small_grey/" 
                      description = escape(item.extended.substr(0,30));
                      description = description.replace('%20', ' ');
                      if (description == 'null'){description = '';}
                      title = item.title.replace("'", "\\'");
                      image = item.resources_img;
                      if (image == 'null'){image = '';}
                      text = '<ul><li id="tzitem_'+counter+'"><a class="item_placemarker" href="javascript:item_openbubble('+counter+');" onmouseover="select_item('+counter+')" onmouseout="deselect_item('+counter+')"><img src="'+icon_base_url+item.icon+'.png">' +title + '</a></li></ul>'
                      $(text).appendTo("#tagzania_list_" + previous_username);
                      create_tagzania_element(item, icon_base_url, title, description, image);
                      previous_json_items = previous_json_items +1;
                  });
    }    
    else
    {
        //advise 
        div_text = '<div id="tagzania_list_'+ previous_username +'" class="fieldset"></div>' 
        $(div_text).appendTo("#user_items_" + previous_username);
        text = '<ul><li"><p>There\'s no points here </p><a href="#" onclick = "javascript:tagzaniaZoomOut();">zoom out</a></li></ul>'
        $(text).appendTo("#tagzania_list_"+ previous_username);
    }                  
}
*/


function addTagzaniaElementsListener(){
    
    remove_before_tzitems();
    removeTagzaniaElementsListener();
    GEvent.addListener(map.maps[map.api], "dragend", function(){ getTagzaniaElements();change_bbox_links_href();});
    GEvent.addListener(map.maps[map.api], "zoomend", function(){ getTagzaniaElements();change_bbox_links_href();});
    change_bbox_links_href();
    /* GEvent.addListener(map.maps[map.api], "zoom", function(oldZoomLevel, newZoomLevel) {
        if(newZoomLevel < 6)
             {
             map.zoomTo(6);} 
        if(newZoomLevel > 7)
	                  {
             map.zoomTo(7);} 
        
       }); 
    */
    
}
function removeTagzaniaElementsListener()
{
    GEvent.clearListeners(map.maps[map.api], "dragend");
    GEvent.clearListeners(map.maps[map.api], "zoomend");
}

function remove_previous_json_items()
{
    if (previous_json_items != 0)
    {
        all_counter = map.markers.length;
        first_json_item = all_counter - previous_json_items;
        for(i = first_json_item; i <= all_counter; i++){map.removeMarker(map.markers[first_json_item]);}    
        previous_json_items = 0;
    }
}
function setMedia_url(media_url, base_url){
    global_media_url = media_url;
    global_base_url = base_url;
}

function create_tagzania_element(item, icon_base_url, title, description, image)
{
    
    if (item.point)
    {
        temp = new Marker(new LatLonPoint( item.lat, item.long));              
        temp.setInfoBubble('<div class="bubble"><h3><img src="'+icon_base_url+item.icon+'.png"/><a class="b_title" href="/pt/'+item.slug+'/" target="_top"> '+title+'</a></h3><div class="clearfix user_media"><ul>'+image+'</ul><p>'+description+'</p></div><div id="user_links"><ul><li>'+item.resources_link+'</li></ul></div><div class="clearfix" id="bubble_links"><ul class="toolbar clearfix"><img src="'+global_media_url+'img/css/bullets/headerPlaceAdd.gif"/><a href="/pt/'+ item.slug+'/add_to_your_map" target="_top"><span>add to your map</span></a></ul></div>');
        temp.setIcon(icon_base_url+item.icon+'.png', near_icon_size, near_icon_anchor);
        temp.setShadowIcon(icon_base_url +'shadow.png', near_icon_shadow_size);
        temp.setLabel(item.title);
        map.addMarker(temp);
    }
    else if (item.line)
    {
        var temp2 = new Array();
        temp = new Marker(new LatLonPoint( item.lat, item.long));              
        temp.setInfoBubble('<div class="bubble"><h3><img src="'+icon_base_url+item.icon+'.png"/><a class="b_title" href="/pt/'+item.slug+'/" target="_top"> '+title+'</a></h3><div class="clearfix user_media"><ul>'+image+'</ul><p>'+description+'</p></div><div id="user_links"><ul><li>'+item.resources_link+'</li></ul></div><div class="clearfix" id="bubble_links"><ul class="toolbar clearfix"><img src="'+global_media_url+'img/css/bullets/headerPlaceAdd.gif"/><a href="/pt/'+ item.slug+'/add_to_your_map" target="_top"><span>add to your map</span></a></ul></div>');
        temp.setIcon(icon_base_url+item.icon+'.png', near_icon_size, near_icon_anchor);
        temp.setShadowIcon(icon_base_url +'shadow.png', near_icon_shadow_size);
        temp.setLabel(item.title);
        map.addMarker(temp);
        
        simple_line = item.simple_line.substring(1, item_simple_line.length-1);
        point_array = simple_line.split(',');
        //((-115.15285491900001, 36.160745955300001), (-115.15113830599999, 36.163517773199999), (-115.151309967, 36.165111524099999), (-115.146417618, 36.172040499200001))
        for(i=0;i<point_array.length; i++)
        {
            temp2.push(point_array[i]);
        }
        
        var poly = new Polyline(temp2)
        poly.setColor('#063bff');
        poly.setOpacity(0.8);
    }
    else
    {
        temp = new Marker(new LatLonPoint( item.lat, item.long));              
        temp.setInfoBubble('<div class="bubble"><h3><img src="'+icon_base_url+item.icon+'.png"/><a class="b_title" href="/pt/'+item.slug+'/" target="_top"> '+title+'</a></h3><div class="clearfix user_media"><ul>'+image+'</ul><p>'+description+'</p></div><div id="user_links"><ul><li>'+item.resources_link+'</li></ul></div><div class="clearfix" id="bubble_links"><ul class="toolbar clearfix"><img src="'+global_media_url+'img/css/bullets/headerPlaceAdd.gif"/><a href="/pt/'+ item.slug+'/add_to_your_map" target="_top"><span>add to your map</span></a></ul></div>');
        temp.setIcon(icon_base_url+item.icon+'.png', near_icon_size, near_icon_anchor);
        temp.setShadowIcon(icon_base_url +'shadow.png', near_icon_shadow_size);
        temp.setLabel(item.title);
        map.addMarker(temp);
        
        simple_polygon = item.simple_polygon.substring(1, item_simple_polygon.length-1);
        point_array = simple_polygon.split(',');
        for(i=0;i<point_array.length; i++)
        {
            temp2.push(point_array[i]);
        }
        
        var poly = new Polyline(temp2)
        poly.setColor('#063bff');
        poly.setOpacity(0.8);
    }
}

function remove_before_tzitems()
{
    $("#user_items_" + previous_username).html('');
    $('#tagzania_list_' + previous_username).html('');
    $('#tagzania_list').html('');
}


function tagzaniaZoomOut()
{
    zoom_level = map.maps[select_marker_api].getZoom();
    map.maps[select_marker_api].setZoom(zoom_level-1);
}

/*
function tagzaniaTagView(tag)
{
    bounds = map.maps[select_marker_api].getBounds();
    sw = bounds.getSouthWest();
    ne = bounds.getNorthEast();  
    minlat = sw.lat();
    minlng = sw.lng();
    maxlat = ne.lat();
    maxlng = ne.lng();
    
    zoom_level = map.maps[select_marker_api].getZoom();
    bounds = minlat + ',' +minlng + ',' + maxlat + ',' + maxlng ;
    //new_url = window.location.href + 'bbox=' + bounds + '&tag=' + tag;
    new_hash = '#bbox=' + bounds + '&zoom='+ zoom_level + '&tag=' + tag;
    //window.location.hash = new_hash;
    window.location.href = 'http://beta.tagzania2.cs/tag/' + tag + new_hash
    
}
*/
/* 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////                       TAGZANIA JSON FUNCTION  - to get permalink parameters                      /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/


function getHashParameters(s) {
      var r = {};
      if (s) {
          var q = s.substring(s.indexOf('#') + 1); // remove everything  up to the ?
          q = q.replace(/\&$/, ''); // remove the trailing &
          jQuery.each(q.split('&'), function() {
              var splitted = this.split('=');
              var key = splitted[0];
              var val = splitted[1];
              // convert numbers
              if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
              // convert booleans
              if (val == 'true') val = true;
              if (val == 'false') val = false;
              // ignore empty values
              if (typeof val == 'number' || typeof val == 'boolean' ||  val.length > 0) r[key] = val;
          });
      }
      return r;
 };


function refresh_links_href(new_hash) { 
    $(".tagUrl").each(function(i){
          url = $(this).attr('bal');
          new_url = url + new_hash
          $(this).attr('href', new_url);
         }); 
}

function change_bbox_links_href() { 
 
  bounds = map.maps[select_marker_api].getBounds();
  sw = bounds.getSouthWest();
  ne = bounds.getNorthEast();  
  minlat = sw.lat();
  minlng = sw.lng();
  maxlat = ne.lat();
  maxlng = ne.lng();
        
  if (zoom){zoom_level = zoom;}
  else{zoom_level = map.maps[select_marker_api].getZoom();}
  
  bounds = replaceAll(String(bounds),'(','');
  bounds = replaceAll(String(bounds),')','');
  
  new_hash = '#bbox=' + bounds + '&zoom='+ zoom_level;// + '&username='+ previous_username + '&tag=' + previous_tag;
  
  $(".tagUrl").each(function(i){
      url = $(this).attr('bal');
      new_url = url + new_hash
      $(this).attr('href', new_url);
     }); 
     
  //new_href = window.location.href; 
  //new_url = new_href + new_hash;
  //$("#permalink").attr('href', new_url);
}
/* 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////                       GLOBAL FUNCTION                       /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/

function replaceAll(OldString, FindString, ReplaceString) {
  var SearchIndex = 0;
  var NewString = ""; 
  while (OldString.indexOf(FindString,SearchIndex) != -1)    {
    NewString += OldString.substring(SearchIndex,OldString.indexOf(FindString,SearchIndex));
    NewString += ReplaceString;
    SearchIndex = (OldString.indexOf(FindString,SearchIndex) + FindString.length);         
  }
  NewString += OldString.substring(SearchIndex,OldString.length);
  return NewString;
}

/* 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////                       GOOGLE ADS                      /////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/
Mapstraction.prototype.add_google_ads = function() {
  var publisher_id = "pub-6294217621555214"; //yourPublisherID;

  var adsManagerOptions = {
    maxAdsOnMap : 2,
    style: 'icon',
    //style: 'adunit',
    // The channel field is optional - replace this field with a channel number 
    // for Google AdSense tracking
    //channel: 'your_channel_id'  
  };

 adsManager = new GAdsManager(map.maps[map.api], publisher_id, adsManagerOptions);
 adsManager.enable();
};


