// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// Use jQuery, set it to noConflict because prototype also
// uses the $ function
jQuery.noConflict();

var msp = {

  hideFlashMessages: function () {
    $$('.flash_message').each(function(e) {
      if (e) Effect.Fade(e, { duration: 5.0 });
    });
  },

	appoint: {
		menu: function(element, href, date) {
			if (!element.tip) {
				
				element.tip = new Tip(element, "test", {
						style: 'creamy',
						hook: {tip: 'topLeft', target: 'bottomLeft'},
						hideAfter: 0.5, hideOn: 'mouseout', width: 100});
        element.prototip.show();						
			}
		},
		
		add: function(href, date) {
      Modalbox.show(href, {params: {date: date}, title: "Neuer Termin", width: 700});         
		},
		edit: function(href, title) {
      Modalbox.show(href, {title: title, width: 700});         
		}

	},
	
	tooltip: {
		add: function(element, tooltip) {
			$(element).observe('mouseover', function() {
				if (!this.tip) {
					this.tip = new Tip(element, tooltip, {
						style: 'creamy', stem: 'topLeft',
						hook: {tip: 'topLeft', mouse: true},
						offset: {x: 7,	y: 7}});
				}
			});
		},
		
		appear: function(event) {
			event.element().tip.wrapper.hide(); 
			event.element().tip.wrapper.appear({ duration: 0.3 });
		},
	
		fade: function(event) {
			event.element().tip.wrapper.show(); 
			event.element().tip.wrapper.fade({ duration: 0.3 });
		}
	},
	
  select: function(olditem, newitem){
    olditem.removeClassName('selected');
    newitem.addClassName('selected');
    return newitem;
  },
  
  dist2latlng: function(position, poly){
    var dist = 0, length = 0;
    for (var m = 1; m < poly.getVertexCount() && dist <= position; m++) {
      length = poly.getVertex(m).distanceFrom(poly.getVertex(m - 1));
      dist += length;
    }
    var p1 = poly.getVertex(m - 1), p2 = poly.getVertex(m - 2), d = (dist - position) / length;
    return new GLatLng(p1.lat() * (1 - d) + p2.lat() * d, p1.lng() * (1 - d) + p2.lng() * d);
  },
  
  add_dots: function(map, poly){
    var tinydot = new GIcon();
    tinydot.iconSize = new GSize(3, 3);
    tinydot.iconAnchor = new GPoint(1, 1);
    tinydot.image = "/images/tiny_dot.png"

    var largedot = new GIcon();
    largedot.iconSize = new GSize(59, 21);
    largedot.iconAnchor = new GPoint(4, 9);
    largedot.image = "/images/km.png"

    var flaggreen = new GIcon();
    flaggreen.iconSize = new GSize(16, 16);
    flaggreen.iconAnchor = new GPoint(11, 16);
    flaggreen.image = "/images/flag_green.png"

    var flagred = new GIcon();
    flagred.iconSize = new GSize(16, 16);
    flagred.iconAnchor = new GPoint(11, 16);
    flagred.image = "/images/flag_red.png"

		var smallmanager = new GMarkerManager(map, {borderPadding: 5})
		var tinymanager = new GMarkerManager(map, {borderPadding: 3})
    for (var i = 100; i < poly.getLength(); i += 100) {
			if (i % 1000 == 0) {
        text = "" + (i / 1000) + ((i < 100000) ? "km" : "")
        opts = {"icon": largedot, "labelText": text, "labelOffset": new GSize(17, -7)};
				smallmanager.addMarker(new LabeledMarker(msp.dist2latlng(i, poly), opts), (i % 2000 == 0) ? 11 : 13);
			}	else {
				tinymanager.addMarker(new GMarker(msp.dist2latlng(i, poly), {icon: tinydot, clickable: false}), 14);
			}
    }
    smallmanager.addMarker(new GMarker(poly.getVertex(poly.getVertexCount()-1), {icon: flagred, clickable: false}), 12);
    smallmanager.addMarker(new GMarker(poly.getVertex(0), {icon: flaggreen, clickable: false}), 12);
  },
  
  prepareMap: function(action){
    var map;
    
    if (GBrowserIsCompatible()) {
      var json = $F('track_map_data');
      if (!json || json == "") 
        json = '{"track":[]}';
      var data = json.evalJSON(true);
      if (!data.track) 
        data.track = [];
      var latlngs = data.track.map(function(ll){
        return new GLatLng(ll[0], ll[1])
      });
      
      map = new GMap2(document.getElementById("map_div"), {
        googleBarOptions: {
          showOnLoad: true,
          resultList: $('resultList'),
          suppressInitialResultSelection: true
        }
      });
      map.enableContinuousZoom();
      map.enableScrollWheelZoom();
      map.setMapType(G_HYBRID_MAP);
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());

      if (action == "overview") {
        GEvent.addListener(map, "moveend", function(){
          bounds = map.getBounds();
          sw = bounds.getSouthWest();
          ne = bounds.getNorthEast();
          new Ajax.Request('/tracks/random/', {
            method:'get',
            parameters: {south: sw.lat(), west: sw.lng(), north: ne.lat(), east: ne.lng()},
            onSuccess: function(transport){
              var tracks = transport.responseText.evalJSON(false);
              for (var i = 0; i< tracks.length; i++) {
                t = tracks[i];
                var icon = new GIcon();
                icon.iconSize = new GSize(25, 25);
                icon.iconAnchor = new GPoint(12, 12);
                icon.image = "/tracks/" + t[0] + "/thumb/25"
                var marker = new GMarker(new GLatLng(t[1], t[2]), {icon: icon, clickable: false});
                map.addOverlay(marker);
              }
            },
            onFailure: function(){ alert('Something went wrong...') }
          });
        });
        map.setCenter(new GLatLng(51, 10), 6);
        return map;
      }

      var line = new GPolyline(latlngs, '#0000FF', 2, 1);
      if (line.getVertexCount() > 0) {
        var bounds = line.getBounds();
        map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
      }
      else {
        map.setCenter(new GLatLng(51, 10), 6);
      }
      if (action == "show") {
        map.addOverlay(new GPolyline(latlngs, '#FFFF00', 5, 0.7));
        map.addOverlay(new GPolyline(latlngs, '#0000FF', 2, 1));
        msp.add_dots(map, line);
        return map;
      }
      map.addOverlay(line);

      map.enableGoogleBar();
      new GKeyboardHandler(map);
      
      var deleting = false;
      var selected;
      
      if (action == "edit") {
        selected = msp.select($('edit_btn'), $('edit_btn'));
        line.enableEditing();
      }
      
      if (action == "new") {
        selected = msp.select($('add_end_btn'), $('add_end_btn'));
        line.enableDrawing({
          fromStart: false
        })
      }
      
      Event.observe($('add_end_btn'), 'click', function(event){
        selected = msp.select(selected, Event.findElement(event, 'li'));
        deleting = false;
        line.enableDrawing({
          fromStart: false
        })
      });
      Event.observe($('add_start_btn'), 'click', function(event){
        selected = msp.select(selected, Event.findElement(event, 'li'));
        deleting = false;
        line.enableDrawing({
          fromStart: true
        })
      });
      Event.observe($('edit_btn'), 'click', function(event){
        selected = msp.select(selected, Event.findElement(event, 'li'));
        deleting = false;
        line.disableEditing()
        line.enableEditing();
      });
      Event.observe($('delete_btn'), 'click', function(event){
        selected = msp.select(selected, Event.findElement(event, 'li'));
        deleting = true;
        line.disableEditing()
        line.enableEditing()
      });
      
      GEvent.addListener(line, "click", function(latlng, index){
        if ((typeof index == "number") && deleting) {
          line.deleteVertex(index);
        }
      });
      
      GEvent.addListener(line, "endline", function(latlng, index){
        setTimeout(function(){
          selected = msp.select(selected, $('edit_btn'));
          deleting = false;
          line.disableEditing()
          line.enableEditing();
        }, 0);
      });

      GEvent.addListener(line, "lineupdated", function(){
        $('track_length_display').update((line.getLength() / 1000.0).toFixed(3));
      });
      $('track_length_display').update((line.getLength() / 1000.0).toFixed(3));

      Event.observe($('track_form'), 'submit', function(){
        data.track = [];
        if (line.getVertexCount() > 0) {
          for (var i = 0; i < line.getVertexCount(); ++i) {
            var ll = line.getVertex(i);
            data.track.push([ll.lat(), ll.lng()]);
          }
          var bounds = line.getBounds();
          $('track_map_data').value = Object.toJSON(data);
          
          $('track_start_lat').value = '' + line.getVertex(0).lat();
          $('track_start_lng').value = '' + line.getVertex(0).lng();
          $('track_lat_min').value = '' + bounds.getSouthWest().lat();
          $('track_lng_min').value = '' + bounds.getSouthWest().lng();
          $('track_lat_max').value = '' + bounds.getNorthEast().lat();
          $('track_lng_max').value = '' + bounds.getNorthEast().lng();
        }
        
        $('track_length').value = '' + line.getLength();
      }, false);
    }
    return map;
  },

  focusLoginFields: function() {
	$('login').observe('focus', function() {
		if ($(this).getValue() == 'Benutzername') {
			$(this).clear();
		}
	});
	$('password').observe('focus', function() {
		if ($(this).getValue() == 'password') {
			$(this).clear();
		}
	});
	$('login').observe('blur', function() {
		if ($(this).getValue() == '') {
			$(this).setValue('Benutzername');
		}
	});
	$('password').observe('blur', function() {
		if ($(this).getValue() == '') {
			$(this).setValue('password');
		}
	});
  }
};

document.observe("dom:loaded", function() {
  setTimeout(msp.hideFlashMessages, 10000);
  setTimeout(msp.focusLoginFields, 100);
});

jQuery(document).ready(function() {
	jQuery("a.ajax").live("click", function() {
		jQuery.ajax({
			url: this.href,
			dataType: "script",
			beforeSend: function(xhr) {
				xhr.setRequestHeader("Accept", "text/javascript")
			}
		});
		return false;
	});
});