var global_position = Array();
var updateLocationId = null;
var updateLocationCount = 0;

function invite_friends(event_id, invitation_text) {
  mpq.track('Facebook Invite');
	request_ids = 
	FB.ui({method: 'apprequests', 
		   message: invitation_text, 
		   data: event_id},
		   function(response) {
        console.debug(response);
         mpq.track('Facebook Invite Complete'); 
		   	 var myAjax = new Ajax.Request('/events/invite/'+event_id+'/'+response.request,
					     {
                 method: 'post', 
							   onSuccess: function (response) {
							 	 
				         }
				       });	
		   });
}

function locate_me() {
	try {
		if (navigator.geolocation) {
			updateLocationId = navigator.geolocation.watchPosition(	get_location_success_updater, 
																	get_location_fail,
																	{ timeout: 10000, enableHighAccuracy: true } );
		} else {
			geolocation = google.gears.factory.create('beta.geolocation');
			updateLocationId = geolocation.watchPosition( get_location_success_updater, 
														  get_location_fail,
														  { timeout: 10000, enableHighAccuracy: true } );	
		}
	} catch (err) {
		$('nearby_bar').style.display='none';
		$('nearby').style.display='none';
		$('nearby_separator').style.display='none';
	}
}

function get_location_success_updater(position) {	

	if (navigator.geolocation) {
		global_position['latitude'] = position.coords.latitude;
		global_position['longitude'] = position.coords.longitude;
		global_position['accuracy'] = position.coords.accuracy;		
		global_position['timestamp'] = position.timestamp;
	} else {
		global_position['latitude'] = position.latitude;
		global_position['longitude'] = position.longitude;
		global_position['accuracy'] = position.accuracy;
		global_position['timestamp'] = position.timestamp.getTime(); //timestamp_new - position.timestamp;
	}
	updateLocationCount++;
	if (updateLocationCount < 2) {
		var myAjax = new Ajax.Request('/base/nearby/0/'+global_position['latitude']+'/'+global_position['longitude']+'/_small',
					    	{method: 'post', 
							 onSuccess: function (response) {
							 	$('nearby').innerHTML = response.responseText;
				        	 }
				        });	
		try {
			if (navigator.geolocation) {
				navigator.geolocation.clearWatch(updateLocationId);
			} else {
				geolocation.clearWatch(updateLocationId);
			}
		} catch (err) {		
		}	
	}
}

function get_location_fail() {
	//alert('no location :(');
}

var event_guest_request = Array();
function event_guest(event_id,id,className) {

	if (className.indexOf('guest_inactive')>=0) {
		type = 'Y';
		$(id).className = 'guest guest_active';
	} else if (className.indexOf('guest_active')>=0) {
		type = 'M';
		$(id).className = 'guest guest_maybe';
	} else {
		type = 'N';
		$(id).className = 'guest guest_inactive';
	}

	var myAjax = new Ajax.Request('/events/guest/'+event_id,
	       {method: 'post', 
	        parameters: { 'data[Guest][type]': type },
				 onSuccess: function (response) {
				 	buffer = eval('('+response.responseText+')'	);					 	 
				 	$(id).innerHTML = buffer.text;
				 }
	        });
}

function event_guest2(event_id,guest_type) {
	if (guest_type == 'N') {
		$('event_iamguest_'+event_id).style.display = 'none';
	} else {
		$('event_iamguest_'+event_id).style.display = 'block';		
		$('event_iamguest_'+event_id).style.margin = '0px 4px 0px 0px';
	}	
  mpq.track('RSVP');
	var myAjax = new Ajax.Request('/events/guest/'+event_id,
	       {method: 'post', 
	        parameters: { 'data[Guest][type]': guest_type },
				 onSuccess: function (response) {
				 	buffer = eval('('+response.responseText+')'	);					 	 
				 	$(id).innerHTML = buffer.text;
				 }
	        });
}

function friend_request(mode,id) {  
	new Ajax.Request('/user/friend/'+mode+'/'+id,
  {
    method:'get',
    onSuccess: function(transport){
    
      Effect.Fade('request_'+id, { duration: 1.0 });
    },
    onFailure: function(){ alert('Something went wrong...') }
  });  
}

function switch_teaser() {
  if ($('teaser_backdrop').style.display == 'none') {    
    $('teaser_backdrop').style.display='block';
    $('teaser_signup').style.display='block';
  } else {
    $('teaser_backdrop').style.display='none';
    $('teaser_signup').style.display='none';
  }  
}

function switch_visible(id) {
	if ($(id).style.display == 'none')
		$(id).style.display = 'block';
	else
		$(id).style.display = 'none';
}

function hide_element(id) {
	$(id).style.display = 'none';
	//Effect.Fade(id, { duration: 0.3 });
}
function show_element(id) {
	$(id).style.display = 'block';
	//Effect.Appear(id, { duration: 0.3 });
}

function send_comment(base_id) {
	if ($('comment_text').value && $('comment_text').value!=lbl['lbl_checkins_enter_comment']) {
		$('comment_button').style.display='none';
		$('comment_indicator').style.display='block';
		$('comment_none').style.display='none';
		
		var myAjax = new Ajax.Request('/ajax/comment',
	       {method: 'post', 
	        parameters: { 'data[Checkin][base_id]': base_id,
	        			   			'data[Checkin][comment]':  $('comment_text').value},
				 onSuccess: function (response) {
          mpq.track('Comment');
				 	$('comment_text').value = '';
				 	$('comment_button').style.display='block';
					$('comment_indicator').style.display='none';
					c = Builder.node('div');
					c.innerHTML = response.responseText;
					$('comment_container').insertBefore(c, $('comment_container').firstChild);
				 }
	        });
	} else {
		alert(lbl['lbl_checkins_enter_comment_warning']);	
	}
}

function createColorSwitchMarker(point,html,use_icon,open,is_draggable){

  var point_no = new google.maps.Marker({
	  position: point,
	  draggable: false,
	  map: map,
	  html: html,
	  icon: use_icon
	});

  i = markers.length;
  markers[i] = point_no;
  
	google.maps.event.addListener(markers[i], 'click', function() {
    infowindow.setContent(html)
    infowindow.open(map,point_no);
	});
	return point_no;
	
	/*
	i = markers.length;
	var m = new GMarker(point, {icon:use_icon, draggable: is_draggable});
	map.addOverlay(m);
	if (is_draggable) {
		GEvent.addListener(m, "dragend", function() {	
			$('BaseLatitude').value = m.getLatLng().lat();
			$('BaseLongitude').value = m.getLatLng().lng();
		});
	}
	if (html) {		
		GEvent.addListener(m,'click',function(){
			m.openInfoWindowHtml(html);
			if (typeof(markers_loop) != 'undefined') {
				clearTimeout(markers_loop);
			}
		});
	}
	markers[i] = m;
	
	if (open)
		markers[i].openInfoWindowHtml(html);
	return i;
	*/
}


var map = null;
var infowindow = null;
var markers = [];
var smallIcon = null;
var greenIcon = null;
var yellowIcon = null;
function initMaps(id) {

  var options = {
    zoom: 15,
    center: new google.maps.LatLng(-33, 151),
    panControl: false,
    zoomControl: true,
    scaleControl: false,
    streetViewControl: false,
    overviewMapControl: false,
    mapTypeControl: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  
  map = new google.maps.Map(document.getElementById(id), options);
  
  infowindow = new google.maps.InfoWindow(
  { content: null,
    size: new google.maps.Size(50,50),    
  });
  
  smallIcon = new google.maps.MarkerImage('https://www.stadtkinder.com/img/pins/pin_red.png',
                                            new google.maps.Size(19, 21),
                                            new google.maps.Point(0,0),
                                            new google.maps.Point(5,20));
  greenIcon = new google.maps.MarkerImage('https://www.stadtkinder.com/img/pins/pin_green.png',
                                            new google.maps.Size(19, 21),
                                            new google.maps.Point(0,0),
                                            new google.maps.Point(5,20));
  yellowIcon = new google.maps.MarkerImage('https://www.stadtkinder.com/img/pins/pin_purple.png',
                                            new google.maps.Size(19, 21),
                                            new google.maps.Point(0,0),
                                            new google.maps.Point(5,20));                                          

  /*                                            
	smallIcon = new GIcon();  	     
	smallIcon.image = 'http://www.stadtkinder.com/img/pins/pin_red.png';
	smallIcon.iconSize = new GSize(19, 21);
	smallIcon.iconAnchor = new GPoint(5, 20); 
	smallIcon.infoWindowAnchor = new GPoint(4,5); 
	
	greenIcon = new GIcon();  	     
	greenIcon.image = 'http://www.stadtkinder.com/img/pins/pin_green.png';
	greenIcon.iconSize = new GSize(19, 21);
	greenIcon.iconAnchor = new GPoint(5, 20); 
	greenIcon.infoWindowAnchor = new GPoint(4,5); 
	
	yellowIcon = new GIcon();
	yellowIcon.image = 'http://www.stadtkinder.com/img/pins/pin_purple.png';
	yellowIcon.iconSize = new GSize(19, 21);
	yellowIcon.iconAnchor = new GPoint(5, 20);
	*/
}

// debug: Add Debug-Message to #debug-div

function debug(msg) {
	if (document.getElementById('debug_box'))
		$('debug_box').innerHTML = msg+"<br/>"+$('debug_box').innerHTML;
}

// switchDebug: Switch #debug-div on/off

function switchDebug() {	
	
	if (Element.getHeight($('debug')) <= 30) {
		$('debug').style.height = "300px";
		$('debug_box').style.height = "280px";
	} else {
		$('debug').style.height = "15px";
		$('debug_box').style.height = "0px";
	}
}

function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}

window.onkeyup = function(e) {
  if (e.keyCode == 27) {  //handle escape key
    $('teaser_backdrop').style.display='none';
    $('teaser_signup').style.display='none';
  }
}


Date.prototype.getWeek = function() {
  var onejan = new Date(this.getFullYear(),0,1);
  return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
