var Thor = Class.create();

Windows.overlayShowEffectOptions = {duration: 0};

//defining the rest of the class implmentation
Thor.prototype = {

   initialize: function() {

   	},

   showEdit: function(wurl) {

   		Dialog.confirm({url: wurl}, {windowParameters: {className:"thor", width:350, title: 'Bearbeiten', effectOptions: {duration:0}},
                                      okLabel: "&auml;ndern", cancelLabel: "abbrechen",
                                      ok:function(win){$('fLogin').submit();return false;}});

   },

   showIndicator: function() {
   	  $('ajax-indicator').show();
   },

   showQuicktour: function(url) {
   		if(url == '' || url == null){
   			url = '/files/quicktour.html';
   		}
		window.open(url, "Zweitfenster", "width=820,height=640");

   },

   showPepperQuicktour: function(url) {
   		if(url == '' || url == null){
   			url = '/files/pepperquicktour.html';
   		}
		window.open(url, "Zweitfenster", "width=820,height=640");

   },

   showDrinkcalc: function() {

   		Dialog.alert({url: '/files/drinkcalc.html'}, {windowParameters: {className:"thor", width: 700, title: 'Getr&auml;nkerechner', effectOptions: {duration:0}, recenterAuto: false},
                                      okLabel: "Fenster schlie&szlig;en"});

   },


   showRegister: function(wurl) {

   	   Dialog.confirm({url: wurl}, {windowParameters: {className:"thor", width: 630, title: 'Nachricht', effectOptions: {duration:0}},
                                      okLabel: "Passwort w&auml;hlen", cancelLabel: "Abbrechen",
                                      ok:function(win){


                                     	if (this.secondclick) {
                                     		$('registerForm').submit();
                                     	} else {
                                     		Element.show('registerForm');
                                     		win.updateHeight();
                                     		button = $$('.ok_button')[0];
                                     		button.value = 'Registrieren';

                                     		this.secondclick = true;
										}
                                     	return false;
                                     	}
                                     	});
   },

   showMagazinPopup: function(wurl) {

   	   Dialog.alert({url: wurl}, {windowParameters: {className:"thor", width:500, title: 'Magazin', effectOptions: {duration:0}},
                                      okLabel: "Schlie&szlig;en"});

   },

   showReminder: function(wurl) {

   	   Dialog.confirm({url: wurl}, {windowParameters: {className:"thor", width:320, title: 'Passworterinnerung', effectOptions: {duration:0}},
                                      okLabel: "best&auml;tigen", cancelLabel: "abbrechen",
                                      ok:function(win){$('fConfirm').submit();return false;}});

   },

   showLogin: function(wurl) {
   		Dialog.confirm({url: wurl}, {windowParameters: {className:"thor", width:320, title: 'Anmelden', effectOptions: {duration:0}},

                                      okLabel: "anmelden", cancelLabel: "abbrechen",
                                      ok:function(win){$('fLoginPopup').submit();return false;}});
   },

   showCommentForm: function(wurl) {

   		Dialog.confirm({url: wurl}, {windowParameters: {className:"thor", width:320, title: 'Neuer Kommentar', effectOptions: {duration:0}},
                                      okLabel: "Abschicken", cancelLabel: "Abbrechen",
                                      ok:function(win){
                                      $$('.ok_button')[0].disabled = true;
                                      $('fComment').submit();
                                      return false;

                                      }

                                      });
   },

   showFeedback: function() {

   		Dialog.confirm({url: '/index/feedback'}, {windowParameters: {className:"thor", width:400, title: 'Feedback', effectOptions: {duration:0}},
                                      okLabel: "Abschicken", cancelLabel: "Abbrechen",
                                      ok:function(win){$('fFeedback').submit();return false;}});
   },

   showPhotoCommentForm: function(pid) {

   		Dialog.confirm('<textarea rows="5" cols="40" name="comments" id="comments"></textarea>', {windowParameters: {className:"thor", width:320, title: 'Neuer Kommentar', effectOptions: {duration:0}},
                                      okLabel: "Abschicken", cancelLabel: "Abbrechen",
                                      ok:function(win){savePhotoComments(pid); Dialog.closeInfo();}});
   },

   showCommentList: function(wurl) {

   		Dialog.alert({url: wurl}, {windowParameters: {className:"thor", width:320, title: 'Kommentare', effectOptions: {duration:0}},
                                      okLabel: "Schlie&szlig;en" });
   },


   showMessage: function(msg) {

   		Dialog.alert(msg, {windowParameters: {className:"thor", width:320, title: 'Nachricht', effectOptions: {duration:0}},
                                      okLabel: "Schlie&szlig;en" });
   },

   showRedirectMessage: function(msg, url) {

   		Dialog.alert(msg, {windowParameters: {className:"thor", width:320, title: 'Nachricht', effectOptions: {duration:0}},
                                      okLabel: "Schlie&szlig;en", ok:function(win){
                                      	document.location.href = url;
        							}});
   },


   showTerms: function() {

   		Dialog.alert({url: '/static/termspopup'}, {windowParameters: {className:"thor", width:500, height:400, title: 'Nutzungsbedingungen', effectOptions: {duration:0}},
                                      okLabel: "Schlie&szlig;en" });
   },

   showReplymessage: function(msg, title) {

   		Dialog.alert(msg, {windowParameters: {className:"thor", width:500, title: title, effectOptions: {duration:0}},
                                      okLabel: "Schlie&szlig;en" });
   },

   showHelp: function(title, wurl) {

   		Dialog.alert({url: wurl}, {windowParameters: {className:"thor", width:600, title: title, effectOptions: {duration:0}},
                                      okLabel: "Schlie&szlig;en" });
   },

   confirm: function(headline, text, func) {

   		Dialog.confirm(text, {windowParameters: {className:"thor", width:320, title: headline, effectOptions: {duration:0}},
                                      okLabel: "Ok", cancelLabel: "Abbrechen",
                                      ok: func });
   },

   actionConfirm: function(wurl,headline) {

   		Dialog.confirm({url: wurl}, {windowParameters: {className:"thor", width:320, title: headline, effectOptions: {duration:0}},
                                      okLabel: "Ok", cancelLabel: "Abbrechen",
                                      ok: function(win) {
                                      	 $('faction').submit(); return false;
                                      }

   		 });
   },

   showEmailForm: function(wurl, rcpts) {

   		Dialog.confirm({url: wurl}, {windowParameters: {className:"thor", width: 400, title: 'E-Mail schreiben', effectOptions: {duration:0}},
                                      okLabel: "E-Mail schicken!", cancelLabel: "Abbrechen",
				      ok:function(win){
					  $('fSendmail').recipients.value = rcpts;
					  $('fSendmail').submit(); return false;
				      }
				   });
   },

   sendConfirmlink: function() {

   		Dialog.alert({url: '/myRegistrationReminder'}, {windowParameters: {className:"thor", width:400, title: 'Registrierungslink zusenden', effectOptions: {duration:0}},
                                      okLabel: "Schlie&szlig;en" });

   },

   showSetanswerForm: function(wurl, rcpts) {

   		Dialog.confirm({url: wurl}, {windowParameters: {className:"thor", width:300, title: 'Antworten bearbeiten', effectOptions: {duration:0}},
                                      okLabel: "Antwort setzen!", cancelLabel: "Abbrechen",
                                      ok:function(win){
						$('fSetanswer').recipients.value = rcpts;
						$('fSetanswer').submit();return false;
					}
				});
   },

   showSetanswerFormError: function(wurl, rcpts) {

   		Dialog.alert({url: wurl}, {windowParameters: {className:"thor", width:300, title: 'Antworten bearbeiten', effectOptions: {duration:0}},
                                       okLabel: "Schlie&szlig;en"
				});
   },

   showCalendarDateForm: function(wurl) {

   		Dialog.confirm({url: wurl}, {windowParameters: {className:"thor", width:400, title: 'Termine', effectOptions: {duration:0}},
                                      okLabel: "Eintragen", cancelLabel: "Abbrechen",
                                      ok:function() {
					  new Ajax.Request('/calendar/validateDateform', { parameters: Form.serialize('fDateform'), onComplete: function(transport) {
					      var response;
					      try {
						  response = eval('(' + transport.responseText + ')');
					      } catch(e) { }
					      if (response) {
						  if (response.valid == true) {
						      $('fDateform').submit();
						  }
						  else if (response.errors) {
						      // errors occured
						      FormError.unset();
						      FormError.addErrors(response.errors);
						      FormError.set();
						  }
					      }
					      else {
						  // server connection failed
					      }
					  } });
					  return false;}});
   },

   showGRouteForm: function(wurl, curl){
   	 google_route_result = false;

   	 Dialog.confirm({url: wurl}, {windowParameters: {className:"thor", width:400, title: 'Route berechnen', effectOptions: {duration:0}},
   	   					okLabel: "Route berechnen", cancelLabel: "Abbrechen",
   	   					ok:function(){
   	   						new Ajax.Request(curl, {method: 'post', asynchronous: false, parameters: Form.serialize('fRoute'), onComplete: function(transport){
   	   							var response;
					      		try {
						  			response = eval('(' + transport.responseText + ')');
					      		} catch(e) {

					      		}
   	   							FormError.unset();
   	   							if(response.valid == true){
   	   								$('saddr').value = response.saddr;
   	   								$('daddr').value = response.daddr;
   	   								google_route_result = true;
   	   								$('form_google_route').submit();
   	   							}else if(response.errors){
   	   								google_route_result = false;
   	   								FormError.addErrors(response.errors);
   	   								FormError.set();
   	   							}
   	   							return true;
   	   						}});
   	   						return google_route_result;
   	   					}});
   }
}

function ThorGMap(state, opts) {
    this.editable = opts.editable;
    this.contentTemplate = opts.contentTemplate;

    this.mapType = ThorGMap.getMapType(state.mapType || 'm');
    this.bounds = state.bounds ? new GLatLngBounds(new GLatLng(state.bounds.s, state.bounds.w), new GLatLng(state.bounds.n, state.bounds.e)) : null;
    this.autoUpdateStopped = state.autoUpdateStopped;
    this.visibleAddress = state.visibleAddress;
    this.marker = [];

    (state.marker || []).each(function(state) { var marker = new ThorMarker(state, { editable: this.editable, contentTemplate: this.contentTemplate }); this.addMarker(marker); if (state.addressMarker) this.addressMarker = marker; }.bind(this));
}

ThorGMap.getGeocoder = function() {
    return ThorGMap._geocoder || (ThorGMap._geocoder = new GClientGeocoder());
};

ThorGMap.getMapType = function(urlArg) {
    return { m: G_NORMAL_MAP, k: G_SATELLITE_MAP, h: G_HYBRID_MAP }[urlArg];
};

ThorGMap.prototype = {
    getState: function() {
	var marker = this.marker.map(function(m) { return m.getState(); });
	var bounds = this.map.getBounds();
	var sw = bounds.getSouthWest();
	var ne = bounds.getNorthEast();
	return { bounds: { s: sw.lat(), w: sw.lng(), n: ne.lat(), e: ne.lng() }, mapType: this.map.getCurrentMapType().getUrlArg(), marker: marker, autoUpdateStopped: this.autoUpdateStopped, visibleAddress: this.visibleAddress };
    },

    setGMap: function(map) {
	this.map = map;
	if (this.bounds) {
	    this.map.setCenter(this.bounds.getCenter(), this.map.getBoundsZoomLevel(this.bounds));
	}
	else {
	    this.map.setCenter(new GLatLng(50.5692828655824, 10.634765625), 5);
	}
	this.map.clearOverlays();
	this.map.setMapType(this.mapType);
	this.marker.each(this.showMarker.bind(this));

	if (this.editable) {
	    GEvent.addListener(this.map, 'click', function(m,p) {
		if (!m) {
		    var marker = new ThorMarker({ lat: p.lat(), lng: p.lng(), title: 'Titel', description: 'Beschreibung' }, { editable: true, contentTemplate: this.contentTemplate });
		    this.addMarker(marker);
		    this.showMarker(marker);
		}
	    }.bind(this));
	}
    },

    addMarker: function(marker) {
	marker.setThorGMap(this);
	this.marker.push(marker);
    },

    showMarker: function(marker) {
	this.map.addOverlay(marker.getGMarker());
    },

    removeMarker: function(marker) {
	this.map.removeOverlay(marker.getGMarker());
	this.map.closeInfoWindow();
	this.marker = this.marker.without(marker);
    },

    getGMap: function() {
	return this.map;
    },

    showAddress: function(address, title, description) {
	if (!this.autoUpdateStopped && address != this.visibleAddress) {
	    ThorGMap.getGeocoder().getLocations(
				  address,
				  function(res) {
				      if (res.Status.code == 200 ) {
					  if ($('tgmap_address_invalid')) {
					      Element.setStyle('tgmap_address_invalid', { visibility: 'hidden' });
					  }
					  var coordinates = res.Placemark[0].Point.coordinates;
					  this.map.setCenter(new GLatLng(coordinates[1], coordinates[0]), 15);
					  if (this.addressMarker) {
					      this.addressMarker.getGMarker().setPoint(new GLatLng(coordinates[1], coordinates[0]));
					      this.addressMarker.setDescription(description);
					  }
					  else {
					      this.addressMarker = new ThorMarker({ lat: coordinates[1], lng: coordinates[0], title: title,  description: description, addressMarker: true }, { editable: true, contentTemplate: this.contentTemplate });
					      this.addMarker(this.addressMarker);
					      this.showMarker(this.addressMarker);
					  }
				      }
				      else {
					  if ($('tgmap_address_invalid')) {
					      Element.setStyle('tgmap_address_invalid', { visibility: 'visible' });
					  }
				      }
				  }.bind(this));
	    this.visibleAddress = address;
	}
    },

    markerModified: function(marker) {
	if (marker == this.addressMarker) this.autoUpdateStopped = true;
    }
};

 function nl2br_12(str) {
     if(typeof(str)=="string") return str.replace(/(\r\n)|(\n\r)|\r|\n/g,"<br/>");
     else return str;
 }

function ThorMarker(state, opts) {
    this.addressMarker = state.addressMarker;

    var dataMap, eventHandler;
    if (opts.editable) {
	this.marker = new GMarker(new GLatLng(state['lat'], state['lng']), { draggable: true });
	dataMap = {
	    title: function(d, s) { return ZPane.Utils.escape(d.title); },
	    description: function(d, s) { return nl2br_12(ZPane.Utils.escape(d.description)); },
	    description_textfield: function(d, s) { return ZPane.Utils.escape(d.description); },
	    displayMode: function(d, s) { return s.editMode ? 'none' : 'block'; },
	    editMode: function(d, s) { return s.editMode ? 'block' : 'none'; }
	};
	eventHandler = [
		{ type: 'click', selector: 'img.editMarker', handler: function(event, pane) { Event.stop(event); pane.setStateKey('editMode', true); pane.update(); } },
		{ type: 'click', selector: 'img.saveMarker', handler: function(event, pane) { Event.stop(event); this.map.markerModified(this); pane.setStateKey('editMode', false); pane.setDataKey('title', pane.getElement().getElementsBySelector('div.markerTitle input')[0].value); pane.setDataKey('description', pane.getElement().getElementsBySelector('div.markerDescription textarea')[0].value); pane.update(); }.bind(this) },
		{ type: 'click', selector: 'img.cancelMarker', handler: function(event, pane) { Event.stop(event); pane.setStateKey('editMode', false); pane.update(); } },
		{ type: 'click', selector: 'img.removeMarker', handler: function(event, pane) { Event.stop(event); this.map.markerModified(this); this.map.removeMarker(this); }.bind(this) }	];
    }
    else {
	this.marker = new GMarker(new GLatLng(state['lat'], state['lng']), { title: state['title'] });
	dataMap = {
	    title: function(d, s) { return ZPane.Utils.escape(d.title); },
	    description: function(d, s) { return nl2br_12(ZPane.Utils.escape(d.description)); }
	};
	eventHandler = [];
    }

    this.content = new ZPane({
		template: opts.contentTemplate,
		data: { title: state['title'], description: state['description'] },
		dataMap: dataMap,
		eventHandler: eventHandler
	});
	this.content.update()

	GEvent.addListener(this.marker, 'click', this.toggleInfoWindow.bind(this));
	GEvent.addListener(this.marker, 'dragstart', function() { this.map.getGMap().closeInfoWindow(); this.map.markerModified(this); }.bind(this));
}

ThorMarker.prototype = {
    getState: function() {
	var point = this.marker.getPoint();
	var data = this.content.getData();
	return { lat: point.lat(), lng: point.lng(), title: data.title, description: data.description, addressMarker: this.addressMarker };
    },

    getGMarker: function() {
	return this.marker;
    },

    setThorGMap: function(map) {
	this.map = map;
    },

    toggleInfoWindow: function() {
	if (!this.map) return;
	var iw = this.map.getGMap().getInfoWindow();
	if (!iw.isHidden() && iw.getPoint().equals(this.marker.getPoint())) {
	    this.map.getGMap().closeInfoWindow();
	}
	else {
	    //	    var state = this.content.getState();
	    //	    state.editMode = false;
	    //	    this.content.update();
	    this.marker.openInfoWindow(this.content.getElement());
	}
    },

    setTitle: function(title) {
	this.content.setDataKey('title', title);
	this.content.update();
    },

    setDescription: function(description) {
	this.content.setDataKey('description', description);
	this.content.update();
    }
};

function inputFocus(input) {
	if (input.value == input.title) {
		input.value = '';
	}
}

function inputBlur(input) {
	if (input.value == '') {
		input.value = input.title;
	}
}

function inputSubmit(form) {
	var f = form.getElementsByTagName('input');

	for(var i=0; i<f.length; i++){
		if (f[i].value == f[i].title) {
			f[i].value = '';
		}
	}

}

function showPopCalendar(obj, allow_past, field, secTarget,onChangeFunction) {

    if (allow_past != 1)
        allow_past = 0;

    try {
    	if(onChangeFunction){
    		popCalendar.onChangeFunction = onChangeFunction;
    	}
        popCalendar.show(obj, field, "dd.mm.yyyy","de", allow_past, -1, -1);
    } catch(e) {
        alert(e);
    }

    return false;
}

var FormError = {
    errors: {},

    addErrors: function(errors, postfix) {
	if (!errors) return;
	postfix = postfix ? ':' + postfix : '';
	for (var name in errors) {
 	    this.errors[name + postfix] = errors[name];
	}
    },

    set: function() {
	for (var name in this.errors) {
	    var form_row;
	    if (form_row = $('form_' + name)) {
		Element.addClassName(form_row, 'form_error');
		var error;
		if (!(error = $('error' + name))) {
		    error = document.createElement('div');
		    error.id = 'error' + name;
		    error.className = 'error_message';
		    form_row.appendChild(error);
		}
		if (typeof this.errors[name] == 'string') {
		    Element.update(error, this.errors[name]);
		}
		else {
		    Element.update(error, this.errors[name].join('<br/>'));
		}
	    }
	}
    },

    unset: function() {
	for (var name in this.errors) {
	    var form_row;
	    if (form_row = $('form_' + name)) {
		Element.removeClassName(form_row, 'form_error');
		var error;
		if ((error = $('error' + name))) {
		    Element.remove(error);
		}
	    }
	    delete(this.errors[name]);
	}
    }
}

Event.observe(window, 'load', FormError.set.bind(FormError));

Ajax.Responders.register({
	onCreate: function() {
		var element;
		if (element = $('ajax-indicator')) Element.setStyle(element, { display: 'block' });
	},

	onComplete: function() {
		var element;
		if ((element = $('ajax-indicator')) && Ajax.activeRequestCount == 0) Element.setStyle(element, { display: 'none' });
	}
});


function hideUserimage() {
	$('overlay').hide();
}

function displayUserimage(elem, path, title) {
	hideUserimage();
	if(path == '') return;
	var elemo = $('overlay');
	var imgElem = $('preview');
	var offset = Position.cumulativeOffset(elem);
	var offset2 = Position.realOffset(elem);
	var offset3 = Position.page($$('body')[0]);
	var left = (offset[0])+'px';
	var top = (offset[1]-offset2[1]-offset3[1])+'px';
	imgElem.src = path;
	imgElem.name = path;
	imgElem.title = title;
	elemo.setStyle({left: left,top: top});
	elemo.show();
}


function csvImportWindow() {

	var wstat;
	var ns4up = (document.layers) ? 1 : 0;
	var ie4up = (document.all) ? 1 : 0;
	var xsize = screen.width;
	var ysize = screen.height;
	var breite=400;
	var hoehe=300;
	var xpos=(xsize-breite)/2;
	var ypos=(ysize-hoehe)/2;

	wstat=window.open("/import/CSVGuestlist/?init=1","","scrollbars=yes,status=no,toolbar=no,location=no,directories=no,resizable=yes,menubar=no,width="+breite+",height="+hoehe+",screenX="+xpos+",screenY="+ypos+",top="+ypos+",left="+xpos);

}