// Добавение маркера в базу
  function saveData() { 
      var nick = encodeURIComponent(document.getElementById("nick").value);
      var url = encodeURIComponent(document.getElementById("url").value);
      var email = encodeURIComponent(document.getElementById("email").value);
      var name = encodeURIComponent(document.getElementById("name").value);
      var lastname = encodeURIComponent(document.getElementById("lastname").value);
      var rss = encodeURIComponent(document.getElementById("rss").value);
      var twitter = encodeURIComponent(document.getElementById("twitter").value);
      var lj = encodeURIComponent(document.getElementById("lj").value);
      var about = encodeURIComponent(document.getElementById("about_area").value);
		if(undefined===window.marker){
			$("#result").html('Поставьте маркер на карту');
			return false;
		}
		else{
			var latlng = marker.getPosition();
		}
      
 
      var url = window.siteurl + "main/add_marker/?nick=" + nick
      		+ "&url=" + url
      		+ "&email=" + email
      		+ "&name=" + name
      		+ "&lastname=" + lastname 
      		+ "&rss=" + rss
      		+ "&twitter=" + twitter
      		+ "&lj=" + lj
      		+ "&about=" + about
      		+ "&lat=" + latlng.lat() 
      		+ "&lng=" + latlng.lng();
      downloadUrl(url, function(data, responseCode) {
        if (responseCode == 200 && data.length > 1) {
          $("#result").html(data);
        }
      });
    }
  
  
  
  


// Интерфейс 
//-------------------------------------------------------------

	// Окно информации о блоггере
	function showInfoWindow(marker, loaddata){
		if(undefined === window.lastMarker){
		}
		else{
			window.lastMarker.setIcon(window.siteurl + 'images/user_small.png');
			window.lastMarker.setZIndex(window.lastZindex);	
		}
		window.lastZindex = marker.getZIndex(); 
		marker.setIcon(window.siteurl + 'images/user_small_red.png');
		marker.setZIndex(900);
		window.lastMarker = marker;
		var nick = '';
		if (marker.nick.length > 15){
			nick = marker.nick.substring(0, 13) + "...";
		}
		else{
			nick = marker.nick;
		}

		

		$("#profile_link").html('<img class="tab_link_img" src="'+ window.siteurl +'images/icons/blogger.png" /> ' + nick);
		$("#profile_link").css({'display': 'block'});
		window.tabs.click("profile");
	
		
		if(undefined===loaddata){
	     	//$('#third_title').html('<img class="tab_img" src="' + window.siteurl + 'images/icons/blogger.png" width="12" height="12" /> Досье: ' + marker.nick);
			$('#profile .nav_content').html('Загрузка...');
			$.get(window.siteurl + "main/get_blogger_page/" + marker.id, function(data){
			  $('#profile .nav_content').html(data); 
			}); 
		}
	}

    function search() { 
		var text = encodeURIComponent(document.getElementById("text").value);
		var url = window.siteurl + "main/search/" + text;
        downloadUrl(url, function(data, responseCode) {
          if (responseCode == 200 && data.length > 1) {
          	//$('#third_title').html('<img class="tab_img" src="' + window.siteurl + 'images/icons/blogger.png" width="12" height="12" /> Поиск блоггеров');
        	$("#search .nav_content").html(data);
        	$("#search_link").css({'display': 'block'});
        	window.tabs.click("search");
			//$('#accordion').accordion( 'activate' , 2 );
          }
        });
	}
	
    function search_last() {
        downloadUrl(window.siteurl + "main/search_last", function(data, responseCode) {
          if (responseCode == 200 && data.length > 1) {
        	//$('#third_title').html('<img class="tab_img" src="' +  window.siteurl + 'images/icons/blogger.png" width="12" height="12" /> Недавно на карте блоггеров');
            $("#recent .nav_content").html(data);
            $("#recent_link").attr('onClick', '');
			//$('#accordion').accordion( 'activate' , 2 );
          }
        });
	}
    
    function backlinks() {
        downloadUrl(window.siteurl + "main/backlinks", function(data, responseCode) {
          if (responseCode == 200 && data.length > 1) {
        	//$('#third_title').html('<img class="tab_img" src="' + window.siteurl + 'images/icons/blogger.png" width="12" height="12" /> О нас пишут еще');
            data = data + '<div style="float:right">По данным <a href="http://blogs.yandex.ru/search.xml?link=blog-map.ru">поиска по блогам</a></div>'
        	$("#backlinks .nav_content").html(data);
            $("#backlinks_link").attr('onClick', '');
			//$('#accordion').accordion( 'activate' , 2 );
          }
        });
	}
    
    function getPosts($id){
		$('#posts-tab').html('Загрузка...');
		$.get(window.siteurl + "main/get_rss/" + $id, function(data){
		  $('#posts-tab').html(data); 
		});    	
    }

    function getTweets($id){
		$('#tweets-tab').html('Загрузка...');
		$.get(window.siteurl + "main/get_twitter/" + $id, function(data){
		  $('#tweets-tab').html(data); 
		});    	
    }    
    
	function showCode(){
		$('#code').toggle();
	}


//Функции Google Maps 
//-------------------------------------------------------------

	  function codeLatLng() {
		    //var input = document.getElementById("latlng").value;
		    //var latlngStr = input.split(",",2);
		    var lat = "40.714224";
		    var lng = "40.714224";
		    var latlng = new google.maps.LatLng(lat, lng);
		    if (geocoder) {
		      geocoder.geocode({'latLng': latlng}, function(results, status) {
		        if (status == google.maps.GeocoderStatus.OK) {
		          if (results[1]) {
		            map.setZoom(11);
		            marker = new google.maps.Marker({
		                position: latlng, 
		                map: map
		            }); 
		            infowindow.setContent(results[1].formatted_address);
		            infowindow.open(map, marker);
		          } else {
		            alert("No results found");
		          }
		        } else {
		          alert("Geocoder failed due to: " + status);
		        }
		      });
		    }
	  }
	
	

  function codeAddress() {
    var address = document.getElementById("text").value;
    if (geocoder) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          map.setCenter(results[0].geometry.location);
		  map.setZoom(12);
        } else {
          alert("Нет такого места на свете");
        }
      });
    }
	}
  
  //Привязываем Окно информации о блогере к маркеру
  function bindInfoWindow(marker, map) {
    google.maps.event.addListener(marker, 'click', function() {

      showInfoWindow(marker);
        
    });
  }  
  
//google maps funcs
  function downloadUrl(url, callback) {
    var request = window.ActiveXObject ?
        new ActiveXObject('Microsoft.XMLHTTP') :
        new XMLHttpRequest;

    request.onreadystatechange = function() {
      if (request.readyState == 4) {
        request.onreadystatechange = doNothing;
        callback(request.responseText, request.status);
      }
    };

    request.open('GET', url, true);
    request.send(null);
  }

  function parseXml(str) {
    if (window.ActiveXObject) {
      var doc = new ActiveXObject('Microsoft.XMLDOM');
      doc.loadXML(str);
      return doc;
    } else if (window.DOMParser) {
      return (new DOMParser).parseFromString(str, 'text/xml');
    }
  }  
  function doNothing() {}  

  
  
  
// Self geolocaion
//-------------------------------------------------------------
  
  
  
//	geometa.js
//-------------------------------------------------------------
//From
//http://google-ajax-examples.googlecode.com/svn/trunk/whereareyou/scripts/geometa.js
function prepareGeolocation(opt_force) {
if ( opt_force || typeof navigator.geolocation == "undefined" || navigator.geolocation.shim ) (function(){

//-- BEGIN GEARS_INIT
(function() {
 // We are already defined. Hooray!
 if (window.google && google.gears) {
   return;
 }

 var factory = null;

 // Firefox
 if (typeof GearsFactory != 'undefined') {
   factory = new GearsFactory();
 } else {
   // IE
   try {
     factory = new ActiveXObject('Gears.Factory');
     // privateSetGlobalObject is only required and supported on WinCE.
     if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
       factory.privateSetGlobalObject(this);
     }
   } catch (e) {
     // Safari
     if ((typeof navigator.mimeTypes != 'undefined')
          && navigator.mimeTypes["application/x-googlegears"]) {
       factory = document.createElement("object");
       factory.style.display = "none";
       factory.width = 0;
       factory.height = 0;
       factory.type = "application/x-googlegears";
       document.documentElement.appendChild(factory);
     }
   }
 }

 // *Do not* define any objects if Gears is not installed. This mimics the
 // behavior of Gears defining the objects in the future.
 if (!factory) {
   return;
 }

 // Now set up the objects, being careful not to overwrite anything.
 //
 // Note: In Internet Explorer for Windows Mobile, you can't add properties to
 // the window object. However, global objects are automatically added as
 // properties of the window object in all browsers.
 if (!window.google) {
   google = {};
 }

 if (!google.gears) {
   google.gears = {factory: factory};
 }
})();
//-- END GEARS_INIT

var GearsGeoLocation = (function() {
   // -- PRIVATE
   var geo = google.gears.factory.create('beta.geolocation');

   var wrapSuccess = function(callback, self) { // wrap it for lastPosition love
       return function(position) {
           callback(position);
           self.lastPosition = position;
       }
   }

   // -- PUBLIC
   return {
       shim: true,

       type: "Gears",

       lastPosition: null,

       getCurrentPosition: function(successCallback, errorCallback, options) {
           var self = this;
           var sc = wrapSuccess(successCallback, self);
           geo.getCurrentPosition(sc, errorCallback, options);
       },

       watchPosition: function(successCallback, errorCallback, options) {
           geo.watchPosition(successCallback, errorCallback, options);
       },

       clearWatch: function(watchId) {
           geo.clearWatch(watchId);
       },

       getPermission: function(siteName, imageUrl, extraMessage) {
           geo.getPermission(siteName, imageUrl, extraMessage);
       }

   };
})();

var AjaxGeoLocation = (function() {
   // -- PRIVATE
   var loading = false;
   var loadGoogleLoader = function() {
       if (!hasGoogleLoader() && !loading) {
           loading = true;
           var s = document.createElement('script');
           s.src = 'http://www.google.com/jsapi?callback=_google_loader_apiLoaded';
           s.type = "text/javascript";
           document.getElementsByTagName('body')[0].appendChild(s);
       }
   };

   var queue = [];
   var addLocationQueue = function(callback) {
       queue.push(callback);
   }

   var runLocationQueue = function() {
       if (hasGoogleLoader()) {
           while (queue.length > 0) {
               var call = queue.pop();
               call();
           }
       }
   }

   window['_google_loader_apiLoaded'] = function() {
       runLocationQueue();
   }

   var hasGoogleLoader = function() {
       return (window['google'] && google['loader']);
   }

   var checkGoogleLoader = function(callback) {
       if (hasGoogleLoader()) return true;

       addLocationQueue(callback);

       loadGoogleLoader();

       return false;
   };

   loadGoogleLoader(); // start to load as soon as possible just in case

   // -- PUBLIC
   return {
       shim: true,

       type: "ClientLocation",

       lastPosition: null,

       getCurrentPosition: function(successCallback, errorCallback, options) {
           var self = this;
           if (!checkGoogleLoader(function() {
               self.getCurrentPosition(successCallback, errorCallback, options);
           })) return;

           if (google.loader.ClientLocation) {
               var cl = google.loader.ClientLocation;

               var position = {
                   latitude: cl.latitude,
                   longitude: cl.longitude,
                   altitude: null,
                   accuracy: 43000, // same as Gears accuracy over wifi?
                   altitudeAccuracy: null,
                   heading: null,
                   velocity: null,
                   timestamp: new Date(),

                   // extra info that is outside of the bounds of the core API
                   address: {
                       city: cl.address.city,
                       country: cl.address.country,
                       country_code: cl.address.country_code,
                       region: cl.address.region
                   }
               };

               successCallback(position);

               this.lastPosition = position;
           } else if (errorCallback === "function")  {
               errorCallback({ code: 3, message: "Using the Google ClientLocation API and it is not able to calculate a location."});
           }
       },

       watchPosition: function(successCallback, errorCallback, options) {
           this.getCurrentPosition(successCallback, errorCallback, options);

           var self = this;
           var watchId = setInterval(function() {
               self.getCurrentPosition(successCallback, errorCallback, options);
           }, 10000);

           return watchId;
       },

       clearWatch: function(watchId) {
           clearInterval(watchId);
       },

       getPermission: function(siteName, imageUrl, extraMessage) {
           // for now just say yes :)
           return true;
       }

   };
})();

//If you have Gears installed use that, else use Ajax ClientLocation
navigator.geolocation = (window.google && google.gears && google.gears.factory.create) ? GearsGeoLocation : AjaxGeoLocation;

})();
}

function doGeolocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(positionSuccess, positionError);
    } else {
      positionError(-1);
    }
  }
 
  function positionError(err) {
    var msg;
    switch(err.code) {
      case err.UNKNOWN_ERROR:
        msg = "Невозможно определить ваше местоположение.";
        break;
      case err.PERMISSION_DENINED:
        msg = "Нет доступа к вашему местоположению.";
        break;
      case err.POSITION_UNAVAILABLE:
        msg = "Ваше местоположение неизвестно.";
        break;
      case err.BREAK:
        msg = "Попытка опрределить местоположение заняла слишком много времени.";
        break;
      default:
        msg = "Определение местоположения не поддерживается браузером.";
    }
    document.getElementById('geo-info').innerHTML = msg;
  }
 
  function positionSuccess(position) {
    // Centre the map on the new location
    var coords = position.coords || position.coordinate || position;
    var latLng = new google.maps.LatLng(coords.latitude, coords.longitude);
    map.setCenter(latLng);
    map.setZoom(9);
    var marker = new google.maps.Marker({
	    map: map,
	    position: latLng,
	    title: 'Вот вы где...',
	    icon: ' '
    });
    document.getElementById('geo-info').innerHTML = 'Ищу <b>' +
        coords.latitude + ', ' + coords.longitude + '</b>...';
 
    // And reverse geocode.
    (new google.maps.Geocoder()).geocode({latLng: latLng}, function(resp) {
		  var place = "Вы где-то здесь...";
		  if (resp[0]) {
			  var bits = [];
			  for (var i = 0, I = resp[0].address_components.length; i < I; ++i) {
				  var component = resp[0].address_components[i];
				  if (contains(component.types, 'political')) {
					  bits.push('<b>' + component.long_name + '</b>');
					}
				}
				if (bits.length) {
					place = bits.join(' > ');
				}
				marker.setTitle(resp[0].formatted_address);
			}
			document.getElementById('geo-info').innerHTML = place;
	  });
  }
 
  function contains(array, item) {
	  for (var i = 0, I = array.length; i < I; ++i) {
		  if (array[i] == item) return true;
		}
		return false;
	}


