/**
 * Google Map and get songs functions
 *
 * @author		  Nicolas Zanghi
 * @copyright     Copyright 2010, Nicolas Zanghi
 */

	/**
	 * Globals Vars
	 */
	var map; // google map
	var map_add; // google map add
	var geocoder; // google geocoder, find a latlong from name
	var ytplayer; // youtube player

	var image; // note image
	var shadow; // note shadow
	var image_play; // note image when is playing

	var markers = new Object(); // list of note markers
	var markers_add = new Array(); // list of note markers for add song

	var radioSound = document.createElement('audio'); // html5 radiosound

	var song_id; // played song id
	var previous_song_id; // previous song id, used in btPrevious

	var mute = false;
	var mute_radio = true;
	var autoplay = true;


	var slider_control; // youtube slider currentTime control

	var db;


	Ajax.Responders.register({
	  onCreate: function() {
		$('spinner').style.display = 'inline';
	  },
	  onComplete: function() {
		$('spinner').style.display = 'none';
	  }
	});


	/**
	 * execute in body onload event
	 * load google map, listener ajax updater songs/get and set slider
	 */
	function initialize() {

		// to know if mouse is down, if down (user move map) doesn't load song
		var mouseDown = false;
		document.body.onmousedown = function() {mouseDown = true;}
		document.body.onmouseup = function() {mouseDown = false;}

		//create google map
		var carouge = new google.maps.LatLng(46.179949, 6.138954);
		var myOptions = {
		  zoom: 4,
		  center: carouge,
		  navigationControl: true,
		  navigationControlOptions: {
			  style: google.maps.NavigationControlStyle.ZOOM_PLAN,
			  position: google.maps.ControlPosition.TOP_RIGHT
		  },
		  mapTypeId: google.maps.MapTypeId.TERRAIN
		}

		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

		geocoder = new google.maps.Geocoder();

		// set marker image notes
		image = new google.maps.MarkerImage('img/notes.png',
			new google.maps.Size(24.0, 24.0),
			new google.maps.Point(0, 0),
			new google.maps.Point(12.0, 12.0)
		);
		shadow = new google.maps.MarkerImage('img/notes_shadow.png',
			new google.maps.Size(37.0, 24.0),
			new google.maps.Point(0, 0),
			new google.maps.Point(12.0, 12.0)
		);
		image_play = new google.maps.MarkerImage('img/notes_play.png',
			new google.maps.Size(24.0, 24.0),
			new google.maps.Point(0, 0),
			new google.maps.Point(12.0, 12.0)
		);

		// call get_song to play if there is a song at this coordinate
		var countMove = 0;
		var genres = '';
		var types = '';
		var years = '';
		var countries = '';
		var news = '';
		google.maps.event.addListener(map, 'mousemove', function(event) {
			if (!mouseDown && ytplayer) { // && !autoplay
				var maxCount = 3;
				/*if (ytplayer.getPlayerState() == '1')
					maxCount = 20;
				*/

				//$('move').innerHTML = countMove+' > '+maxCount;

				if (countMove > maxCount) {

					genres = getCheckboxValue(document.optionsMapForm, 'data[options][Genre][]');
					types = getCheckboxValue(document.optionsMapForm, 'data[options][Type][]');
					years = getCheckboxValue(document.optionsMapForm, 'data[options][Year][]');
					countries = getCheckboxValue(document.optionsMapForm, 'data[options][Country][]');
					news = getCheckboxValue(document.optionsMapForm, 'data[options][News][]');
//					playlists = getCheckboxValue(document.optionsMapForm, 'data[options][Playlist][]');

					//alert('songs/get/latlng:'+event.latLng+'/zoom:'+map.getZoom()+'/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news'+news);

					//new Ajax.Updater('song', 'songs/get/latlng:'+event.latLng+'/zoom:'+map.getZoom()+'/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news:'+news+'/playlists:'+playlists, {
					new Ajax.Updater('song', 'songs/get/latlng:'+event.latLng+'/zoom:'+map.getZoom()+'/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news:'+news, {
						asynchronous:true,
						evalScripts:true,
						method:'post'
					  });
					  countMove=0;
				 }
				 countMove++;
			}
//            $('video_duration').innerHTML = ytplayer.getPlayerState();

		});


		// load and play radio sound
		radioSound.setAttribute('src', 'files/radio.wav');
		radioSound.volume = 0.4;
		//radioSound.play();

		// loop radio sound
		radioSound.addEventListener('ended', function() {
			this.currentTime = 0;
		}, false);

		// position control
		slider_control = new Control.Slider($('video_seek').down('.handle'), $('video_seek'), {
		  range: $R(0, 100),
		  sliderValue: 0,
		  onSlide: function(value) {
			value = ytplayer.getDuration()/100*value;
			ytplayer.seekTo(value, true);
			$('video_handle').style.marginLeft = '0';
		  }
		});

		// volume control
		new Control.Slider($('volume_slider').down('.handle'), $('volume_slider'), {
		  range: $R(0, 100),
		  sliderValue: 100,
		  onSlide: function(value) {
			ytplayer.setVolume(value);
		  },
		  onChange: function(value) {
			ytplayer.setVolume(value);
		  }
		});


		// limit zoom
		google.maps.event.addListener(map, 'zoom_changed', function() {
		  if (map.getZoom() < 2) {
			map.setZoom(2);
		  }
		});


		/**
		 * Create songs local table
		 */
        /*
         // @todo desactivate for now
		new Ajax.Updater('song', 'songs/create_sqlite', {
			asynchronous: true,
			evalScripts: true,
			method: 'post',
			onComplete: function () {
			}
		  });
        */



		/*
		// play pause when space is pressed
		// @todo work in input not good
		document.body.addEventListener('keypress', function() {
			var code;
			if (!e) var e = window.event;
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			if (code == 32)
				if (ytplayer.getPlayerState() == '1')
					btPause();
				else
					btPlay();
		}, false);
		*/


	} // end initialize


	/**
	 * center the map at an address
	 */
	function codeAddress(map, address_input) {
		var address = $(address_input).value;
		geocoder.geocode( {'address': address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				map.setCenter(results[0].geometry.location);
			} else {
				alert("Location not found");
			}
		});
	}


	/**
	 * call songs/get to show all songs	in relation to genres, types, years and countries checked
	 */
	function showAllSongs() {
		// move copyright of map
		// delete old markers
		for (var i in markers) {
		  markers[i].setMap(null);
		}
		markers = new Object();

		genres = getCheckboxValue(document.optionsMapForm, 'data[options][Genre][]');
		types = getCheckboxValue(document.optionsMapForm, 'data[options][Type][]');
		years = getCheckboxValue(document.optionsMapForm, 'data[options][Year][]');
		countries = getCheckboxValue(document.optionsMapForm, 'data[options][Country][]');
		news = getCheckboxValue(document.optionsMapForm, 'data[options][News][]');
//		playlists = getCheckboxValue(document.optionsMapForm, 'data[options][Playlist][]');
		//new Ajax.Updater('song', 'songs/get/all/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news:'+news+'/playlists:'+playlists, {
		new Ajax.Updater('song', 'songs/get/all/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news:'+news, {
			asynchronous:true,
			evalScripts:true,
			method:'post'
		  });
	}

	function songsList() {
		genres = getCheckboxValue(document.optionsMapForm, 'data[options][Genre][]');
		types = getCheckboxValue(document.optionsMapForm, 'data[options][Type][]');
		years = getCheckboxValue(document.optionsMapForm, 'data[options][Year][]');
		countries = getCheckboxValue(document.optionsMapForm, 'data[options][Country][]');
		news = getCheckboxValue(document.optionsMapForm, 'data[options][News][]');
//		playlists = getCheckboxValue(document.optionsMapForm, 'data[options][Playlist][]');
		//new Ajax.Updater('page', 'songs/index/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news:'+news+'/playlists:'+playlists, {
		new Ajax.Updater('page', 'songs/index/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news:'+news, {
			asynchronous:true,
			evalScripts:true,
			method:'post',
			onComplete: function () {blindDown('page_container');}
		  });
	}

	function songsListSearch() {
		genres = getCheckboxValue(document.optionsMapForm, 'data[options][Genre][]');
		types = getCheckboxValue(document.optionsMapForm, 'data[options][Type][]');
		years = getCheckboxValue(document.optionsMapForm, 'data[options][Year][]');
		countries = getCheckboxValue(document.optionsMapForm, 'data[options][Country][]');
		news = getCheckboxValue(document.optionsMapForm, 'data[options][News][]');
//		playlists = getCheckboxValue(document.optionsMapForm, 'data[options][Playlist][]');
		//new Ajax.Updater('page', 'songs/index/get:search/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news:'+news+'/playlists:'+playlists, {
		new Ajax.Updater('page', 'songs/index/get:search/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news:'+news, {
			asynchronous:true,
			evalScripts:true,
			parameters:Form.serialize($('SongIndexForm')),
			requestHeaders:['X-Update', 'page']
		});
	}



	/**
	 * call songs/get to get id song
	 */
	function getOneSong(id, from) {
		new Ajax.Updater('song', 'songs/get/one/id:'+id, {
			asynchronous:true,
			evalScripts:true,
			method:'post'
		  });
		if (from == 'history')
			Effect.BlindUp('history_container');
	}

	/**
	 * call songs/get to get a random song in relation to genres, types, years and countries checked
	 */
	function getRandomSong() {

		$('details').style.display = 'none';
		$('song_video').style.visibility = 'hidden';
		$('song_name').style.display = 'none';


		var except = '';
		if (song_id != undefined)
			except = '/except:'+song_id;

		genres = getCheckboxValue(document.optionsMapForm, 'data[options][Genre][]');
		types = getCheckboxValue(document.optionsMapForm, 'data[options][Type][]');
		years = getCheckboxValue(document.optionsMapForm, 'data[options][Year][]');
		countries = getCheckboxValue(document.optionsMapForm, 'data[options][Country][]');
		news = getCheckboxValue(document.optionsMapForm, 'data[options][News][]');
//		playlists = getCheckboxValue(document.optionsMapForm, 'data[options][Playlist][]');
		//new Ajax.Updater('song', 'songs/get/random/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news:'+news+'/playlists:'+playlists+except, {
		new Ajax.Updater('song', 'songs/get/random/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news:'+news+except, {
			asynchronous:true,
			evalScripts:true,
			method:'post'
		  });

/*
        // @todo if after after 20 seconds is still loading the song pass to next
        new PeriodicalExecuter(function(pe) {
          if (ytplayer.getPlayerState() == 3)
              getRandomSong();
          pe.stop();
        }, 20);
        */

	}


	/**
	 * show in $('count') how many songs there is in relation to genres, types, years and countries checked
	 */
	function getCount() {
		genres = getCheckboxValue(document.optionsMapForm, 'data[options][Genre][]');
		types = getCheckboxValue(document.optionsMapForm, 'data[options][Type][]');
		years = getCheckboxValue(document.optionsMapForm, 'data[options][Year][]');
		countries = getCheckboxValue(document.optionsMapForm, 'data[options][Country][]');
		news = getCheckboxValue(document.optionsMapForm, 'data[options][News][]');
		//playlists = getCheckboxValue(document.optionsMapForm, 'data[options][Playlist][]');
		//new Ajax.Updater('count', 'songs/count/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news:'+news+'/playlists:'+playlists, {
		new Ajax.Updater('count', 'songs/count/genres:'+genres+'/types:'+types+'/years:'+years+'/countries:'+countries+'/news:'+news, {
			asynchronous:true,
			evalScripts:true,
			method:'post'
		  });

		// center map on the country if only one is selected
		if (countries.length == 2) {
			if (countries == 'TW') countries = 'Taiwan';
			geocoder.geocode( {'address': 'country '+countries}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					map.setCenter(results[0].geometry.location);
				}
			});
		}

	}



	/**
	 * if browser give the geo location of user, center map at this location
	 */
	function goToMyLocation() {
		var initialLocation;
		var browserSupportFlag =  new Boolean();
		  // Try W3C Geolocation (Preferred)
		  if(navigator.geolocation) {
			browserSupportFlag = true;
			navigator.geolocation.getCurrentPosition(function(position) {
			  initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
			  map.setCenter(initialLocation);
			}, function() {
			  handleNoGeolocation(browserSupportFlag);
			});
		  // Try Google Gears Geolocation
		  } else if (google.gears) {
			browserSupportFlag = true;
			var geo = google.gears.factory.create('beta.geolocation');
			geo.getCurrentPosition(function(position) {
			  initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
			  map.setCenter(initialLocation);
			}, function() {
			  handleNoGeoLocation(browserSupportFlag);
			});
		  // Browser doesn't support Geolocation
		  } else {
			browserSupportFlag = false;
			handleNoGeolocation(browserSupportFlag);
		  }
		  function handleNoGeolocation(errorFlag) {
		  }

	}

	/**
	 * Get checkbox value
	 */
	function getCheckboxValue(form, input) {
		var c_value = "";
		for (var i=0; i < form[input].length; i++)
		   if (form[input][i].checked)
			  c_value = c_value + form[input][i].value + ',';
		c_value = c_value.substr(0, c_value.length-1); // delete last ','
		return c_value;
	}






/************************
 * used in songs/add
 ***********************/

	function addMarker(location) {
		for (var i=0;i<markers_add.length;i++) {
		  markers_add[i].setMap(null);
		}
		marker = new google.maps.Marker({
			position: location,
			map: map_add
		});
		markers_add.push(marker);
		var tmp_latlng = String(location);
		tmp_latlng = tmp_latlng.split(',');
		tmp_latlng[0] = tmp_latlng[0].substr(1);
		tmp_latlng[1] = tmp_latlng[1].substr(1, tmp_latlng[1].length-2);
		$('SongLat').value = tmp_latlng[0];
		$('SongLng').value = tmp_latlng[1];

		// get country name
		var geocoder = new google.maps.Geocoder();
	    geocoder.geocode({'latLng': new google.maps.LatLng(tmp_latlng[0], tmp_latlng[1])},
			function(results, status) {
				if(status == google.maps.GeocoderStatus.OK) {
					if (results.length>0) {
						var country = "";
						for (i=0; i<results.length; i++) {
							var res = results[i];
							for (j=0; j<res.types.length; j++)
								if (res.types[j]=="country")
								   country = res.address_components[0].short_name;
						}
					    $('SongCountry').value = country;
					} else {
						$('SongCountry').value = '';
					}
				} else {
					$('SongCountry').value = '';
				}
			});


	}

	function codeAddressAdd() {
		$('addressAdd_loading').style.display = 'inline';
		$('addressAdd_error').style.display = 'none';
		$('addressAdd_valid').style.display = 'none';
		var address = $('SongAddressAdd').value;
		geocoder.geocode( {'address': address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				map_add.setCenter(results[0].geometry.location);
				parent.map.setCenter(results[0].geometry.location);
				$('SongLatlng').value = results[0].geometry.location;
				addMarker(results[0].geometry.location);
				$('addressAdd_valid').style.display = 'inline';
			} else {
				//alert("Location not found");
				$('addressAdd_error').style.display = 'inline';
			}
			$('addressAdd_loading').style.display = 'none';
		});
	}

	function loadAddSong(position) {

		if (position == null)
			position = new google.maps.LatLng(46.179949, 6.138954); // carouge

		var myOptions = {
		  zoom: 4,
		  center: position,
		  mapTypeId: google.maps.MapTypeId.TERRAIN,
		  disableDefaultUI: true
		}
		map_add = new google.maps.Map($("map_canvas_add"), myOptions);
		geocoder = new google.maps.Geocoder();

		google.maps.event.addListener(map_add, 'click', function(event) {
			$("SongLatlng").value = event.latLng;
			addMarker(event.latLng);
		});

		$('SearchButton').observe('click', function() {codeAddressAdd();}, false);
	}

	function loadEditSong(lat, lng) {

		var position = new google.maps.LatLng(lat, lng);

		loadAddSong(position);

		addMarker(position);
	}

