

function isdefined( variable)
{
 return (typeof(window[variable]) == "undefined")? false: true;
}

function versenden() {
 var send_link = document.location + "";
 //send_link = send_link.substr (0, send_link.indexOf("sid")-1 );
 document.location = "mailto:?Subject=Insider-Tipp von reisenet.at!&body=" + send_link;
}

/*
 * Main application
 */
var StorySlider = Class.create();
Object.extend(Object.extend(StorySlider.prototype, Widget.prototype), {
	logger: maptales.getLogger("slider"),
	initialize: function(container, parent, contextObject, view, templatePath, parameters, useInnerHtml) {
		var increment = 4;
		var interval = 60;
		try{
			var up   = document.getChildById("up", container);
			var down = document.getChildById("down", container);
			var list = document.getChildById("storyList", container);
			var clip = document.getChildById("storyListClipArea", container);
			var totalHeight = Element.getDimensions(list).height;
			var clippingHeight =  Element.getDimensions(clip).height;;
			var minimumTop = totalHeight-clippingHeight;
			var upIntervalId = null;
			var downIntervalId = null;
			
			var upfunction = function(){
				if(Math.abs(list.offsetTop)<Math.abs(minimumTop)){
					list.style.top = (list.offsetTop - increment) + "px";
				}
			}
			var boundUpFunction = upfunction.bind(this);
			var boostFunction = function(){increment=increment*2;}.bind(this);
			var deBoostFunction = function(){increment=increment/2;}.bind(this);
			
			var downfunction = function(){
				if(list.offsetTop<0){
					list.style.top = (list.offsetTop + increment) + "px";
				}
			}
			
			var boundDownFunction = downfunction.bind(this);
			
			up.onmouseover = function(){
				upIntervalId = window.setInterval(boundUpFunction, interval);
			}
			
			up.onmousedown = boostFunction;
			up.onmouseup = deBoostFunction;
			
			up.onmouseout = function(){
				window.clearInterval(upIntervalId);
			}
			
			down.onmouseover = function(){
				downIntervalId = window.setInterval(boundDownFunction, interval);
			}
			
			down.onmouseout = function(){
				window.clearInterval(downIntervalId);
			}
			down.onmousedown = boostFunction;
			down.onmouseup = deBoostFunction;
			
		
		}catch(e){
			reisenet.logger.error("story scroll konnte nicht initialisiert werden", e)
		}
	}
});
maptales.widgets["StorySlider"] = StorySlider;
 
var Slider = Class.create();
 
Object.extend(Object.extend(Slider.prototype, Widget.prototype), {
	logger: maptales.getLogger("zoom-slider"),
	initialize: function(container, parent, contextObject, view, templatePath, parameters, useInnerHtml) {
		this.initializeWidget(container, parent, contextObject, view, templatePath, parameters, true);
		this.steps = 20;
		this.stepSize = 7;
		this.sliderSize = 150;
		this.onDisplay();
	},
	
	onDisplay: function(){
		this.slider = new SliderHandler(this.getElement("zoom-slider"), this.sliderSize, 0);
		this.slider.onDragEnd = function(){
			this.gotoZoomLevel(this.determineZoomLevelFromHandler());
		}.bind(this);
		
		window.setTimeout(function(){
			this.getApplication().getMainMap().registerMoveListener(this);
			this.gotoZoomLevel(this.getApplication().getMainMap().getZoom());
		}.bind(this), 1000);
		
	},
	
	determineZoomLevelFromHandler: function(){
		var top = this.getElement("zoom-slider").offsetTop;
		var distance = Math.abs(top-this.sliderSize);
		var zoomLevel = Math.round(distance/this.stepSize);
		return zoomLevel;
	},
	
	onMapMove: function(){
		var zoomLevel = this.getApplication().getMainMap().getZoom();
		this.gotoZoomLevel(zoomLevel);
	},
	
	gotoZoomLevel: function(zoomLevel){
		$m("zoomTo", zoomLevel);
		this.getElement("zoom-slider").style.top = Math.round(Math.abs(zoomLevel-this.steps)*this.stepSize)+"px";
	}
	
	
});

maptales.widgets["Slider"] = Slider;

var SliderHandler = Class.create();

SliderHandler.prototype = {
	logger: maptales.getLogger("sliderHandler"),
	initialize: function(htmlElement, limitYMax, limitYMin){
		this.htmlElement = htmlElement;
		this.limitYMax = limitYMax;
		this.limitYMin = limitYMin;
			
		this.boundMouseMainMoveListener = this.mouseMainMoveListen.bind(this);
		this.boundStopObservingMain = this.stopObservingMain.bind(this);
		this.htmlElement.onmousedown = this.startDragMain.bindAsEventListener(this);
	},
	startDragMain: function(event){
		this.onDragStart();
		event.cancelBubble = true; //in case of 2 draggables over each other we only want to notify the first one. eg: Trashcan
		//start listening to mouse moves
		Event.observe(document, "mousemove", this.boundMouseMainMoveListener);
		Event.observe(document, "mouseup", this.boundStopObservingMain);
		
		this.initialMouseY = parseInt(Event.pointerY(event));		
		this.initialMainY = this.htmlElement.offsetTop;
		return false; //image bug fix
	},
	onDragStart: function(){},
	onDragEnd: function(){},
	/*
	 * This moves the box around after startDragMain started it
	 */
	mouseMainMoveListen: function(event){
		event.cancelBubble = true; //in case of 2 draggables over each other we only want to notify the first one. eg: Trashcan
		var yDelta = Event.pointerY(event)-this.initialMouseY;		
		var top = (parseInt(this.initialMainY)+parseInt(yDelta));
		
		//limit to area
		if(this.limitYMax!=null&&top>this.limitYMax)
			top=this.limitYMax;
			
		if(this.limitYMin!=null&&top<this.limitYMin)
			top=this.limitYMin;
		
		this.htmlElement.style.top  = top+"px";
		return false;
	},
	/*
	 * This stops the dragging behaviour
	 */
	stopObservingMain: function(){
		Event.stopObserving(document, "mousemove", this.boundMouseMainMoveListener);
		Event.stopObserving(document, "mouseup", this.boundStopObservingMain);
		this.onDragEnd();
	}
}
 
function ReisenetControl() {}
ReisenetControl.prototype = new GControl();

ReisenetControl.prototype.initialize = function(map) {
  this.isOpen = true;
  this.map = map;
  this.container = document.createElement("div");
  this.container.style.overflow = "hidden";
  this.container.className = "mapFilter";
  map.getContainer().appendChild(this.container);
  Templates.getTemplate("anzeigeoptionen", function(template){
  		this.container.innerHTML=template.process(this, {throwExceptions: true});
		$("welt-head-box").style.overflow = "hidden";
		$('welt-head-box-toggle').onclick=function(){
			if(this.isOpen){
				this.height = Element.getDimensions($("welt-head-box")).height;
				$("welt-head-box").style.height = "26px";
				$("toggleImage").src = "/img/welt/w_icn_open.gif";
				this.isOpen = false;
			}else{
				$("welt-head-box").style.height = this.height+"px";
				$("toggleImage").src = "/img/welt/w_icn_close.gif";
				this.isOpen = true;
			}
		}.bind(this)
  }.bind(this));
  
  return this.container;
}

ReisenetControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0, 0));
}


var reisenet = {};
reisenet.logger = maptales.getLogger("reisenetlogger");
reisenet.service = {};
reisenet.service.zoomLockItem = null;
reisenet.service.lockFunction = function(){
	if(reisenet.service.zoomLockItem!=null)
		maptales.ui.getMainMap().panTo(reisenet.service.zoomLockItem.get("location"));
}


reisenet.service.enableZoomLock = function(object){
	if(object instanceof Media){
		var mapobject = object.getRefFromCache("mapobject");
		reisenet.service.zoomLockItem = mapobject;
		GEvent.addListener(maptales.ui.getMainMap().gmap, "zoomend", reisenet.service.lockFunction);
	}
}

reisenet.service.disableZoomLock = function(){
	reisenet.service.zoomLockItem = null;
}



function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

reisenet.getViewRightIcon = function(id){
	var contextObject = $O(id);
	var base = "/welt-entdecken/css/images/";
	if(contextObject.get("viewRight") == RIGHT_GROUP){
		return base+"publish_yellow.gif";
	}else if(contextObject.get("viewRight") == RIGHT_PRIVATE){
		return base+"publish_red.gif";
	}else{
		return base+"publish_green.gif";
	}
}

reisenet.setRights = function(id, form){
	var objsToPersist = [];
	var contextObject = $O(id);
	
	alert(getCheckedValue(form.elements['view_right']));
	contextObject.setRight("view", getCheckedValue(form.elements['view_right']));
	objsToPersist.push(contextObject);
	
	
	maptales.service.persist(objsToPersist, function(reply){ 
		 if(reply instanceof SnapMapException){
				//this.display("rightsManager/error");
				alert("Fehler");
		 }
		 else{
		 		Dialog.closeAll();
				//Actions.initAction("dialogDestroy", null,null,this.container);
		 }
	}.bind(this));
}


reisenet.flagItem = function(id){
	var pars = "parameters=" + JSON.stringify({id: id}); 
	maptales.rpc.callRPC("/flagItem", pars, "post", function(reply){	
		if(reply.wasSuccessful()){
        	// callback(reply.getData());
        }
        else{
        	 //ajaxLog.warn("flagItem returned error. message: "+reply.getReplyMessage());
        }     
	});
}

reisenet.service.updateMapFilter = function(){
	var redaktion = $('anzeigeoptionenRedaktion');
	var user = $('anzeigeoptionenUser');
	maptales.ui.service.query.setGroupModeratorFilter(redaktion.checked);
	maptales.ui.service.query.setGroupMemberFilter(user.checked);
	maptales.ui.service.query.search();
}

reisenet.selectMenu = function(id){
	if(id == null) return;
	var liElement = $('navi_'+id);
	if(liElement==null) return;
	var ulElement = liElement.parentNode;
	Element.cleanWhitespace(ulElement);
	for(var i=0; i<ulElement.childNodes.length; i++){
		ulElement.childNodes[i].className = "";
	}
	
	liElement.className = "on";
}


reisenet.weltkarte = {};

reisenet.weltkarte.fotos = function(id){
	reisenet.selectMenu(id);
	reisenet.weltkarte.prepare();
	loadPage("weltkarte/fotos");
}

reisenet.weltkarte.tipps = function(id){
	reisenet.selectMenu(id);
	reisenet.weltkarte.prepare();
	loadPage("weltkarte/tipps");
}

reisenet.weltkarte.videos = function(id){
	reisenet.selectMenu(id);
	reisenet.weltkarte.prepare();
	loadPage("weltkarte/videos");
}

reisenet.weltkarte.posts = function(id){
	reisenet.selectMenu(id);
	reisenet.weltkarte.prepare();
	loadPage("weltkarte/posts");
}

reisenet.weltkarte.neues = function(id){
	reisenet.selectMenu(id);
	reisenet.weltkarte.prepare();
	loadPage("weltkarte/neues");
}

reisenet.weltkarte.lieblingsorte = function(id){
	reisenet.selectMenu(id);
	reisenet.weltkarte.prepare();
	loadPage("weltkarte/fotos");
}

reisenet.weltkarte.stories = function(id){
	reisenet.selectMenu(id);
	reisenet.weltkarte.prepare();
	loadPage("weltkarte/stories");
}

reisenet.weltkarte.prepare = function(){
	maptales.ui.getMainMap().setCenter(new GLatLng(37.16031654673677, 51.85546875), 3);
	maptales.ui.service.query.startQueryBatch();
	maptales.ui.service.query.clearTags();
	maptales.ui.getMainMap().setToQueryMode(new Query({type:"medias", locally: true, clustered: true, tags: maptales.ui.service.query.getTags()}));
}

reisenet.service.addThis = function(type, id, title, event){
	addthis_url=reisenet.service.getLink(type, id); 
	addthis_title= title+' - Reisenet'; 
	addthis_click(Event.element(event));
}

reisenet.service.getLink = function(type, id){
	if(type=="story"){
		return clientConfig.baseURL+"/weltkarte/?storyId="+id; 
	}else{
		return clientConfig.baseURL+"/weltkarte/?mediaId="+id; 
	}
}

reisenet.service.makeProfileImage = function(num){
	reisenet.selectMenu(num);
	loadPage("ich/selectProfileImage");
}

reisenet.service.copyrightElement = document.createElement("div");
reisenet.service.copyrightElement.className="copyrightText";
reisenet.service.copyrightIsDisplayed = false;
reisenet.service.displayCopyright = function(id, event){
	if(id==null||reisenet.service.copyrightIsDisplayed==true) return;
	var object = $O(id);
	if(object instanceof Media){
		var text = object.get("copyright");
		if(text != null && text.length > 0){
			reisenet.service.copyrightElement.innerHTML = text;
			document.body.appendChild(reisenet.service.copyrightElement);
			reisenet.service.positionCopyright(event);
			reisenet.service.copyrightIsDisplayed = true;
		}
	}
}

reisenet.service.positionCopyright = function(event){
	if(reisenet.service.copyrightIsDisplayed == true){
		var x = parseInt(Event.pointerX(event));//+reisenet.service.copyrightElement.offsetHeight;
		var y = parseInt(Event.pointerY(event));//+reisenet.service.copyrightElement.offsetWidth;
		reisenet.service.copyrightElement.style.top = y+"px";
		reisenet.service.copyrightElement.style.left = x+"px";
	}
}

reisenet.service.hideCopyright = function(){
	try{
		document.body.removeChild(reisenet.service.copyrightElement);
		reisenet.service.copyrightIsDisplayed = false;
	}catch(e){

	}
}


reisenet.service.search = function(inputId){
	try{
		
		//check what to search for
		var inputs = maptales.ui.getFormHashMap(inputId);
		var searchString = inputs["searchString"];
		
		//check if limited to redaktion
		if(inputs.redakteurFilter==true||inputs.redakteurFilter=="true"){
			maptales.ui.service.query.setMap(13035);
		}else{
			maptales.ui.service.query.setMap(null);
		}
		
		
		maptales.ui.service.query.setGroupModeratorFilter(inputs["redakteurFilter"] == "true");
		maptales.ui.service.query.setGroupMemberFilter(inputs["memberFilter"] == "true");
	
		if(inputs["inhalt"]){
			var inhalt = (inputs["inhalt"] == "true");
		}else{
			var inhalt = true;
		}
		
		if(inputs["ort"]!=null){
			var ort = (inputs["ort"] == "true");
		}else{
			var ort = true;
		}
		
		var parameters = {ort: ort, inhalt: inhalt};

		reisenet.service.searchString(searchString, parameters);
	}catch(e){
		reisenet.logger.error("Search konnte nicht durchgeführt werden", e)
	}
}

reisenet.service.searchString = function(searchString, parameters){
	maptales.ui.service.query.startQueryBatch();
	maptales.ui.service.query.clearCache();
	
	
	//set search query
	maptales.ui.service.query.setTag(searchString); 
	
	//search for items in group
	maptales.ui.service.query.setGroup(maptales.ui.groupId);
	
	maptales.ui.getMainMap().setToQueryMode(new Query({type:"medias", locally: true, clustered: true, tags: maptales.ui.service.query.getTags()}));
	maptales.ui.setMapItemClickVariables("pages/search/mediaItem", null);
	
	
	
	if(parameters == null){
		var parameters = {ort: true, inhalt: true};
	}
	
	loadPage("search/ergebnisse", parameters);
}


reisenet.service.media = {};
reisenet.service.media.persist = function(objectId, formId){
	try{
		var inputs = maptales.ui.getComponent("contentPanel").getFormHashMap(formId);
		var object = $O(objectId);
		object.set("text", inputs['text']);
		object.set("title", inputs['titel']);
		//tags
		
		maptales.rpc.persist(object, function(reply){
			if(reply instanceof SnapMapException){
				loadPage("error", {titel: "Wir konnten die Änderungen nicht abspeichern.", message:"Es traten Probleme beim abspeichern auf."});
			}else{
				loadPage("media/page", null, object);
			}
		});
	}catch(e){
		reisenet.logger.error("Konnte Media nicht speichern", e);
	}
}


reisenet.service.storeStatus = function(statusString, display, inputField, string){
	display.innerHTML = statusString;
	maptales.rpc.user.storeStatus({status: statusString}, function(statusStringReply){
		display.innerHTML = statusStringReply;
		inputField.value = string;
	});
}


reisenet.service.ich = {};
reisenet.service.ich.auswahl = {};
reisenet.service.ich.meineEintraege = function(event){
	reisenet.selectMenu(event);
	if(maptales.ui.getCurrentUser()!=null){
		maptales.ui.getCurrentUser().clearSlot("medias");
	}
	loadPage('ich/meineEintraege');
}

reisenet.service.ich.auswahlLoeschen = function(){
	var objsToDelete = [];
	for(auswahl in reisenet.service.ich.auswahl){
		objsToDelete.push(auswahl);
	}
	maptales.rpc.deleteById({ids: objsToDelete}, function(reply){
		if(reply instanceof SnapMapException){
			loadPage("error", {title: "Fehler Beim löschen", message: "Ihre Einträge konnten nicht gelöscht werden."});
		}else{
			reisenet.service.ich.auswahl = {};
			reisenet.service.ich.meineEintraege();
		}
	});
}


reisenet.service.ich.auswahlHinzufuegen = function(id, container, event){
	var htmlElement = Event.element(event);
	var checkElement = $("auswahl_"+id);
	
	if(checkElement!=htmlElement){
		checkElement.checked = !checkElement.checked;
	}
	
	bool = checkElement.checked;
	if(bool==true){
		reisenet.service.ich.auswahl[id] = true;
		container.className = "on";
	}else{
		reisenet.service.ich.auswahl[id] = false;
		container.className = "";
	}
}


reisenet.service.ich.istAusgewaehlt = function(id){
	var val = reisenet.service.ich.auswahl[id];
	if(val==null)return false;
	return val;
}

/*
 * Text
 */
reisenet.service.text = {};
reisenet.service.text.currentText = null;
reisenet.service.text.currentTags = [];
reisenet.service.text.textVerfassen = function(event){
	reisenet.selectMenu(event);
	loadPage("text/verfassen");
}


reisenet.service.text.addTag = function(inputId, listId){
	if(reisenet.service.text.currentTags.length==0){
		$(listId).innerHTML="";
	}
	reisenet.service.text.currentTags.push(maptales.service.create("Tag", {tag:$(inputId).value}));
	reisenet.service.addTagToDOM(inputId, listId, "reisenet.service.text.removeTag", reisenet.service.text.currentTags);
}

reisenet.service.text.removeTag = function(index){
	reisenet.service.text.currentTags.splice(index, 1);
}

reisenet.getCurrentDisplayName = function(){
	try{
		return maptales.ui.getCurrentUser().get("firstName")+" "+maptales.ui.getCurrentUser().get("lastName");
	}catch(e){
		return "anonymous";
	}
}

reisenet.service.text.textSpeichern = function(id){
	try{
		reisenet.service.text.currentText = maptales.service.create("Post");
		var inputs = maptales.ui.getComponent("contentPanel").getFormHashMap(id);
		post = reisenet.service.text.currentText;
		post.set("text", inputs["text"]);
		post.set("title", inputs["titel"]);
		post.set("viewRight", RIGHT_PUBLIC);
		post.set("creationDate", new Date());
		post.set("timestamp", new Date());
		post.creatorDisplayName = reisenet.getCurrentDisplayName();
		if(reisenet.service.text.currentTags.length>0){
			post.addToSlot("tags", reisenet.service.text.currentTags);
			post.setSlotLength("tags", reisenet.service.text.currentTags.length);
		}
		
		maptales.rpc.store(post, function(reply){
			if(reply instanceof SnapMapException){
				loadPage("error", {title: "Fehler Beim speichern des Textes", message: reply.getMessage()});
			}else{
				//reisenet.service.text.currentText = reply[0];
				loadPage("text/platzieren");
			}
		});
	}catch(e){
		reisenet.logger.error("Text konnte nicht gespeichert werden", e);
	}
}

reisenet.service.text.publizieren = function(){
	if(reisenet.service.text.currentText.getRefFromCache("mapobject")!=null){
		reisenet.service.text.currentText.getRefFromCache("mapobject").set("viewZoomLevel", maptales.ui.getMainMap().getZoom());
		reisenet.service.text.currentText.getRefFromCache("mapobject").set("definitionZoomLevel", maptales.ui.getMainMap().getZoom());
		
		maptales.service.persist(reisenet.service.text.currentText.getRefFromCache("mapobject"), function(reply){});	
	}	
	
	maptales.service.group.addMedias({groupId: maptales.ui.groupId, mediaId: reisenet.service.text.currentText.id}, function(reply){
		if(reply instanceof SnapMapException){
			loadPage("error", {title: "Fehler Beim publizieren", message: reply.getMessage()});
		}else{
			loadPage("text/danke");
		}
	});
	
}

/*
 * Video
 */
reisenet.service.video = {};
reisenet.service.video.currentVideo = null;
reisenet.service.video.idEingeben = function(event){
	reisenet.selectMenu(event);
	loadPage('video/verknuepfen'); 
}
reisenet.service.video.verknuepfen = function(id){
	var inputs = maptales.ui.getComponent("contentPanel").getFormHashMap(id);
	if(inputs.urls==null||inputs.urls.length<1){
		loadPage("error", {title: "Wir konnten das Video nicht verknüpfen", message: reply.getMessage()});
	}
	
	maptales.service.importVideos({urls: "http://youtube.com/watch?v="+inputs.urls}, function(reply){
		if(reply instanceof SnapMapException){
			loadPage("error", {title: "Wir konnten das Video nicht verknüpfen", message: reply.getMessage()});
		}else{
			reisenet.service.video.currentVideo = reply[0];
			loadPage("video/platzieren");
		}
	});
}
reisenet.service.video.zoom = function(){
	if(reisenet.service.video.currentVideo.getRefFromCache("mapobject")!=null){
		reisenet.service.video.currentVideo.getRefFromCache("mapobject").set("viewZoomLevel", maptales.ui.getMainMap().getZoom());
		reisenet.service.video.currentVideo.getRefFromCache("mapobject").set("definitionZoomLevel", maptales.ui.getMainMap().getZoom());
		
		maptales.service.persist(reisenet.service.video.currentVideo.getRefFromCache("mapobject"), function(reply){});	
	}
	
	maptales.service.group.addMedias({groupId: maptales.ui.groupId, mediaId: reisenet.service.video.currentVideo.id}, function(reply){
		if(reply instanceof SnapMapException){
			loadPage("error", {title: "Es ist ein Fehler beim abspeichern aufgetreten", message: reply.getMessage()});
		}else{
			loadPage("video/beschreiben");
		}
	});
}

reisenet.service.video.publizieren = function(formId){
	var inputs = maptales.ui.getComponent("contentPanel").getFormHashMap(formId);
	reisenet.service.video.currentVideo.set("title", inputs["titel"]);
	reisenet.service.video.currentVideo.set("text", inputs["text"]);
	reisenet.service.video.currentVideo.set("viewRight", RIGHT_PUBLIC);
	reisenet.service.video.currentVideo.set("creationDate", new Date());
	reisenet.service.video.currentVideo.set("timestamp", new Date());
	reisenet.service.video.currentVideo.creatorDisplayName = reisenet.getCurrentDisplayName();
	maptales.service.persist(reisenet.service.video.currentVideo, function(reply){
		if(reply instanceof SnapMapException){
			loadPage("error", {title: "Wir konnten das Video nicht publizieren", message: reply.getMessage()});
		}else{
			loadPage("video/danke");
		}	
	});
}



/*
 * Foto
 */
reisenet.service.foto = {};
reisenet.service.foto.hochladen = function(event){
	reisenet.selectMenu(event);
	reisenet.service.foto.currentFoto = null;
	reisenet.service.foto.currentTags = [];
	maptales.rpc.uploadedObjects = [];
	loadPage('photo/hochladen'); 
}

reisenet.service.foto.hochladenCallback = function(){
	reisenet.service.foto.currentFoto = maptales.rpc.uploadedObjects[0];
	loadPage('photo/platzieren');
}

reisenet.service.foto.addTag = function(inputId, listId){
	if(reisenet.service.foto.currentTags.length==0){
		$(listId).innerHTML="";
	}
	reisenet.service.foto.currentTags.push(maptales.service.create("Tag", {tag:$(inputId).value}));
	reisenet.service.addTagToDOM(inputId, listId, "reisenet.service.foto.removeTag", reisenet.service.foto.currentTags);
}

reisenet.service.foto.removeTag = function(index){
	reisenet.service.foto.currentTags.splice(index, 1);
}

reisenet.service.foto.zoom = function(){
	//set all markers
	var markers = [];
	for(var i=0; i<maptales.rpc.uploadedObjects.length; i++){
		if(maptales.rpc.uploadedObjects[i].getRefFromCache("mapobject")!=null){
			var marker = maptales.rpc.uploadedObjects[i].getRefFromCache("mapobject");
			marker.set("viewZoomLevel", 	  maptales.ui.getMainMap().getZoom());
			marker.set("definitionZoomLevel", maptales.ui.getMainMap().getZoom());
			markers.push(marker);
		}
	}

	if(markers.length>0){
		maptales.service.persist(markers, function(reply){
			if(reply instanceof SnapMapException){
				loadPage("error", {title: "Es ist ein Fehler beim abspeichern aufgetreten", message: "Das Zoomlevel konnte nicht gespeichert werden"});
			}else{
				reisenet.service.foto.addToGroup();
			}
		});
	}else{
		reisenet.service.foto.addToGroup();
	}	
		
	
}

reisenet.service.foto.addToGroup = function(){
	maptales.service.group.addMedias({groupId: maptales.ui.groupId, mediaIds: maptales.rpc.getUploadedIds()}, function(reply){
		if(reply instanceof SnapMapException){
			loadPage("error", {title: "Es ist ein Fehler beim abspeichern aufgetreten", message: reply.getMessage()});
		}else{
			loadPage("photo/beschreiben");
		}
	});
}


reisenet.service.foto.publizieren = function(formId){
	
	var inputs = maptales.ui.getComponent("contentPanel").getFormHashMap(formId);
	
	for(var i=0; i<maptales.rpc.uploadedObjects.length; i++){
		maptales.rpc.uploadedObjects[i].set("title", inputs["titel_"+i]);
		maptales.rpc.uploadedObjects[i].set("text", inputs["text_"+i]);
		maptales.rpc.uploadedObjects[i].set("viewRight", RIGHT_PUBLIC);
		maptales.rpc.uploadedObjects[i].set("creationDate", new Date());
		maptales.rpc.uploadedObjects[i].set("timestamp", new Date());
		maptales.rpc.uploadedObjects[i].creatorDisplayName = reisenet.getCurrentDisplayName();
		
		if(reisenet.service.foto.currentTags.length>0){
			maptales.rpc.uploadedObjects[i].addToSlot("tags", reisenet.service.foto.currentTags);
			maptales.rpc.uploadedObjects[i].setSlotLength("tags", reisenet.service.foto.currentTags.length);
		}
		
	}
	
	maptales.service.persist(maptales.rpc.uploadedObjects, function(reply){
		if(reply instanceof SnapMapException){
			loadPage('error', {title: "Wir konnten das Foto nicht publizieren", message: reply.getMessage()}); 
		}else{
			loadPage('photo/danke'); 
		}
	});
}



/*
 * Photoshow
 */
reisenet.service.fotoshow = {};
reisenet.service.fotoshow.hochladen = function(event){
	reisenet.selectMenu(event);
	reisenet.service.fotoshow.currentFotoshow = null;
	reisenet.service.fotoshow.currentTags = [];
	loadPage('photoshow/hochladen'); 
}
reisenet.service.fotoshow.placeImages = function(){
	loadPage('photoshow/platzieren'); 
}

reisenet.service.fotoshow.addTag = function(inputId, listId){
	if(reisenet.service.fotoshow.currentTags.length==0){
		$(listId).innerHTML="";
	}
	reisenet.service.fotoshow.currentTags.push(maptales.service.create("Tag", {tag:$(inputId).value}));
	reisenet.service.addTagToDOM(inputId, listId, "reisenet.service.fotoshow.removeTag", reisenet.service.fotoshow.currentTags);
}

reisenet.service.fotoshow.removeTag = function(index){
	reisenet.service.fotoshow.currentTags.splice(index, 1);
}

reisenet.service.fotoshow.storeZoom = function(){
	if(maptales.rpc.uploadedObjects[0].getRefFromCache("mapobject")==null){
		maptales.rpc.uploadedObjects[0].getRefFromCache("mapobject").set("viewZoomLevel", maptales.ui.getMainMap().getZoom());
		maptales.rpc.uploadedObjects[0].getRefFromCache("mapobject").set("definitionZoomLevel", maptales.ui.getMainMap().getZoom());
		maptales.rpc.persist(maptales.rpc.uploadedObjects[0].getRefFromCache("mapobject"), function(reply){
			if(reply instanceof SnapMapException){
				loadPage("error", {titel: "Wir konnten das Zoomlevel nicht abspeichern", message:"Es traten Probleme beim abspeichern des Zoomlevels auf."});
			}else{
				loadPage("photoshow/beschreiben");
			}
		});
	}else{
		loadPage("photoshow/beschreiben");
	}
}

reisenet.service.fotoshow.publizieren = function(formId){
	try{
		reisenet.service.fotoshow.currentFotoshow = maptales.service.create("Story", {});
		var inputs = maptales.ui.getComponent("contentPanel").getFormHashMap(formId);
		reisenet.service.fotoshow.currentFotoshow.set("title", inputs["titel"]);
		reisenet.service.fotoshow.currentFotoshow.set("text", inputs["text"]);
		reisenet.service.fotoshow.currentFotoshow.set("viewRight", RIGHT_PUBLIC);
		reisenet.service.fotoshow.currentFotoshow.set("creationDate", new Date());
		reisenet.service.fotoshow.currentFotoshow.set("timestamp", new Date());
		reisenet.service.fotoshow.currentFotoshow.set("mainImage", maptales.rpc.uploadedObjects[0]);
		
		maptales.service.store(reisenet.service.fotoshow.currentFotoshow, function(reply){
			if(reply instanceof SnapMapException){
				loadPage('error', {title: "Wir konnten Ihre Fotoshow nicht publizieren", message: reply.getMessage()}); 
			}else{
				if(reisenet.service.fotoshow.currentTags.length>0){
					reisenet.service.fotoshow.currentFotoshow.addToSlot("tags", reisenet.service.fotoshow.currentTags);
					reisenet.service.fotoshow.currentFotoshow.setSlotLength("tags", reisenet.service.fotoshow.currentTags.length);
				}
				
				reisenet.service.fotoshow.currentFotoshow.addToSlot("medias", maptales.rpc.uploadedObjects);
				
				var objectsToPersist = [];
				for(var i=0; i<maptales.rpc.uploadedObjects.length; i++){
					if(inputs["bildbeschreibung_"+i]!=null&&inputs["bildbeschreibung_"+i].length>0){
						maptales.rpc.uploadedObjects[i].set("text", inputs["bildbeschreibung_"+i]);
						
					}
					maptales.rpc.uploadedObjects[i].set("viewRight", RIGHT_PUBLIC);
					objectsToPersist.push(maptales.rpc.uploadedObjects[i]);
				}
				
				objectsToPersist.push(reisenet.service.fotoshow.currentFotoshow);
				
				maptales.service.persist(objectsToPersist, function(reply){
					if(reply instanceof SnapMapException){
						loadPage('error', {title: "Wir konnten Ihre Fotos nicht abspeichern", message: reply.getMessage()}); 
					}else{
						
						maptales.service.group.addMedias({groupId: maptales.ui.groupId, mediaIds: maptales.rpc.getUploadedIds()}, function(){
							if(reply instanceof SnapMapException){
								loadPage('error', {title: "Wir konnten Ihre Fotoshow nicht publizieren", message: reply.getMessage()}); 
							}else{
								loadPage('photoshow/danke'); 
							}
						});
						
					}
				});
			}
		});
	}catch(e){
		reisenet.logger.error("Konnte Fotoshow nicht publizieren", e);
	}
}

/*
 * Story anlegen
 */

reisenet.service.story = {};
reisenet.service.story.anlegen = function(event){
	reisenet.selectMenu(event);
	maptales.ui.service.user.getCurrentUser().clearSlot("medias");
	$m("setForceLineDrawing", true);
	loadPage("story/auswaehlen");
	reisenet.service.story.currentStory = null;
	reisenet.service.story.auswahl = {};
}

reisenet.service.story.auswahlHinzufuegen = function(id, container, event){
	var htmlElement = Event.element(event);
	var checkElement = $("auswahl_"+id);
	
	if(checkElement!=htmlElement){
		checkElement.checked = !checkElement.checked;
	}
	
	bool = checkElement.checked;
	if(bool==true){
		reisenet.service.story.auswahl[id] = true;
		container.className = "on";
	}else{
		reisenet.service.story.auswahl[id] = false;
		container.className = "";
	}
}

reisenet.service.story.istAusgewaehlt = function(id){
	var val = reisenet.service.story.auswahl[id];
	if(val==null)return false;
	return val;
}

reisenet.service.story.auswaehlen = function(){
	var story = maptales.service.create("Story");
	
	reisenet.service.story.currentStory = story;
	
	var medias = [];
	for(id in reisenet.service.story.auswahl){
		if(reisenet.service.story.auswahl[id]==true){
			medias.push($O(id));
		}
	}
	
	story.addToSlot("medias", medias);
	
	maptales.rpc.store(story, function(reply){
		if(reply instanceof SnapMapException){
			loadPage('error', {title: "Wir konnten Ihre Story nicht abspeichern", message: reply.getMessage()}); 
		}else{
			$m('clearAllOverlays');
			$m('addQueryOverlays', medias);
			$m('showObjectBounds', medias)
			loadPage("story/sortieren");
		}	
	});
}

reisenet.service.story.eintragEntfernen = function(id){
	reisenet.service.story.currentStory.removeFromSlot("medias", id);
	reisenet.service.story.currentStory.cleanSlot("medias"); //clean it, since it was removed through persist of the collection item
	var obj = $O(id);
	if (obj instanceof Media) {
		obj.set("story", 0);
		obj.persist();
	}
}

reisenet.service.story.erstesBild = function(story){
	var medias = story.getSlotFromCache("medias", 0, 1);
	if(medias !=null){
		for(var i=0; i<medias.length; i++){
			if(medias[i] instanceof Picture){
				return medias[i];
			}
		}
	}else{
		return null;
	}
}

reisenet.service.story.beschreiben = function(formId){
	var inputs = maptales.ui.getComponent("contentPanel").getFormHashMap(formId);
	reisenet.service.story.currentStory.set("title", inputs["titel"]);
	reisenet.service.story.currentStory.set("text", inputs["text"]);
	reisenet.service.story.currentStory.set("viewRight", RIGHT_PUBLIC);
	reisenet.service.story.currentStory.set("creationDate", new Date());
	reisenet.service.story.currentStory.set("timestamp", new Date());
	
	try{
		reisenet.service.story.currentStory.set("mainImage", reisenet.service.story.erstesBild(reisenet.service.story.currentStory));
	}catch(e){
		reisenet.logger.error("Konnte Bild nicht setzen", e);
	}
	
	if(reisenet.service.story.currentTags.length>0){
		reisenet.service.story.currentStory.addToSlot("tags", reisenet.service.story.currentTags);
		reisenet.service.story.currentStory.setSlotLength("tags", reisenet.service.story.currentTags.length);
	}

	maptales.service.persist(reisenet.service.story.currentStory, function(reply){
		if(reply instanceof SnapMapException){
			loadPage('error', {title: "Wir konnten Ihre Story nicht abspeichern", message: reply.getMessage()}); 
		}else{
			loadPage("story/danke");
		}
	});
}

reisenet.service.story.currentTags = [];
reisenet.service.story.addTag = function(inputId, listId){
	if(reisenet.service.story.currentTags.length==0){
		$(listId).innerHTML="";
	}
	reisenet.service.story.currentTags.push(maptales.service.create("Tag", {tag:$(inputId).value}));
	reisenet.service.addTagToDOM(inputId, listId, "reisenet.service.story.removeTag", reisenet.service.story.currentTags);
}

reisenet.service.story.removeTag = function(index){
	reisenet.service.story.currentTags.splice(index, 1);
}

reisenet.service.story.connectionLines = {};
reisenet.service.story.connectionLinesRevertHTML = {};
reisenet.service.story.connect = function(id1, id2, containerId){
	try{
		var container = maptales.ui.getComponent("contentPanel").getElement(containerId);
		
		Templates.getTemplate("pages/story/automatischVerbinden", function(template){
			reisenet.service.story.connectionLinesRevertHTML[id1+"_"+id2] = container.innerHTML;
			container.innerHTML=template.process({id1: id1, id2: id2}, {throwExceptions: true});
		});
		
		var marker1 = $O(id1).getRefFromCache("mapobject");
		var marker2 = $O(id2).getRefFromCache("mapobject");
		
		var properties = {creator: maptales.service.user.getCurrentUserId(),
							definitionZoomLevel: maptales.ui.getMainMap().gmap.getZoom(),
							viewZoomLevel: maptales.ui.getMainMap().gmap.getZoom(),
	        				controlpoints: [marker1.get("location"), marker2.get("location")],
							startMarker: marker1, 
							endMarker: marker2};
	                
	                
	    var lineMedia = maptales.service.create("Post", {});
	                
		var line = maptales.service.create("Line", properties);
		
		line.set("startMarker", marker1);
		line.set("endMarker", marker2);
		
		line.setSlotLength("medias", 0);
	    line.addToSlot("medias", lineMedia);
	    
	    marker1.addOutgoingLine(line);
	    marker2.addIncomingLine(line);
	    
		maptales.ui.getMainMap().addQueryOverlay(line);
		reisenet.service.story.connectionLines[id1+"_"+id2] = line;
		
	}catch(e){
		reisenet.logger.error("Could not connect automatically: id1: "+id1+", id2: "+id2+", container: "+containerId, e);
	}
}

reisenet.service.story.cancelConnect = function(id1, id2, formId){
	var line = reisenet.service.story.connectionLines[id1+"_"+id2];
	maptales.ui.getMainMap().removeQueryOverlay(line);
	var container = maptales.ui.getComponent("contentPanel").getElement(formId);
	container.parentNode.innerHTML = reisenet.service.story.connectionLinesRevertHTML[id1+"_"+id2];
	reisenet.service.story.connectionLines[id1+"_"+id2] = null;
}

reisenet.service.story.storeConnection = function(id1, id2, formId){
	try{
		var line = reisenet.service.story.connectionLines[id1+"_"+id2];
		
		var inputs = maptales.ui.getComponent("contentPanel").getFormHashMap(formId);
		
		
		try{
			var newTimestamp = ($O(id1).get("timestamp").getTime()+$O(id2).get("timestamp").getTime())/2;
			var lineMedia = line.getSlotFromCache("medias", 0, 1)[0];
			lineMedia.set("timestamp", newTimestamp);
			lineMedia.set("titel", inputs["titel"]);
			lineMedia.set("text", inputs["text"]);
			lineMedia.set("viewRight", RIGHT_PUBLIC);
			lineMedia.set("story", reisenet.service.story.currentStory);
		}catch(e){
			reisenet.logger.error("Could not set Timestamp of Lines Media item", e);
		}
		
		if(line!=null){
			maptales.rpc.store(line, function(reply){
				if(reply instanceof SnapMapException){
					reisenet.logger.error("Konnte Pfad nicht abspeichern, "+reply.getMessage());
				}else{
					var container = maptales.ui.getComponent("contentPanel").getElement(formId);
					Templates.getTemplate("pages/story/afterAutomatischVerbinden", function(template){
  						container.parentNode.innerHTML=template.process({lineMedia: lineMedia}, {throwExceptions: true});
					});
					lineMedia.set("mapobject", line);	
				}
			});
		}else{
			reisenet.logger.error("Konnte Marker nicht verbinden.")	
		}
	}catch(e){
		reisenet.logger.error("Konnte Marker nicht verbinden", e);
	}
}

reisenet.service.story.canBeConnected = function(id1, id2){
	if(id1==null||id2==null)return false;
	try{
		if(id2!=null){
			var marker1 = $O(id1).getRefFromCache("mapobject");
			var marker2 = $O(id2).getRefFromCache("mapobject");
			if( marker1 instanceof Marker &&
			 	marker2 instanceof Marker &&
			 	marker1.id!=marker2.id){
			 		return true;
			 }else{
			 	return false;	
			 }
		}else{
			return false;
		}
	 }catch(e){
	 	return false;
	 }
}

/*
 * Functionality
 */
reisenet.service.addTagToDOM = function(inputId, listId, functionName, tagList){
	var tag = $(inputId).value;
	var list = $(listId);
	
	var li = document.createElement("li");
	li.innerHTML = tag + "<a href='#' onclick='"+functionName+"("+(tagList.length-1)+"); reisenet.service.removeTag(this); return false;'>[x]</a>";

	if(list!=null){
		list.appendChild(li);
	}
	
	$(inputId).value = "";
}

reisenet.service.removeTag = function(element){
	var li = element.parentNode;
	var ul = li.parentNode;
	ul.removeChild(li);
}


var loadPage = function(page, parameters, contextObject){
	reisenet.service.disableZoomLock();
	maptales.ui.getComponent("contentPanel").getContainer().innerHTML = "";
	maptales.ui.gotoPath(contextObject, "pages/"+page, parameters);
}

var loginMaptales = function(id){
	var element = $(id);
	var userName = document.getChildById("name" , element).value;
	var pass = document.getChildById("pass" , element).value;
	
	maptales.rpc.user.login({name: userName, pass: pass}, function(reply){
		if(reply instanceof SnapMapException){
			loadPage("login");
		}else{
			loadPage("nachLogin");
		}
	});
}



/*
 * Root Widget
 */
var ReisenetApplication = Class.create();

Object.extend(Object.extend(ReisenetApplication.prototype, Widget.prototype), {
	logger:  maptales.getLogger("com.maptales.webclient.ReisenetApplication"),
	initialize: function(container, groupId, config, loadMapQueryOnStart){
		this.loadMapQueryOnStart = loadMapQueryOnStart;
		var browserLayout = new log4javascript.PatternLayout("%c %d{HH:mm:ss} %-5p - %m%n");
		var browserAppender = new log4javascript.BrowserConsoleAppender(this.browserLayout);
		maptales.addRootAppender(browserAppender);

		this.setDefaultMapSyncParameters();
		
		this.boundSetMapMode = this.setMapMode.bind(this);
		
		maptales.event.registerEventListener("setMapMode", this.boundSetMapMode);
		
		maptales.ui = this;
		this.service = maptales.service;
		
		this.service.query.setGroupFilter(groupId);
		
		//configure domain object
		maptales.setConfig(config);
		
		maptales.rpc.addLoadingListener(this.onLoading.bind(this));

		if(config.loggedInUser){
			this.service.user.setCurrentUser(maptales.cache.makeObjects(config.loggedInUser));
		}
		
		this.groupId = groupId;
		this.domain = maptales;
		this.container = container;
		this.appName = "Maptales";
		
		this.historyController = new HistoryController();
	    
	    this.rootViews = {
				welcome: {name: "Welcome", template:"MapTales/MapTalesIntro",  menuItem: true}
		};
		
		this.defaultView = "browse";
			
	    this.urlToViewMappings = {
				defaultMapping: "browse",
				welcome: "welcome",
				view: "view",
				tags: "browse",
				browse: "browse",
				register: "register"
		};
		
	    
	    // detect browser
	    if ((BrowserDetect.browser == "Safari" && BrowserDetect.version > 10 && BrowserDetect.version < 420) // Safari 2.x
	    	|| BrowserDetect.browser == "unknown") {
	    	Line.prototype.doShadows = false;
	    }
		
		this.initializeWidget(this.container, null, null, null, null, null, true);
		
		//this gets notified when the server seems to be down
		maptales.rpc.addServerOfflineCallback(this.onServerOffline.bind(this));
		
		this.boundOnSessionExpirationCallback = this.onSessionExpirationCallback.bind(this);
		
		//if the user is logged in already then check if the session expires
		if(maptales.service.user.getCurrentUser()!=null){
			maptales.rpc.checkServerSessionTimeout();
			maptales.rpc.addSessionExpirationCallback(this.boundOnSessionExpirationCallback);
		}
		
		this.boundLoginListener = this.onLogin.bind(this);
        maptales.service.user.addLoginListener(this.boundLoginListener);
		
		//container, parent, contextObject, view, templatePath, parameters, useInnerHtml
		this.mainMap = new MapWidget($('mainMapContainer'), this, null, null, null, {}, true);
		this.contentPanel = new PageWidget($('main'), this, null, null, null, {templatePath: "pages/login"}, true);
		
		this.setComponent("map", this.mainMap);
		this.setComponent("contentPanel", this.contentPanel);
		
		if(maptales.getURLParameter("goto")){
			var goto = maptales.getURLParameter("goto");
			if(goto == "textVerfassen"){
				reisenet.service.text.textVerfassen(17);
			}else if(goto == "fotoHochladen"){
				reisenet.service.foto.hochladen(15);
			}else if(goto == "fotoshow"){
				reisenet.service.fotoshow.hochladen(545);
			}else if(goto == "meineEintraege"){
				reisenet.service.ich.meineEintraege(14);
			}else if(goto == "videoPlatzieren"){
				reisenet.service.video.idEingeben(16);
			}else if(goto == "storyAnlegen"){
				reisenet.service.story.anlegen(18);
			}
		}else if(maptales.getURLParameter("cropProfileImage")){
			reisenet.service.makeProfileImage(21);
		}else if(maptales.getURLParameter("mediaId")){
			var mediaId = maptales.getURLParameter("mediaId");
			loadPage("media/page", null, mediaId);
		}else if(maptales.getURLParameter("storyId")){
			maptales.rpc.getById(maptales.getURLParameter("storyId"), function(reply){
				if(reply instanceof SnapMapException){
					loadPage("error", {titel:"Story existiert nicht", message: "Entweder die Story existiert nich oder sie ist gelöscht worden"});
				}else{
					if(reply instanceof Story){
						loadPage("story/index", {storyId: reply.id});
					}else{
						loadPage("error", {titel:"Story existiert nicht", message: "Entweder die Story existiert nich oder sie ist gelöscht worden"});
					}
				}
			});
			
		}else{
			if(document.URL.indexOf("meine-weltkarte")==-1){
				reisenet.weltkarte.neues(6);
			}
			
			if(this.loadMapQueryOnStart){
				this.setMapToQueryMode(new Query({type: "medias", locally: true, clustered: true, groupId: this.groupId }), null);
			}
		}
		var control = new ReisenetControl();
		this.getMainMap().gmap.addControl(control);
		
		var slider = new Slider($('mapSlider'), this, null, null, null, {}, true);
		
		this.getComponent("contentPanel").onDisplay = function(){
			callSifr();
		}.bind(this);
	},
	
	onLoading: function(bool){
		var element = this.getElement("contentLoading");
		if(element!=null){
			if(bool){
				element.style.display = "block";
			}else{
				element.style.display = "none";
			}
		}
	},
	
	
	onLogin: function(user){
		
	},
	
	setMapMode: function(callingObject, parameters){
		if(callingObject instanceof SlotWidget){
			this.setMapToSlotMode(callingObject.getParameters());
		}else{
			alert("non slotwidget call");
		}
	},
	
	onServerOffline: function(code){
		//this.getElement("serverOfflineNotification").style.display = "block";
	},
	

	onSessionExpirationCallback: function(){
		if(maptales.service.user.getCurrentUser()!=null){
			if(this.getElement("sessionExpirationNotification")!=null)
				this.getElement("sessionExpirationNotification").style.display = "block";
		}
	},
	
	getCurrentUser: function(){
		return maptales.service.user.getCurrentUser();
	},
	
	getCurrentUserName: function(){
		if( maptales.service.user.getCurrentUser()!=null)
			return maptales.service.user.getCurrentUser().get("name");
	},
	
	currentUserHasRole: function(role){
		if(maptales.service.user.getCurrentUser()!=null){
			return maptales.service.user.getCurrentUser().hasRole(role);
		}else{
			return false;
		}
	},
	
	getCurrentUserId: function(){
		return maptales.service.user.getCurrentUserId();
	},
	
	
	//the widget is only displayed once, when the page is loaded. load mapobjects here
	onDisplay: function(){
		
	},
	
	
	getAppName: function(){
		return this.appName;
	},
	
	getPath: function(){
    	return [{name:this.getAppName(), path: this.getAppName()}];
    },
    
	getViews: function(){
    	return this.rootViews;
    },
    
    getDefaultView: function(){
    	return this.rootViews[this.defaultView];
    },
    
    hasView: function(name){
    	if (this.rootViews[name]) {
    		return true;
    	}
    	else {
    		return false;
    	}
    },
    
    getView: function(name){
    	if(name)
    		return this.rootViews[name];
    	else
    		return this.rootViews[this.defaultView];
    },
    
	getTemplateOfView: function(view){
		 
         try{
            var templatePath = "";
            if(view == "default" || view == null){
            	if(this.rootViews[this.defaultView].template){
                	templatePath +=  this.rootViews[this.defaultView].template;  
            	}else{
            		return null;
            	} 
            }
            else {
            	if(this.rootViews[view].template){
                	templatePath +=  this.rootViews[view].template; 
            	}else{
            		return null;
            	} 
            }
            return templatePath;
        }
        catch(e) {
            return false;
        }
    },
    
    
    
	//since the widget does the component handling delegate to widget
    getMainMap: function(){
    	return this.getComponent("map");
    },
    
    getContentPanel: function(){
    	return this.getComponent("contentPanel");
    },    
    
    /*
     *
     */
    grantAllRights: function(contentobject){
    	if(contentobject instanceof Tag){
    	}else{
	    	var rights = DEFAULT_RIGHTS;
	    	$H(rights).each( function(valuePair){
	    		var key = valuePair.key;
	    		contentobject.renderedRights[key] = true;
	    	}.bind(this));
    	}
    },
    
    getAndIncrementTempId: function(){
    	return maptales.tempIdIndex--;
    },

	/*
	 * Status Bar Handling. Maybe we should push this into an AbstractType, since we might need it often
	 */
	addStatusMessage: function(type, message) {
    	var sb = this.getComponent("statusBar");
    	if (sb) sb.addMessage(type, message);
    },
        
    /*
     *	Warnings and Messages are recorded here and then passed to the ui.
     *  If the user interface does not handle them they wont be dsplayed
     */
    addWarning: function(title, message){
     	//this.warnings.push({title: title, message: message});
     	try{
    		this.addStatusMessage("UserWarning",{title: title, text: message});
    	}catch(e){} //user interface does not have to implement display
    },
    
    addException: function(exception){
    	//this.exceptions.push(exception);
    	try{
    		this.addStatusMessage("Exception", exception);
    	}catch(e){} //user interface does not have to implement display
    },
    
    addFailure: function(title, message){
    	//this.failures.push({title: title, message: message});
    	try{
    		this.addStatusMessage("Failure", {title: title, text: message});
    	}catch(e){} //user interface does not have to implement display
    },
        
    addInfo: function(title, message){
    	//this.infos.push({title: title, message: message});
    	try{
    		this.addStatusMessage("Info", {title: title, text: message});
    	}catch(e){} //user interface does not have to implement display
    },
    
	checkTip: function(tip, focusEl, orientation) {
		if (this.currentUser && this.currentUser.getProperty("showTips")) {
			var shownTips = this.currentUser.getPropertyAsArray("shownTips");
			if (shownTips.indexOf(tip) == -1) {
				if (!Dialog.lastDialog) {
					if (!orientation) orientation = Dialog.NORTH;
					Dialog.toggle("", this, "tip", "tips/" + tip, {}, $(focusEl), orientation);
		    		
		    		var arr = this.currentUser.getPropertyAsArray("shownTips");
		    		// property has not been set so far
		    		if (!arr) arr = [];
		    		arr.push(tip);
		    		this.currentUser.setPropertyAsArray("shownTips",arr);
		    		this.currentUser.persist();	
				}
			}
		}			
	},
	
	showTip: function(tip, focusEl, orientation) {
		if (!orientation) orientation = Dialog.NORTH;
		Dialog.toggle("", this, "tip", "tips/" + tip, {mandatory: true}, $(focusEl), orientation);
	},
	
	
	
		 
    /////////////////////////////////////////////////////
    //ACTION HANDLER
    /////////////////////////////////////////////////////
    checkRights: function(action){
    	if(this.getCurrentUserId() != false)
    		return false;
    	else
    		return true;
    },
    
    clusterClicked: function() {
    	
    },
    
    gotoPath: function(contextObject, templatePath, parameters){
    	var path = new Path({contextObject: contextObject, templatePath: templatePath, parameters: parameters});
    	this.getComponent("contentPanel").gotoPath(path);
    },
    
     /*
	 * MAP ACTIONS
	 */
	
	defaultMapSyncParameters: {template: "pages/media/page", parameters: null},
	mapSyncParameters:  this.defaultMapSyncParameters,
	setMapItemClickVariables: function(template, parameters){
		this.mapSyncParameters = {template: template, parameters: parameters};
	}, 
	
	setDefaultMapSyncParameters:  function(){
		this.mapSyncParameters = this.defaultMapSyncParameters;
	},
	
	onMapItemClick: function(parameters){
		var path = {};
		path.parameters = this.mapSyncParameters.parameters || {};
		path.templatePath = this.mapSyncParameters.template;
		Object.extend(path.parameters, parameters);
		path.contextObject = parameters.contextObject;
		this.gotoPath(path.contextObject, path.templatePath, path.parameters);
	},
	
	displayMediaOnMap: function(id){
		try{
			this.getMainMap().gotoMedia(id);
		}catch(e){
			this.logger.warn("Error in displayMediaOnMap ", e);
		}
	},
	
	setMapToSlotMode: function(param, onMapItemClickParam){
		try{
			if(!param)return;
			this.getMainMap().setToSlotMode(param);
			if(onMapItemClickParam==null)onMapItemClickParam=this.defaultMapSyncParameters;
			this.setMapItemClickVariables(onMapItemClickParam.template, onMapItemClickParam.parameters);
		}catch(e){
			this.logger.warn("Error in setMapToSlotMode ", e);
		}
	},
	
	setMapToQueryMode: function(query, onMapItemClickParam){
		try{
			this.getMainMap().setToQueryMode(query);
			if(onMapItemClickParam==null)onMapItemClickParam=this.defaultMapSyncParameters;
			this.setMapItemClickVariables(onMapItemClickParam.template, onMapItemClickParam.parameters);
		}catch(e){
			this.logger.warn("Error in setMapToQueryMode ", e);
		}
	},
	
	setMapToItemMode: function(id){
		try{
			this.getMainMap().gotoMedia(id);
		}catch(e){
			this.logger.warn("Error in setMapToItemMode ", e);
		}
	},
	

    
	/*
	 * Handle Root actions
	 */
	handleBubbleAction: function(action){
		this.logger.debug("MaptalesWidget>handleBubbleAction: "+action.getType());
        action.cancelBubble = true; 
        if(action.type == "loadPage"){
        	this.loadPage(action.parameters);
        }
    }
});



//this decides if text can be selected or not
function decideSelect(event){
	var nodeName = Event.element(event).nodeName.toLowerCase();
	if(nodeName=="textarea"||nodeName=="input"){
		return true;
	}else{
		return false;
	}
}



// Dynamic Mediator
var dynamicMediatorConfigs = {};
dynamicMediatorConfigs.profileImageSelectConfig = {
	template: "cropProfileImageMediator",
    actions: {
	    cropChange:
		        [
			        {
			            methodToInvoce: "styleElement",
			            element: "buddyIcon"
			        }
		        ],
		finishedAreaSelect:
				[ 
					{
			            bubbleAction: "loadPage",
			            parameters: {template: "pages/ich/profilCropConfirm", parameters: null}
			        }
				]
    }
};