function Dooyago() {
	this.xmlrpc = null;
	this.rateDaysLimit = 4;
	this.sourceMore = null;
	this.user = false;	
	this.f = [];
//	this.serverPath = "/wergehthin/";
	this.serverPath = "/";
	this.onloadF = [];
	this.showPicture = null;
	this.valM = [
//				 'bitte noch | ausf\u00FCllen',
				 'Bitte ausf\u00FCllen: ',	
				 'bitte \u00FCberpr\u00FCfen: ',
				 'bitte \u00FCberpr\u00FCfe nochmal das Feld ',
				 'bitte \u00FCberpr\u00FCfe nochmal das Feld ',
				 'bitte \u00FCberpr\u00FCfe nochmal das Feld ',
				 ' muss eine 5-stellige Postleitzahl sein',
				 ' muss eine Zahl sein. Bitte kein Text (z.B.).',
				 'Leider k\u00F6nnen derzeit noch keine HTML-tags wie bspw. <b>, <u>, ... akzeptiert werden. Bitte daher nur normalen Text verwenden'				 
				];
	this.functionM = [
						 'Bitte gib Deine Email ein...', //login
						 'Bitte gib Dein Password ein...', //login
//						 'Login hat leider nicht geklappt', //login
						 'Entweder Email oder Passwort stimmen nicht. Probier\'s bitte nochmal', //login	
						 'Diesen Event hattest Du Dir bereits gemerkt ;-)',
						 'Diesen Spot hattest Du Dir bereits gemerkt ;-)',
						 'Wir haben Dir soeben eine Mail zugeschickt. F\u00FCr ein neues Passwort, klicke bitte auf den darin enthaltenen Link', // forgot password
						 'Sch\u00F6n, dass Du dabei bist! Du hast soeben eine Email von uns bekommen. Bis gleich...', //register user 
						 'Deine Nachricht wurde verschickt!', //send message
						 'Deine Freundschaftsanfrage wurde verschickt!', // friend request
						 'Please check the checkbox to upload photos and videos', // Check to upload
						 'Sorry, you dont have permission to send a message to ', //No permission to send private message
						 'Dein Hinweis wurde verschickt!', // Send Invite
  						 'Deine Einstellungen wurden erfolgreich gespeichert!', //Settings saved
  						 'Um dem $1 einen weiteren Punkt zu geben, warte bitte noch $2 $3', // Already rated up
//  						 'Mehrmalige Bewertungen sind leider nicht m\u00F6lglich', //Rated already
 						 'Fertig! Du nimmst nun an unserer Freikarten-Aktion teil.\nEtwa 3 Stunden vor dem Event erhalten alle Gewinner eine Mail von uns. ', // Free Ticket
  						 'Wir haben Dich f\u00FCrs n\u00E4chste Mal vorgemerkt. F\u00FCr heute wurden bereits alle Freikarten verteilt.', // Free Ticket  						 
 						 'Fertig! Du nimmst nun an unserer Freikarten-Aktion teil.\n\nEtwa 3 Stunden vor dem Event erhalten alle Gewinner eine Mail von uns. ', // Free Ticket
 						 'Leider wurden bereits alle Freikarten verteilt. Wir informieren Dich sobald es Neue gibt.', // Free Ticket
  						 'M\u00F6chtest Du die Freundschaft mit ',
  						 ' wirklich beenden?',
  						 'Diese Nachricht endg\u00FCltig l\u00F6schen?', //Confirm delete message
  						 'Diese Freundschaftsanfrage wirklich zur\u00FCckziehen?', // withdraw friend request
  						 'Um dem $1 einen weiteren Punkt abzuziehen, warte bitte noch $2 $3', //Already rated down
  						 'Vielen Dank f\u00FCr Deine Stimme!\r\nDie Verlosung startet sobald sich gen\u00FCgend Leute eingetragen haben.\r\nUnser Tipp: Lass Freunde & Bekannten mit abstimmen & gewinnt bevorzugt Freikarten!' , //Additional freeTicket alert
   						 'Wir haben Dir soeben einen neuen Bestätigungslink geschickt.\r\nBitte pr\u00FCfe Dein E-Mail Postfach und klicke auf den Aktivierungslink in dieser E-Mail (Evtl. checke auch Deinen Spam Ordner).\r\nBei Problemen melde Dich einfach unter support@wergehthin.de',
						 'Bitte aktiviere zun\u00E4chst Deinen Account.\r\nKlicke dazu einfach auf den Link in unserer Best\u00E4tigungsmail an Dich.\r\n\r\nSollen wir Dir den Link noch einmal zuschicken?',
						 'Du nimmst bereits an dieser Verlosung teil.\r\nOb Du gewonnen hast erf\u00E4hrst Du sp\u00E4testens 3 Stunden vor dem Event per Mail.\r\nViel Gl\u00FCck!' 						 
					];								
	this.sendInviteM = [
				 'Zeig Deinen Freunden diesen Event!',
				 'Zeig Deinen Freunden diesen Spot!',
				 'Wem k\u00F6nnte es hier gefallen? Wer sollte diesen Event nicht verpassen?',
				 'Wem k\u00F6nnte es hier gefallen? Wer sollte diesen Spot anschauen?',
				 'Dein.Freund@web.de,Dein.Bekannter@gmx.de',				 
				 'Hi,\nich habe gerade diesen Event gefunden. Schau ihn Dir mal an!\n\nViele Gr\u00FC\u00dfe',				 
				 'Hi,\nich habe gerade diesen Spot gefunden. Schau ihn Dir mal an!\n\nViele Gr\u00FC\u00dfe'				 				 				 
				];
				
	this.overTextM = [
		'Klick\' auf <span class="t9b pinkT" >Mag ich!</span> um Dir \ndiesen Event zu merken \n &amp; \u00E4hnliche Events zu entdecken', //Mag_ich_event
		'Klick\' auf <span class="t9b purpleT">Mag ich!</span> um Dir \ndiesen Spot zu merken \n &amp; \u00E4hnliche Spots zu entdecken', //Mag_ich_spot
		'Lade Deine eigenen \n Fotos von diesem Event \n hoch', //Fotos_event
		'Lade Deine eigenen \n Fotos von diesem Spot \n hoch', //Fotos_spot
		'Dein Event findet hier \nstatt? Trage ihn jetzt ein.', //Event eintrangen
		'Du r\u00E4tst von diesen Event \nab? Dann zieh\' ihm einen \nPunkt ab!', //Arrow event down
		'Du kannst diesen Event \nempfehlen? Dann gib\' \n ihm einen Punkt!', //Arrow event up
		'Du r\u00E4tst von diesen Spot \nab? Dann zieh\' ihm einen \nPunkt ab!', //Arrow spot down
		'Du kannst diesen Spot \nempfehlen? Dann gib\' \n ihm einen Punkt!', //Arrow event up
		'Klick auf <span class="t9b greenT" >gemerkt</span>, wenn Du diesen Event nicht mehr magst', // Germerkt event
		'Klick auf <span class="t9b greenT" >gemerkt</span>, wenn Du diesen Spot nicht mehr magst', // Germerkt spot
		'Klick auf <span class="t9b pinkT" >mag ich!</span> wenn Dir dieses Foto gef\u00E4llt' // Rate up popular photo
	];
				
	this.similarTextM = [
		'Bitte w\u00E4hle mindestens einen __entity__ aus, f\u00FCr den Du freigeschaltet werden m\u00F6chtest. Kicke dazu einfach auf den entsprechenden __entity__ in der Liste.', // No events/spots selected
		'Vielen Dank f\u00FCr Deinen Hinweis!\nDas wergehthin-Team pr\u00FCft nun Deine Anfrage und wird Dich informieren, sobald Dein __entity__ freigeschaltet wurde.' //Email has been sent				 
	];	
};


var dooyago = new Dooyago();

function keepAlive() {
	dooyago.xmlrpc.executeAsync('Dooyago.keepAlive', function(ret, e) {
		return});
	setTimeout(keepAlive, 5*60*1000);
}


function init() {
	//Nifty("ul.postnav a","transparent");
	while (dooyago.onloadF && dooyago.onloadF.length>0) {
		var f = dooyago.onloadF.pop();
		f();         
	}
	
	keepAlive();

/*		dooyago.f.push(
			function() { window.location.href='userdashboard.jsp'; }	
		);
*/
/*
		var username = getCookie("username");
		var password = getCookie("password");
		var rememberInfo = getCookie("rememberInfo");
		
		if( username != null && username != "" && password != null && password.length >= 8 && rememberInfo != null && rememberInfo != '') {
			$('rememberInfo').checked = true;
			$('headUser').value = getCookie("username");
			$('headPass').value = decrypt(getCookie("password"),"password");
			headLogin();
		}
*/
	hideAds();
}


function ifLoggedShort(fname, param) {
	var sep = (typeof param == 'string') ? "'" : "";
	var f = function() { eval(fname + '(' + sep + param + sep + ')') };
	return ifLogged(f);
}


function ifLogged(f,notreload) {
	if (dooyago.user) {
		return f();
	} else {
		//Default: reload page after execution of "f"
		if (!notreload) {
			dooyago.f.push(
				function() { window.location.reload(); }	
			);
		}
		if(f) {
			dooyago.f.push(f);
		}
		showForm('/forms.Main/LoginRequest_form.htmli?lang=de', 'LoginRequest','0', '');				
	}
	return false;
}

function highlightChild(id,index) {
	if($(id)) {
		$(id).childElements()[index].firstChild.className="";
	}
}

function showPicture(ev,url) {
	if (dooyago.showPicture) {
		clearTimeout(dooyago.showPicture);
	}
	var target = ev.getTarget();
	dooyago.showPicture = setTimeout(function() {
		showPictureMore(target,url);
	},300);
}

function clearPictureTimeout() {
	clearTimeout(dooyago.showPicture);
}

function showPictureMore(target,url) {
	if (!dooyago.sourcePicture) {
		dooyago.sourcePicture = application.wrapNode(document.getElementById('sourcePicture'));
	}
	dooyago.sourcePicture.close();
	var div = $('pictureDiv');
	
	var top = target.getY() -50;
	var left = target.getX() -50;
	div.setStyle('top:'+top+'px;left:'+left+'px;');
//	$('pictureRoller').show();
//	div.appear({ duration: 0.4});
	div.show();
	dooyago.sourcePicture.setUrl(url);
	dooyago.sourcePicture.open(function() {
	//	$('pictureRoller').hide();
	});
	
}

function hidePicture() {
	$('pictureDiv').hide();
	dooyago.sourceMore.close();
}
function showMore(ev,url,centered) {
	dooyago.sourceMore.close();
	var div = $('moreDiv');
	
	var htmlElement = application.getDocumentElement();
	var coords = getMoreCoordinates(ev);
	//window.status = 'ev.getClientY():'+ev.getClientY()+',pageHeight():'+pageHeight()+',overflow:'+overflow;
	//div.setStyle('top:'+ev.getClientY()+'px;left:'+(ev.getClientX()+100)+'px;');	
	div.setStyle('top:'+coords[0]+'px;left:'+coords[1]+'px;');
	//$('moreRoller').show();
	div.appear({ duration: 0.4});
	//div.show();
	if (!dooyago.sourceMore) {
		dooyago.sourceMore = application.wrapNode(document.getElementById('sourceMore'));
	}
	dooyago.sourceMore.setUrl(url);
	dooyago.sourceMore.open(function() {
		var container = dooyago.sourceMore.getChildContainer();
		var id = container.getElementById('id');
		if (id) id = id.getValue();

		if(id && id.indexOf(url) < 0) {
			showMore(ev,url,centered);
		}
		//$('moreRoller').hide();
	});
}

function getMoreCoordinates(ev) {
	var htmlElement = application.getDocumentElement();
	var top = ev.getClientY()+application.getScrollTop();
	var left = ev.getClientX()+application.getScrollLeft()+60;
	var overflowY = (ev.getClientY() + 200 + 25) - pageHeight();
	var width = pageWidth();
	var overflowX = (ev.getClientX() + 330 + 55) - width;	

	if (overflowY > 0) {
		top = top - (overflowY+40);
	}
	if (overflowX > 0) {
		left = left - (overflowX+350+45);
	}
	return [top,left];
}

function moveMore(ev) {
	var div = $('moreDiv');
	var coords = getMoreCoordinates(ev);
	div.setStyle('top:'+coords[0]+'px;left:'+coords[1]+'px;');
//	div.setStyle('top:'+(ev.getClientY()+application.getScrollTop())+'px;left:'+(ev.getClientX()+application.getScrollLeft()+61)+'px;');
}

function moveTextMore(ev) {
	var div = $('textMoreDiv');
	var coords = getTextMoreCoordinates(ev);
	div.setStyle('top:'+coords[0]+'px;left:'+coords[1]+'px;');
//	div.setStyle('top:'+(ev.getClientY()+application.getScrollTop())+'px;left:'+(ev.getClientX()+application.getScrollLeft()+61)+'px;');
}


function hideMore() {
	$('moreDiv').hide();
	dooyago.sourceMore.close();
}

function hideTextMore() {
	$('textMoreDiv').hide();
}

function removeCss() {
	var css = document.getElementsByTagName('link');
	for (var i=0; i < css.length; i++) {
		if(css[i].href.indexOf('jrapid-runtime/jrapid-runtime.css') > 0) {
			//css[i].setAttribute('href','');
			css[i].parentNode.removeChild(css[i]);
		}
	}
}

function showForm(url, entity, id, defaultset, handler, useOther) {
//	var div = $('sourceDiv');
//	div.show();
	var source = application.wrapNode($(useOther? useOther : 'source'));
	source.setUrl(url);

	source.open(function() {
		removeCss();
		var childContainer = source.getChildContainer();
		jrapid.loadForm(childContainer, entity, id, defaultset, true, function() {
			childContainer.getElementById('window').setNoMaxButton(true);
			childContainer.getElementById('window').setHelpButton(false);			
			registerAction(entity, id, defaultset);
			if (handler) {
				handler(childContainer);
			}
			//$('roller').hide();
//			div.style.width = source.getChildContainer().getElementById('windowcontainer').getWidth() + 'px';
//			application.wrapNode(div).center();
			});
	});
}

JRapid.prototype.openListing = function(me, entity, canvas, listing, subset, replace, handler, skipWindow, url) {
    var container = me.getContainer();
    if (replace) {
        container.getElementById(canvas).setInnerHTML('');
    }

    // clone source
    var sourcePrototype = application.wrapNode(document.getElementById('source')).cloneNode(true);
    sourcePrototype.setId('listing' + Math.random());
    sourcePrototype.setInnerHTML('');
    
    // append source to canvas
    if (container.getElementById(canvas)) {
        container.getElementById(canvas).appendChild(sourcePrototype);
    } else {
        application.getElementById(canvas).appendChild(sourcePrototype);
    }
    
    // console
    var txOpenListing = jrapid.startConsole('Opening listing', false, 'green');
    
    // load source
    sourcePrototype.setUrl(url ? url : (entity + (listing && listing.length > 0 ? '_' : '') + listing + (skipWindow ? '_baselist.htmli' : '_list.htmli')));
    sourcePrototype.open(function() {
   		
    	if (!sourcePrototype.isOpened()) {
		   	jrapid.endConsole(txOpenListing);
	   		jrapid.startConsole('Network error', true, 'red');
	   		return;
    	}
    	
        var childContainer = sourcePrototype.getChildContainer();
        var xsl = jrapid.listingGetXsl(childContainer);
        xsl.getStyle().display = '';
        var baseurl = JRapid.SERVER_PATH + entity + (subset && subset.length > 0 ? ('/' + subset) : '');
        xsl.setUrl(baseurl + ',page1');
        xsl.setAttribute('baseurl', baseurl);
        xsl.setAttribute('entity', entity);
        if (!skipWindow) {
            var childContainer = sourcePrototype.getChildContainer();
            if (childContainer.node) {
                childContainer.node.canvas = childContainer.getElementById('window');
            } else {
                application.canvas = childContainer.getElementById('window');
            }
        }
       
       xsl.refresh(function(foo, xmlDoc, status) {
    	
    		// end console
        	jrapid.endConsole(txOpenListing);
        	
        	// check network error
        	if (status != 200) {
        		jrapid.startConsole('Network error', true, 'green');  
        		return;
        	}
        	
        	// check service error
        	if (xmlDoc == null || xmlDoc.documentElement == null || xmlDoc.documentElement.tagName == 'exception') {
        		jrapid.startConsole('Network error', true, 'red'); 
				if (xmlDoc != null && xmlDoc.documentElement && xmlDoc.documentElement.hasChildNodes()) {
					alert(xmlDoc.documentElement.childNodes[0].nodeValue);
				} else {
					alert('Unable to read');
				}
        		return; 
        	}
        	
        	// call handler
        	if (handler) {
                handler(xsl.getContainer());                
            }
            
            // open window
            if (!skipWindow) {
                var win = childContainer.getElementById('window');
                win.open();                
            }
        });
    });
        
    
};



function registerAction(entity , id, defaultset) {

	if(pageTracker) {
		var path = dooyago.serverPath + "front/" + entity;
		if(defaultset) {
			path = path + "/" + defaultset;
		}
		
		pageTracker._trackPageview(path);
	}

	var userId = dooyago.user;
	if(!dooyago.user) {
		userId = '0';
	}
	
	dooyago.xmlrpc.executeAsync('Tracking.storeFrontAction', function(ret, e) {
         if (e) {

         } else {
         }
     }, '' + userId + '', entity, id, defaultset);
   return false;  
}				
	
com_htmli_ui_Window.alwaysCentered = true;
com_htmli_ui_Window.alwaysExclusive = true;
//com_htmli_ui_Window.alwaysExclusive = true;

function hideForm() {
	application.wrapNode($('source')).close();
	$('sourceDiv').hide();	
//	$('roller').show();	
}

function headLogin() {
	dooyago.f.push(
		function() { window.location.href='/front/userdashboard.jsp'; }	
	);

	if($('rememberInfo').checked && $F('headUser') && $F('headUser') != '' && $F('headPass') && $F('headPass') != '') {
		var date = new Date();
		date.setTime(new Date().getTime()+(365*24*60*60*1000));
	    var expires = 'expires=' + date.toGMTString() + ';';
	    var cook = "password=" + encrypt($F('headPass'),"password") + ";" + expires;
		document.cookie = cook; 
		cook = "username=" + $F('headUser') + ";" + expires;
		document.cookie = cook;
		cook = "rememberInfo=" + "remember" + ";" + expires;
		document.cookie = cook;
	}
	
	
	return login($F('headUser'),$F('headPass'));
}


function saveInfo(me) {
	var cookie = document.cookie;
	if($('rememberInfo').checked) {
		if(getCookie("username") != '' && getCookie("password") != null && getCookie("password").length >= 8) {
			var username = getCookie("username");
			var password = decrypt(getCookie("password"), "password");			
		}
	} else {		
		/*var newCookie = cookie.replace(new RegExp(/password=[^;]+;/g), "");
		newCookie = newCookie.replace(new RegExp(/username=[^;]+;/g), "");*/
		var date = new Date();
		date.setTime(new Date().getTime()+(365*24*60*60*1000));
	    var expires = 'expires=' + date.toGMTString() + ';';
		var newCookie = "username=;" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
		document.cookie = newCookie;
		newCookie = "password=;" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
		document.cookie = newCookie;
		newCookie = "rememberInfo=;" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
		document.cookie = newCookie;
	}
}


function login(user,pass) {
	if (user.blank()) {
		alert(dooyago.functionM[0]);
		return false;
	}
	if (pass.blank()) {
		alert(dooyago.functionM[1]);
		return false;
	}	

	dooyago.xmlrpc.executeAsync('User.login', function(ret, e) {
         if (e) {
			if( e == "Error: NoActivated" )
				resendMail(user);				
			else
             	alert(dooyago.functionM[2]);
         } else {
			dooyago.user = ret;
   			while (dooyago.f && dooyago.f.length>0) {
   				var f = dooyago.f.pop();
   				//alert(f);
    			f();         
			}
			registerSuccessful("Login");
         }
     }, user, pass, false);
   return false;  
}

function resendMail(user)
{
	if( confirm('Bitte aktiviere zun\u00E4chst Deinen Account.\r\nKlicke dazu einfach auf den Link in unserer Best\u00E4tigungsmail an Dich.\r\n\r\nSollen wir Dir den Link noch einmal zuschicken?') ) {
		dooyago.xmlrpc.executeAsync('EmailServices.resendRegistrationEmail', function(ret, e) {		
		}, user );
		alert('Wir haben Dir soeben einen neuen Best\u00E4tigungslink geschickt.\r\nBitte pr\u00FCfe Dein E-Mail Postfach und klicke auf den Aktivierungslink in dieser E-Mail (Evtl. checke auch Deinen Spam Ordner).\r\nBei Problemen melde Dich einfach unter support@wergehthin.de.');	
	}
}

function htmliLogin(me) {
	var container = me.getContainer(); 
	login(container.getElementById('loginRequest_email').getValue(),
		container.getElementById('loginRequest_password').getValue() ); 
	return false;
}

function logout() {
    dooyago.xmlrpc.executeAsync('User.logout', function(ret, e) {
		if (e) {} else {
/*			var date = new Date();
			date.setTime(new Date().getTime()+(365*24*60*60*1000));
		    var expires = 'expires=' + date.toGMTString() + ';';
			var newCookie = "username=;" + expires;
			document.cookie = newCookie;
			newCookie = "password=;" + expires;
			document.cookie = newCookie;
*/		
			var newCookie = "username=;" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
			document.cookie = newCookie;
			newCookie = "password=;" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
			document.cookie = newCookie;
			newCookie = "rememberInfo=remeber;" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
			document.cookie = newCookie;
		
			window.location.href='/front/home.jsp';		
		}
    });
	dooyago.user = false;
}

function addEvent(id, f) {
	dooyago.xmlrpc.executeAsync('User.addEvent', function(ret, e) {
		if (!e instanceof TypeError) {
		    alert(dooyago.functionM[3]);
		} else {
			if (f)  {
				f();
			} 
			if(!dooyago.user > 0) {
				setTimeout(function() {
					window.location.reload();
				},100);
			}

		}
    },id);
}

function addLocation(id, f) {
	dooyago.xmlrpc.executeAsync('User.addLocation', function(ret, e) {
		if (!e instanceof TypeError) {
		    alert(dooyago.functionM[4]);
		} else {
			if (f)  {
				f();
			} 
			if(!dooyago.user > 0) {
				setTimeout(function() {
					window.location.reload();
				},100);
			}
		}
    },id);
}

function deleteUserLocation(id, f) {
	dooyago.xmlrpc.executeAsync('UserLocation.deleteUserLocation', function(ret, e) {
		if(e) {} else {
			if(f) {
				f();
			}
		}
	}, id);
}

function deleteUserEvent(id, f) {
	dooyago.xmlrpc.executeAsync('UserEvent.deleteUserEvent', function(ret, e) {
		if(e) {} else {
			if(f) {
				f();
			}
		}
	}, id);
}

function changeQuestion(id,forEvent) {
	var oldQ = $F('questionId');
	
		dooyago.xmlrpc.executeAsync('Question.getNew', function(ret, e) {
		if  (e) {} else {
			var index = ret.indexOf(';');
			var newQ = ret.substring(0, index);
			var question = ret.substring(index + 1,ret.length);
			$('displayQuestionText').update(question);
			Effect.SlideDown('displayQuestion', { queue: 'end' });
			$('questionId').setValue(newQ);				

		}
	},oldQ,forEvent,id);		
}

function deleteComment(me,commentId) {
	$('commentTr'+commentId).fade();
	$('commentTr'+commentId).slideUp();
	
	dooyago.xmlrpc.executeAsync('Comment.deleteComment', function(ret,e) {
		if(e) {} else {

		}
	}, commentId);	
}

function saveQuestionComment(id, target) {
	return saveComment(id,'questionAnswer',$F('questionId'),target);
}

function addComment(id,target) {
	return saveComment(id,'commentField','',target);
}

function saveComment(id, fieldName,questionId,target) {
	var comment = $F(fieldName);
	if (secureString(comment)) {
		if(comment == "") {
	//		alert("You have to answer something");
		} else {
			dooyago.xmlrpc.executeAsync('Comment.storeComment', function(ret,e) {
				if(e) {} else {
					$(fieldName).setValue("");
					hideComments();
					showComments('comments.jsp?' + target + 'Id=' + id);	
				}
			},id,questionId,comment,target);
		}
	}
}


function showComments(url) {
	showSource(url,'sourceComments','commentsRoller');
}


function showMessages(url) {
	if(url.indexOf('message.jsp') == 0 && url.indexOf('sent') < 0) {
		var id = url.split('message=')[1];
		if(id > 0) {
			dooyago.xmlrpc.executeAsync('Message.setMessageAsRead', function(ret,e) {
				if(e) {} else {
					updateUnread(ret);
					showSource(url,'sourceMessages','messagesRoller');
				}
			},id);			
		}
	} else {
		showSource(url,'sourceMessages','messagesRoller');
	}
}

function setMessageAsRead(id) {
	dooyago.xmlrpc.executeAsync('Message.setMessageAsRead', function(ret,e) {
				if(e) {} else {
					updateUnread(ret);
				}
			},id);			
}

function hideMessages(url) {
	hideSource('sourceMessages','messagesRoller');
}

function hideComments() {
	hideSource('sourceComments','commentsRoller');
}

function showSource(url,sourceDiv,rollerDiv) {
	var source = application.wrapNode($(sourceDiv));
	if (!source.isOpened()) { 
		source.setUrl("/front/" + url);
		source.open(function() {
			$(rollerDiv).hide();
		});
	}
}

function hideSource(sourceDiv, rollerDiv) {
	var source = application.wrapNode($(sourceDiv));
	if (source.isOpened()) {
		source.close();
	}
	$(rollerDiv).show();
}

function showInterested(url) {
	showSource(url,'sourceInterested','interestedRoller');
}

function hideInterested() {
	hideSource('sourceInterested','interestedRoller');
}

function showAttending(url) {
	showSource(url,'sourceAttending','attendingRoller');
}

function hideAttending() {
	hideSource('sourceAttending','attendingRoller');
}



function rateEvent(rating, eventId, me, rbId) {
	dooyago.xmlrpc.executeAsync('EventRatedBy.getDayDiff', function(ret, e) {
		if(e) { } else {
			var ans = ret.split("|");
			var ddiff = ans[0];
			var rated = "up";
			if(ans.length > 1) {
				rated = ans[1] == "true"? "up" : "down";
			}
			if(ddiff <= dooyago.rateDaysLimit && rated == rating) {
				var index = rating == 'up'? 13 : 22;
				var mtext = dooyago.functionM[index].replace('$1','Event').replace('$2', dooyago.rateDaysLimit - ddiff).replace('$3', (dooyago.rateDaysLimit - ddiff) == 1? 'Tag' : 'Tage');
				alert(mtext);
				if(!dooyago.user > 0) {
					setTimeout(function() {
						window.location.reload();
					},1);
				}
			} else {
				dooyago.xmlrpc.executeAsync('Event.rate', function(ret,e) {
					if(e) {} else {
						var events = $$('.eventScore' + eventId);
						var thumbsUp = document.getElementsByName('thumbUpImg' + eventId);
						var thumbsDown = document.getElementsByName('thumbDownImg' + eventId);
						for(var i = 0; i < events.length; i++) {
							events[i].pulsate();
							if(rating == 'up') {
								thumbsUp[i].src = "/front/design/Arrow _up_dark.png";
								thumbsDown[i].src = "/front/design/arrow_down_light.png";				
							} else {
								thumbsUp[i].src = "/front/design/arrow_up_light.png";
								thumbsDown[i].src = "/front/design/arrow_down_dark.png";				
							}
							events[i].update(ret);
							if(!dooyago.user > 0) {
								setTimeout(function() {
									window.location.reload();
								},1);
							}
						}		
					}	
				}, eventId,rating);
			}
		}
	}, rbId, eventId);
}

function addEventHandler(id, add) {
		var myEvents = $$('.myEvent' + id);
		var notMyEvents = $$('.notMyEvent' + id);
		
		for(var i = 0; i < myEvents.length; i++) {
			if(!add) {
				myEvents[i].hide();
				notMyEvents[i].show();
			} else {
				myEvents[i].show();
				notMyEvents[i].hide();
			}
		}

}


function ratePhoto(rating, photoId,me) {
	if(me && me.src.indexOf("dark") > 0) {
		alert(dooyago.functionM[13]);
	} else {
		if(me) {
			$('photoScore').pulsate();
		}
		dooyago.xmlrpc.executeAsync('Photo.rate', function(ret,e) {
			if(e) {} else if(me) {
				if(rating == 'up') {
					$('thumbUpImg').src = "/front/design/Arrow _up_dark.png";
					$('thumbDownImg').src = "/front/design/arrow_down_light.png";
				} else {
					$('thumbUpImg').src = "/front/design/arrow_up_light.png";
					$('thumbDownImg').src = "/front/design/arrow_down_dark.png";
				}
				$('photoScore').update(ret);
			} else {
				// Texto al rankear positiva la foto

			}
		}, photoId,rating);
	}
}


function rateLocation(rating, locationId, me, rbId) {
	dooyago.xmlrpc.executeAsync('LocationRatedBy.getDayDiff', function(ret, e) {
		if(e) { } else {
			var ans = ret.split("|");
			var ddiff = ans[0];
			var rated = "up";
			if(ans.length > 1) {
				rated = ans[1] == "true"? "up" : "down";
			}
			if(ddiff <= dooyago.rateDaysLimit && rated == rating) {
				var index = rating == 'up'? 13 : 22;
				var mtext = dooyago.functionM[index].replace('$1','Spot').replace('$2', dooyago.rateDaysLimit - ddiff).replace('$3', (dooyago.rateDaysLimit - ddiff) == 1? 'Tag' : 'Tage');
				alert(mtext);
				if(!dooyago.user > 0) {
					setTimeout(function() {
						window.location.reload();
					},1);
				}
			} else {
				dooyago.xmlrpc.executeAsync('Location.rate', function(ret,e) {
					if(e) {} else {
						var spots = $$('.locationScore' + locationId);
						var thumbsUp = document.getElementsByName('spotThumbUpImg' + locationId);
						var thumbsDown = document.getElementsByName('spotThumbDownImg' + locationId);
						for(var i = 0; i < spots.length; i++) {
							spots[i].pulsate();
							if(rating == 'up') {
								thumbsUp[i].src = "/front/design/Arrow _up_dark.png";
								thumbsDown[i].src = "/front/design/arrow_down_light.png";				
							} else {
								thumbsUp[i].src = "/front/design/arrow_up_light.png";
								thumbsDown[i].src = "/front/design/arrow_down_dark.png";				
							}
							spots[i].update(ret);
							if(!dooyago.user > 0) {
								setTimeout(function() {
									window.location.reload();
								},1);
							}
						}			
						
					}	
				}, locationId,rating);
			}
		}
	}, rbId, locationId);
}



function refreshComments() {
 	var targetId = $('targetId').value;
 	var targetName = $('targetName').value;
 	var pageNumber = $('pageNumber').value; 	
 	
 	hideComments();
 	showComments('comments.jsp?' + targetName + '=' + targetId +'&page='+ pageNumber);

}

function saveStatus() {
	if($('statusInput').value != 'Update your status') {
		status = $('statusInput').value;
		if (secureString(status)) {
			dooyago.xmlrpc.executeAsync('User.setStatus', function(ret,e) {
				if(e) {} else {
	/*				if(status != "") {
						$('statusInputDiv').hide();
						$('currentStatus').update(status);		
						$('currentStatusDiv').show();
						$('cancelStatusDiv').hide();
					 } else {
						//$('statusInput').setValue("Update your status");
						//$('cancelStatusDiv').hide();
						$('statusInputDiv').hide();
						$('currentStatusDiv').show();
						$('cancelStatusDiv').hide();
					 }*/
					 window.location.reload();
				}
			}, status);
		}
	}
}

function editStatus() {
	status = $('currentStatus').innerHTML;
	$('currentStatusDiv').hide();
	$('statusInputDiv').show();
	//$('statusInput').setValue(status);
	$('cancelStatusDiv').show();
	$('anStatus').hide();
}

function cancelStatus() {
	if(status == "") {
//		$('statusInputDiv').show();
		//$('statusInput').setValue(status);		
		$('currentStatus').hide();
		$('statusInputDiv').hide();
		$('currentStatusDiv').show();	
		$('anStatus').show();			
	} else {
		$('statusInputDiv').hide();
		$('currentStatusDiv').show();		
		$('anStatus').show();
		//$('currentStatus').update(status);				
	}
//	$('cancelStatusDiv').hide();		
}	


function saveAboutMe() {
	aboutMe = $F('aboutMeInput');
	if (secureString(aboutMe)) {
		dooyago.xmlrpc.executeAsync('User.setAboutMe', function(ret,e) {
			if(e) {/*alert(e.message);*/} else {
/*				$('aboutMeInputDiv').hide();
				$('currentAboutMe').update(aboutMe);		
				$('currentAboutMeDiv').show();
				$('cancelAboutMeDiv').hide();
				$('anpAboutMe').show();*/
				window.location.reload();
			}
		}, aboutMe);
	}
}

function editAboutMe() {
	aboutMe = $('currentAboutMe').innerHTML;
	$('currentAboutMeDiv').hide();
	$('aboutMeInputDiv').show();
//	$('aboutMeInput').setValue(aboutMe);
	$('cancelAboutMeDiv').show();
	$('anpAboutMe').hide();
}

function cancelAboutMe() {
	if(aboutMe == "") {
//		$('aboutMeInputDiv').show();
//		$('aboutMeInput').setValue(aboutMe);		
		$('currentAboutMe').hide();
	} else {
		$('aboutMeInputDiv').hide();
		$('currentAboutMeDiv').show();		
		$('currentAboutMe').update(aboutMe);				
		$('anpAboutMe').show();
	}
//	$('cancelAboutMeDiv').hide();		
}	

function moveSlider(id, pixels) {
	var div = $(id);
	var min = -$(div.cleanWhitespace().firstChild).getWidth();

	var pos = parseInt(div.style.left) + pixels;
			
	if(pos%pixels == 0 && pos <= 0 && pos > min) {
		move(id,pixels);
		
		pos += pixels;
		
		if(pos%pixels==0) {
			if(pos>0) {
				$('arrowLeft' + id).hide();
			}else {
				$('arrowLeft' + id).show();
			}
			
			if(pos <= min) {
				$('arrowRight' + id).hide();
			}else {
				$('arrowRight' + id).show();
			}
	
		}
	}

	return false;
}


function move(id,pixels) {
	var div = $(id);
	new Effect.Move(div, { x: pixels, y: 0, mode: 'relative' });
}

function collapseLeft(eid) {
	var div = $('recEvent' + eid);
	new Effect.Fade(div);
}

function collapseLeftHangs(lid) {
	var div = $('loc' + lid);
	new Effect.Fade(div);
}

function collapseLeftRecLoc(lid) {
	var div = $('recLocation' + lid);
	new Effect.Fade(div);
}


function hideEvent(eid) {
	collapseLeft(eid);
	dooyago.xmlrpc.executeAsync('User.addHiddenEvent', function (){},eid);
}

function hideEventFading(eid,divName) {
	
	var div = $(divName + '' + eid);
	dooyago.xmlrpc.executeAsync('User.addHiddenEvent', function (ret,e){
		if(e) {} else {
			new Effect.Fade(div,{from:1.0, to:0.4});
			$(divName + '' + eid + 'AddButton').hide();
			$(divName + '' + eid + 'HideButton').hide();			
			var n = $('n' + divName).innerHTML;
			if(n > 0) {
				$('n' + divName).update(n - 1);
			}
		}
	},eid);	
}

function hideLocationFading(lid) {
	var div = $('location' + lid);
	dooyago.xmlrpc.executeAsync('User.addHiddenLocation', function (ret,e){
		if(e) {} else {
			new Effect.Fade(div,{from:1.0, to:0.4});
			$('location' + lid + 'AddButton').hide();
			$('location' + lid + 'HideButton').hide();			
			var n = $('nlocation').innerHTML;
			if(n > 0) {
				$('nlocation').update(n - 1);
			}
		}	
	},lid);
}


function hideLocation(lid) {
	collapseLeftRecLoc(lid);
	dooyago.xmlrpc.executeAsync('User.addHiddenLocation', function (){},lid);
}

function hidePerson(pid) {
	new Effect.Opacity('evNeigh' + pid, { from: 1.0, to: 0.3, duration: 0.5 });
	dooyago.xmlrpc.executeAsync('User.addHiddenUser', function (){}, pid); 
}

	
function showWhoLikes(id, url) {
	var sourceWhoLikes = application.wrapNode($(id));
	if (!sourceWhoLikes.isOpened()) { 
		sourceWhoLikes.setUrl("/front/" + url);
		sourceWhoLikes.open(function() {
			$('commentsRoller').hide();
		});
	}
}

function hideWhoLikes(id) {
	var sourceWhoLikes = application.wrapNode($(id));
	if (sourceWhoLikes.isOpened()) {
		sourceWhoLikes.close();
	}
	$('commentsRoller').show();
	
}


function moveInterested(id,pageNumber,gender,totalPages,totalDivs, size,pixels,target) {
	if(parseInt($('userIntDiv').style.left)%pixels == 0){
		var divCount = $('divCount').value;
		if(pixels > 0) {
			
			if(divCount == 1 && pageNumber == 1) {
				$('arrowLeft').hide();
			}
			
			if(divCount == 0) {
				var page = pageNumber - 1;
				hideInterested();
				showInterested('interestedwidget.jsp?' + target + '='+ id +'&page=' + page +'&gender=' + gender + '');							  						
			} else {
				 moveSliderInterested(size,'userIntDiv',pixels);
				if(divCount < totalDivs) 
				{
					divCount--;
					$('divCount').setValue(divCount);
				}
			} 	
		} else {
			// Move to next
			if(pageNumber == totalPages && totalDivs == parseInt(divCount)+2) {
				$('arrowRight').hide();
			}
			if((divCount + 1) == totalDivs) {
				var page = pageNumber + 1;
				hideInterested();
				showInterested('interestedwidget.jsp?' + target + '='+ id +'&page=' + page +'&gender=' + gender + '');							  						
			} else {
				moveSliderInterested(size,'userIntDiv',pixels);
				if(divCount < totalDivs) 
				{
					divCount++;
					$('divCount').setValue(divCount);
				}
			}
		}
	}
	return false;	
}


function moveAttending(id,pageNumber,totalPages,totalDivs, size,pixels,target) {
	if(parseInt($('userIntDiv').style.left)%pixels == 0){
		var divCount = $('divCountFriends').value;
		var divCountFriends = divCount;
		 
		if(pixels > 0) {
			
			if(divCount == 1 && pageNumber == 1) {
				$('arrowLeftFriends').hide();
			}
			
			if(divCountFriends == 0) {
				var page = pageNumber - 1;
				hideAttending();
				showAttending('friendsattendingwidget.jsp?' + target + '='+ id +'&page=' + page + '');							  						
			} else {
				 moveSliderInterested(size,'userIntDivFriends',pixels);
				if(divCountFriends < totalDivs && parseInt($('userIntDiv').style.left)%pixels == 0) 
				{
					divCountFriends--;
					$('divCountFriends').setValue(divCountFriends);
				}
			} 	
		} else {
			// Move to next
			if(pageNumber == totalPages && totalDivs == parseInt(divCountFriends)+2) {
				$('arrowRightFriends').hide();
			}
			if((divCountFriends + 1) == totalDivs) {
				var page = pageNumber + 1;
				hideAttending();
				showAttending('friendsattendingwidget.jsp?' + target + '='+ id +'&page=' + page  + '');							  						
			} else {
				moveSliderInterested(size,'userIntDivFriends',pixels);
				if(divCountFriends < totalDivs && parseInt($('userIntDivFriends').style.left)%pixels == 0) 
				{
					divCountFriends++;
					$('divCountFriends').setValue(divCountFriends);
				}
			}
		}
	}
	return false;	
}



function moveSliderInterested(pages,id, pixels) {
	var div = $(id);
	var pos = parseInt(div.style.left) + pixels;
	var min = -1*pages* Math.abs(pixels);
	if(pos%pixels == 0 && pos <= 0 && pos > min) {
		move(id,pixels);
		
		pos += pixels;		
	}
}


 
 function moveLoopSlider(id, pixels) {
	var div = $(id);

		if (moves == 0) {
			var last = div.lastChild;
			last.parentNode.removeChild(last);
		}
		
	if (moves>=groupPages-1) {
		var groups = div.childNodes;
		var firstGroup = div.childNodes[moves - groupPages + 1];
		
		var newDiv = firstGroup.cloneNode(true);
		newDiv.style.width=application.wrapNode(firstGroup).getWidth()+'px';
		newDiv.innerHTML='&nbsp;';
		
		div.appendChild(firstGroup.cloneNode(true));

		setTimeout(function() {
			firstGroup.parentNode.replaceChild(newDiv,firstGroup);
		},1000);
		

	}
	move(id,pixels);
	moves++;
	
}

function triggerSlider() {
	if(groupPages >= 1)
		lock = setInterval(function() {
			moveLoopSlider('groupSlider',-780);
		}, 10000);
}

function addToFriends(userId) {
	dooyago.xmlrpc.executeAsync('User.addFriend', function (){}, userId); 
}

function removeFromFriends(userId, userName) {
	if(confirm(dooyago.functionM[18] + userName + dooyago.functionM[19])) {
		dooyago.xmlrpc.executeAsync('User.deleteFriend', function (){}, userId); 
		window.location.reload();
	}
}


function setCalendarViews(view) {
	$$('div.c'+view).each(function(item) {
		$(item.firstChild).toggleClassName('cal'+view);
		if (item.firstChild.className.blank()) {
			item.hide();
		} else {
			item.show();
		};
	});
}

function addView(id,target) {
	if(!idInCookie(id, target)) {	
		dooyago.xmlrpc.executeAsync(target + '.addView',function(ret,e) {
				if(e) {} else {
				
				}
			}, id);
	}
}


function idInCookie(id, target) {
	target = target.toLowerCase();
	var cookie = getCookie(target + "s");
	if(cookie != null && cookie.indexOf('|' + id + '|') >= 0) {
		return true;		
	}
	
	if(target != "user") {
		var nids = "|" + id + "|";
		if(cookie != null) {
			nids = nids + cookie;
		} 
		var date = new Date();
		
		// Time diff until 24hs (in seconds)
		var time = (24 * 60 * 60) - (date.getHours() * 60 * 60 + date.getMinutes() * 60 + date.getSeconds());
		
		// Time diff until 4am (in seconds)
		time = time + 4 * 60 * 60;
		
		// Time diff in miliseconds
		time = time * 1000;
		date.setTime(new Date().getTime()+ time);
	    var expires = 'expires=' + date.toGMTString() + ';path=/';
	    var ncookie = "events=" + nids + ";" + expires;
		document.cookie = ncookie; 
	}

	
	return false;
}

function addActivity() {
	dooyago.xmlrpc.executeAsync('UserActivity.addActivity',function(ret,e) {
			if(e) {} else {
			
			}
		});
}

function calToggleAdded() {
	if(added == 'true') {
		added = 'false';
	} else {
		added = 'true';
	}
}

function calTogglePosted() {
	if(posted == 'true') {
		posted = 'false';
	} else {
		posted = 'true';
	}
}

function calToggleFriends() {
	if(friends == 'true') {
		friends = 'false';
	} else {
		friends = 'true';
	}
}

function changeCalendar(a, p, f , m) {
	var link =  '?added=' + a + '&posted=' + p + '&friends=' + f + '&date=' + m;
	window.location = link;
}

function initCalendarViews () {
	if(friends == 'true') {
		dooyago.onloadF.push(function() {$('friendInput').checked='true';setCalendarViews('Friend');});	
	}
	
	if(posted == 'true') {
	dooyago.onloadF.push(function() {$('postedInput').checked='true';setCalendarViews('Posted');});
	}
	
	if(added == 'true' ) {
		dooyago.onloadF.push(function() {$('addedInput').checked='true';setCalendarViews('Added');});
	}
}

function showSearchOptions(target) {
	if(target == 'Events') {
		$('eventType').show();
		//$('cities').show();		
	} else if(target == 'Places') {
		$('eventType').hide();
		//$('cities').show();					
	} else if(target == 'People'){
		$('eventType').hide();
		//$('cities').show();				
	} else {
		$('eventType').hide();
		//$('cities').hide();	
	}
}

function searchLink() {
	var categories = $('searchCategories');
	var search = encodeURIComponent($('lookFor').value);
	if(search != '') {
		var searchTag = false;
		var cities = $('cities');
	
		var cat = categories.options[categories.selectedIndex].value;
		if(cat == 'Alles') {
			window.location.href = "/front/searchresult.jsp?search=" + search;
		} else {
			var link = "cat=" + cat;
			if(searchTag) {
				link = link + "&searchTag=" + search;
	 		} else {
	 			link = link + "&searchAll=" + search;
	 		}
	 		/*if(cities != null) {
				var city = cities.options[cities.selectedIndex].text;
				link = link + "&searchCity=" + city;
			}*/
			if(cat == "Events") {
				if($('upcomingEvents').checked) {
					link = link + "&type=upcoming";
				} else if($('pastEvents').checked) {
					link = link + "&type=past";
				}
			}
			window.location.href = "/front/search.jsp?" + link;
		}
	} 

}

function selectMessages(state) {
	var x = document.getElementsByName('selectCheck');
	for(var i = 0; i < x.length; i++) {
		x[i].checked = state;
	}
	if(state == 'true') { 
		$('selectAll').style.display = 'none';
		$('unselectAll').style.display = '';
	} else {
		$('selectAll').style.display = '';
		$('unselectAll').style.display = 'none';	
	}
}


function deleteSelectedInbox(target,boxType,page) {
	var x = document.getElementsByName('selectCheck');
	var erase = "";
	for(var i = 0, j = 0; i < x.length; i++) {
		if(x[i].checked) {
			var id = x[i].value;
			if(erase != "") {
				erase = erase + ",";
			}
			erase = erase + id;
		}
	}	
	if(erase.length > 0) {
		dooyago.xmlrpc.executeAsync(target+ '.delete' + target,function(ret,e) {
				if(e) {} else {
					window.location.href="/front/inbox.jsp?box=" + boxType + "&page=" + page;
				}
			}, erase);
	}			
	
}

function deleteMessage(boxType, page, id) {
	if(confirm(dooyago.functionM[20])){
		dooyago.xmlrpc.executeAsync('Message.deleteMessage',function(ret,e) {
					if(e) {} else {
						window.location.href="/front/inbox.jsp?box=" + boxType + "&page=" + page;
					}
				}, id);
	}
}

function deleteInvitation(boxType, page, id) {
	dooyago.xmlrpc.executeAsync('Invitation.deleteInvitation',function(ret,e) {
				if(e) {} else {
					window.location.href="/front/inbox.jsp?box=" + boxType + "&page=" + page;
				}
			}, id);
}

function deleteNotification(boxType, page, id) {
	dooyago.xmlrpc.executeAsync('Notification.deleteNotification',function(ret,e) {
				if(e) {} else {
					window.location.href="/front/inbox.jsp?box=" + boxType + "&page=" + page;
				}
			}, id);
}

function searchLinkHome(url) {
	var search = $('lookFor').value;
	if(url) {
		window.location.href = "/front/" + url + "?cat=Events&type=upcoming&searchAll=" + search;
	} else {
		window.location.href = "/front/search.jsp?cat=Events&type=upcoming&searchAll=" + search;
	}
}




function updateUnread(read) {
	if(read == 'false') {
		if($('inboxUnread') != null) {
			var text = $('inboxUnread').innerHTML;
			var cant = text.substr(1,text.length - 2) - 1;
			if(cant > 0) {
				$('inboxUnread').update('(' + cant + ')');	
			} else {
				$('inboxUnread').hide();
			}
			reduceMessagesUnread(1);
		}
	}
}

function showMessageOptions(box) {
		var options = new Array('messages','friends', 'invites');
		options.each(function(item) {
			if(item != box) {
				$(item + 'Options').hide();
				$(item + 'ArrowDown').hide();
				$(item + 'Arrow').show();
			} else {
				$(item + 'Options').show();
				$(item + 'Arrow').hide();				
				$(item + 'ArrowDown').show();
			}
		});
}

function searchLinkHome() {
	var search = $('lookFor').value;
	window.location.href = "/front/search.jsp?cat=Events&type=upcoming&searchAll=" + search;
}

function addFriendInWidget(uId) {
	showForm('/forms.Main/FriendRequest_form.htmli?lang=de', 'FriendRequest',uId, 'forUser');
}

function changeToContact(uId) {
	dooyago.xmlrpc.executeAsync('User.changeToContact',function(ret,e) {
		if(e) {} else {
		
		}
	}, uId);
	window.location.reload();
}

function changeToFriend(uId) {
	dooyago.xmlrpc.executeAsync('User.changeToFriend',function(ret,e) {
		if(e) {} else {
		
		}
	}, uId);
	window.location.reload();
}

function addBookmark(uId) {
	dooyago.xmlrpc.executeAsync('User.addBookmark',function(ret,e) {
		if(e) {} else {
		
		}
	}, uId);
}

function deleteBookmark(uId) {
	dooyago.xmlrpc.executeAsync('User.deleteBookmark',function(ret,e) {
		if(e) {} else {
		
		}
	}, uId);
}


function deleteFriendRequest(requestId,boxType, page) {	
	if(confirm(dooyago.functionM[21])){
		dooyago.xmlrpc.executeAsync('FriendRequest.deleteRequest', function(ret,e) {
			if(e) { alert(e.message);} else {
				if(new String(window.location).indexOf("/leute/") > 0) {
					
					window.location.reload();
				} else {	
					window.location.href="/front/inbox.jsp?box=" + boxType + "&page=" + page;
				}
			}
		}, requestId);		
	}
}

function confirmFriendRequest(requestId, f) {
	dooyago.xmlrpc.executeAsync('FriendRequest.confirmRequest', function(ret,e) {
		if(e) {} else {
			if(new String(window.location).indexOf("/leute/") > 0) {
				window.location.reload();
			} else {
				$('requestTr'+ requestId).fade();
				$('requestTr'+ requestId).slideUp();		
				updateRequests();
				reduceMessagesUnread(1);
			}
		}
	}, requestId);		
	
}

function updateRequests() {
	if($('friendRequests') != null) {
		var text = $('friendRequests').innerHTML;
		var cant = text.substr(1,text.length - 2) - 1;
		if(cant > 0) {
			$('friendRequests').update('(' + cant + ')');	
		} else {
			$('friendRequests').hide();
		}
	}
}

function showIMightRunInto(url) {
	var sourceWhoLikes = application.wrapNode($('sourceIMightRunInto'));
	if (!sourceWhoLikes.isOpened()) { 
		sourceWhoLikes.setUrl("/front/" + url);
		sourceWhoLikes.open(function() {
			$('commentsRoller').hide();
		});
	}
}

function showIMightLike(url) {
	var sourceIMightLike = application.wrapNode($('sourceIMightLike'));
	if (!sourceIMightLike.isOpened()) { 
		sourceIMightLike.setUrl("/front/" + url);
		sourceIMightLike.open(function() {
			$('commentsRollerLike').hide();
		});
	}
}



function hideIMightLike() {
	var sourceWhoLikes = application.wrapNode($('sourceIMightLike'));
	if (sourceWhoLikes.isOpened()) {
		sourceWhoLikes.close();
	}
	$('commentsRollerLike').show();
	
}

function showHotThisWeek(url) {
	var sourceWhoLikes = application.wrapNode($('sourceHotThisWeek'));
	if (!sourceWhoLikes.isOpened()) { 
		sourceWhoLikes.setUrl(url);
		sourceWhoLikes.open(function() {
			$('commentsRollerHot').hide();
		});
	}
}

function hideHotThisWeek() {
	var sourceWhoLikes = application.wrapNode($('sourceHotThisWeek'));
	if (sourceWhoLikes.isOpened()) {
		sourceWhoLikes.close();
	}
	$('commentsRollerHot').show();
	
}

function hidePersonIMightLIke(pid) {
	var div = $('mightLike' + pid);
	new Effect.Fade(div);
	dooyago.xmlrpc.executeAsync('User.addHiddenUser', function (){}, pid); 
}

function makePrimaryPhoto(pid, aid) {
	dooyago.xmlrpc.executeAsync('Album.changePrimaryPhoto', function (ret,e){
		if(e) {} else {
			editAlbum(aid);
		}
	}, pid, aid); 
}

function editAlbum(aid) {
	var table = $('photosTable');
	var rows = table.rows.length;
	var array = new Array();
	for(var i = 1; i < rows; i++) {
		var rowInfo;
		var id = table.rows[i].cells[0].innerHTML;
		rowInfo = id;
		rowInfo = rowInfo + "-" + $('order' + id).value;
		rowInfo = rowInfo + "-" + $('caption' + id).value;
		array[i - 1] = rowInfo;
	}
	dooyago.xmlrpc.executeAsync('Album.editChanges', function (ret,e){
		if(e) {} else {
			window.location.reload();
		}
	}, aid, array); 
	
}

function deletePhoto(pId) {
	dooyago.xmlrpc.executeAsync('Photo.deletePhoto', function (ret,e){
		if(e) {
//			alert(e.message);
		} else {
			alert(ret);
			/*if(ret.split("-")[0] == "true") {
				dooyago.xmlrpc.executeAsync('Album.setRandomPrimary',function(ret,e) {
					window.location.reload();
				},ret.split("-")[1]);
			} else {*/
				window.location.reload();
			//}
		}
	}, pId); 	
}

function tagPhoto(event, photoId) {
	var square = $('tagSquare');
	
	var imageDiv = $('taggingPhotoImg');

	var wrap = application.wrapNode(imageDiv);
	var imageX = wrap.getX() - application.getScrollLeft();
	var imageY = wrap.getY() - application.getScrollTop();	

	var top = event.getClientY() - imageY - 50;
	var left = event.getClientX() - imageX  - 50;
	square.style.top = top  + "px";
	square.style.left = left + "px";
	square.show();
	showForm('/forms.Main/TagPhoto_form.htmli?lang=de', 'TagPhoto','' + top + '/' + left + '/' + photoId + '' , 'forPosition');
}

function onTagPhoto(tagging) {
	if(tagging) {
		$('tagPhoto').hide();
		$('tagPhotoImg').hide();
		$('taggingPhoto').show();
		$('taggingPhotoImg').show();
	}	else {
		$('tagPhoto').show();
		$('tagPhotoImg').show();
		$('taggingPhoto').hide();
		$('taggingPhotoImg').hide();
		hideTagSquare();
	}
}

function hideTagSquare() {
	$('tagSquare').hide();
}

dooyago.lock = false;
function createTag(top,left,id) {

	var div = $('tag'+id);
	if (div && div.style.display=='none') {
		div.show();	
	} else if (!dooyago.lock) {
		dooyago.lock = true;
		dooyago.xmlrpc.executeAsync('PhotoTag.getTagLabel', function (ret,e){
			if(e) {
				dooyago.lock = false;
			} else {
				dooyago.lock = false;			
				var square = $('tagSquare');	
				var newTag = document.createElement("div");
	
				var imageDiv = $('imageCont');
				var wrap = application.wrapNode(imageDiv);
				var imageX = wrap.getX();
				var imageY = wrap.getY();	
													
				var t = parseInt(top) + parseInt(imageY);
				var l = parseInt(left) + parseInt(imageX);
				
				newTag.style.top = t + "px";
				newTag.style.left = l + "px";
				newTag.className = "tag";
				newTag.id = "tag" + id;
			
				var label = newTag.appendChild(document.createElement("span"));
				label.className = "tagFooter";
				label.innerHTML = ret;
			
				newTag.onmouseout = function() { destroyTag(id) };
				document.body.appendChild(newTag);			
				
			}
		}, id); 	
	}	

}

function destroyTag(id) {
	var tag = document.getElementById('tag' + id);
	if(tag) {
		document.body.removeChild(tag);
	}
}




function deleteTag(id) {
	dooyago.xmlrpc.executeAsync('PhotoTag.deleteTag', function (ret,e){
		if(e) {} else {
			window.location.reload();
		}
	}, id); 		
}

function deleteAlbum(albumId,userId) {
	dooyago.xmlrpc.executeAsync('Album.deleteAlbum', function (ret,e){
		if(e) {} else {
			window.location.href="/front/albums.jsp?user=" + userId;
		}
	}, albumId); 			
}

function storeForgotPassword(me) {
	jrapid.store(me, function() {
		setTimeout(function() {
			alert(dooyago.functionM[5]);
		},1000);	
	});
	return false; 
}

function uncheckAllContacts() {
	var form = $('contacts');
	var chbxs = form.getElements();
	chbxs.each(function(item) {
		item.checked = false;
	});
	
	$('uncheckAll').hide();
	$('checkAll').show();
}

function checkAllContacts() {
	var form = $('contacts');
	var chbxs = form.getElements();
	chbxs.each(function(item) {
		item.checked = true;
	});
	
	$('uncheckAll').show();
	$('checkAll').hide();
}
function sendEmails() {
	var form = $('contacts');
	var chbxs = form.getElements();
	var mails = "";
	var sentMails = false;
	
	chbxs.each(function(item) {
		if(item.checked) {
			mails += item.value + ",";
			sentMails = true;
		}
	});
	
	if(sentMails) {
		dooyago.xmlrpc.executeAsync('SendInvite.sendInvitesToContacts', function (ret,e){
				if(e) {} else {
					//window.location.href="albums.jsp?user=" + userId;
						$('importData').hide();
						$('invitationSent').show();
						registerSuccessful("ContactImporter");
				}
			}, mails); 		
	
		form.disable();

	} else {
		$('noEmails').show();
	}
}

function registerSuccessful(entity) {
	var path = dooyago.serverPath + "front/Successful_" + entity;

	pageTracker._trackPageview(path);	
}

function registerUser(me) {
	jrapid.store(me, function(id) {
		registerSuccessful('Registration');
		setTimeout(function() {
			alert(dooyago.functionM[6]);
		},1000);
	});
	return false; 
}

	function getCookie( check_name ) {
		var a_all_cookies = document.cookie.split( ';' );
		var a_temp_cookie = '';
		var cookie_name = '';
		var cookie_value = '';
		var b_cookie_found = false; // set boolean t/f default f
		
		for ( i = 0; i < a_all_cookies.length; i++ ) {
			a_temp_cookie = a_all_cookies[i].split( '=' );
			
			cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		
			if ( cookie_name == check_name ) {
				b_cookie_found = true;
				if ( a_temp_cookie.length > 1 ) {
					cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
				}
				return cookie_value;
				break;
			}
			a_temp_cookie = null;
			cookie_name = '';
		}
		if ( !b_cookie_found ) {
			return '';
		}
	}				

function setRead(target, read) {	
	if(read > 0) {
		dooyago.xmlrpc.executeAsync(target + '.read' + target, function (ret,e){
			if(e) {} else {
				$(target + 'Unread').hide();
				reduceMessagesUnread(read);			
			}
		}); 				
	}	
}

function reduceMessagesUnread(read) {
	var inc = $('inboxMessagesNum').innerHTML;
	if(inc - read < 1) {
		$('inboxMessagesCount').hide();
	} else {
		$('inboxMessagesNum').update(inc - read);
	}
}





function showHidden(target, id) {
		dooyago.xmlrpc.executeAsync('User.showHidden', function (ret,e){
			if(e) {} else {
				window.location.reload();
			}
		}, target,id); 		
}

function showMessageBody(id, sent) {
	if(sent == null) {
		setMessageAsRead(id);
	}
	$('body' + id).toggle();
//	$('arrow' + id).toggle();
	var arrowType = new String($('arrow' + id).src);
	$('arrow' + id).src = arrowType.indexOf('down') > 0? '/front/design/arrow_orange_dark_s.gif' : '/front/design/arrow_orange_dark_down.gif';
	$('title' + id).className='title3 greenLink';
}

function changeGender(gender, source, link) {
	var imgs = new Array('a','f', 'm');
	hideWhoLikes(source);
	showWhoLikes(source, link + 'gender=' + gender);
	
	imgs.each(function(item) {
		if(item == gender) {
			$(source + item).className = '';
		} else {
			$(source + item).className = 'fadeImg';
		}
	});
	return false;
}

function checkUpload(f) {
	if($('checkToUpload').checked) {
		f();
	} else {
		alert(dooyago.functionM[9]);
	}
}

var noFreeTickets = false;

function freeTicket(eventId,message, freeTicketActive) {
	var email = $('freeTicket_email').value;
	if(email != null && email.indexOf("@") > 0) {
		dooyago.xmlrpc.executeAsync('FreeTicket.addTicket', function (ret,e){
			if(e) {} else {
				if(ret == -1) { alert(dooyago.functionM[26]); }
				else{
					pageTracker._trackPageview(dooyago.serverPath + 'front/Freeticket');			
					setTimeout(function() {
							if(noFreeTickets) {
								message = 1;
							}
							if(freeTicketActive == true) {
								alert(dooyago.functionM[14 + message]);
							} else {
								alert(dooyago.functionM[23]);
							}
							//hay que cambiar el mensaje aca segun si tiene el boolean de freeticket activado o no
						$('freeTicket_email').value = "Deine Emailadresse eintragen";
					},1000);		
					var target = $('freeTicketFrame');
					window.open('freeticket.jsp','freeTicketFrame');
				}			
			}
		}, eventId, email, freeTicketActive); 		
	}

}

function sendPhoneInfo(eventId,userId) {
	var phone = $('freeTicket_phone').value;
	if(phone != null && phone != 'Deine Telefonnummer' ) {
		dooyago.xmlrpc.executeAsync('EventServices.sendContactInformation', function (ret,e){
		if(e) {} else {			
			alert('Vielen Dank f\u00FCr Dein Interesse! \r\nWir haben Deine Nachricht erhalten und werden uns in den n\u00E4chsten Stunden bei Dir melden.' );
			$('additional').style.display = 'none'; $('button1').show(); $('initial').style.marginBottom='50px';				
		}
	},userId,eventId,phone);
	
		 		
	}
}

function sendMailInfo(eventId,userId) {

	dooyago.xmlrpc.executeAsync('EventServices.sendContactInformation', function (ret,e){
		if(e) {} else {			
			alert('Vielen Dank f\u00FCr Dein Interesse! \r\n Wir haben Deine Nachricht erhalten und werden uns in den n\u00E4chsten Stunden bei Dir melden.' );
			$('additional').hide(); $('button1').show(); $('initial').style.marginBottom='50px';				
		}
	},userId,eventId," ");
}

function updateTimer() {
	setTimeout(function() {
		if($('timerHs')) {
			var sec = $('timerSec').innerHTML;
			var min = $('timerMin').innerHTML;
			var hs = $('timerHs').innerHTML;
			if(sec == 0) {
				sec = 59;
				var min = $('timerMin').innerHTML;
				if (min == 0) {
					min = 59;
					var hs = $('timerHs').innerHTML;
					if(hs == 0) {
						 $('timerHs').innerHTML = "00";
						 $('timerMin').innerHTML = "00";
						 $('timerSec').innerHTML = "00";						 						 
						 noFreeTickets = true;
						 return;
					} else {
						hs  = hs - 1;
					}
				} else {
					min = min - 1;
				}
			} else {
				sec = sec - 1;
				
			}
			 $('timerHs').innerHTML = ((hs.length < 2)? '0' + hs : hs);
			 $('timerMin').innerHTML = ((min.length < 2)? '0' + min : min);
			 $('timerSec').innerHTML = ((sec.length < 2)? '0' + sec : sec);						 						 
			
			updateTimer();
		}
	},1000);					
}

var ratingTimer;
var msg;

function setRatingUp(me) {
	setRatingTimer('Yeah!');
	me.onmouseout = function(me) { 
		clearRatingTimer();
	 }; 
}

function setRatingDown(me) {
	setRatingTimer('Buuh!');
	me.onmouseout = function(me) { 
		clearRatingTimer();
	 }; 
}


function setRatingTimer(message) {
	msg = message;
	clearTimeout(ratingTimer);
/*	ratingTimer = setTimeout("alert(msg);", 3000);*/
	ratingTimer = setTimeout(function() {
		window.status = msg;
	}, 3000);
}

function clearRatingTimer() {
	clearTimeout(ratingTimer);
}



JRapid.prototype.checkIf = function(obj, bool) {
    if (!bool) {
        jrapid.hasErrors += 'Error ';
    }
    obj.style.backgroundColor = bool ? '': 'red';
};

var dateRegExp = /(?:0[1-9]|[12][0-9]|3[01])[\/\.-](?:0[1-9]|1[0-2])[\/\.-]((19|20)?\d{2})/;
//var dateRegExp = '\\d\\d[/\.-]\\d\\d[/\.-](\\d\\d)?\\d\\d';

JRapid.validations = [];
JRapid.validations['required'] = function(obj) { return obj.value && (obj.tagName.toLowerCase() != 'select' || obj.value != '0') ? null : (dooyago.valM[0] + obj.title); };
JRapid.validations['date'] = function(obj) { return obj.value == '' || dateRegExp.test(obj.value)? null : (dooyago.valM[1] + obj.title); };
JRapid.validations['datetime'] = function(obj) { return obj.value == '' || obj.value.match(jrapid.dateTimeRegExp) ? null : (dooyago.valM[0] + obj.title); };
JRapid.validations['time'] = function(obj) { return obj.value == '' || obj.value.match(jrapid.timeRegExp) ? null : (dooyago.valM[1] + obj.title); };
JRapid.validations['timequantity'] = function(obj) { return obj.value == '' || obj.value.match(jrapid.timeQuantityRegExp) ? null : (obj.title + ' es cantidad de tiempo'); };
JRapid.validations['timerange'] = function(obj) { return obj.value == '' || obj.value.match(jrapid.timeRangeRegExp) ? null : (obj.title + ' es rango de tiempo'); };
JRapid.validations['email'] = function(obj) { return obj.value == '' || obj.value.match(/^([a-zA-Z0-9_\-\.])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/) ? null : (obj.title +  dooyago.valM[4]);};
JRapid.validations['short'] = function(obj) { return obj.value == '' || obj.value.match('\\d*') ? null : (obj.title + ' es short'); };
JRapid.validations['integer'] = function(obj) { return obj.value == '' || obj.value.match('\\d*') ? null : (dooyago.valM[5] + obj.title ); };
JRapid.validations['long'] = function(obj) { return obj.value == '' || obj.value.match('\\d*') ? null : (obj.title + ' es long'); };
JRapid.validations['float'] = function(obj) { return obj.value == '' || obj.value.match('\\d*(\\.\\d+)?') ? null : (dooyago.valM[6] + obj.title); };
JRapid.validations['double'] = function(obj) { alert("value: " + obj.value); return obj.value == '' || obj.value.match('\\d*(\\.\\d+)?') ? null : (obj.title + ' es double'); };


/*function goTo(url) {
 var a = document.createElement(a);
 if(!a.click) { //only IE has this (at the moment);
  window.location = url;
  return;
 }
 a.setAttribute("href", url);
 a.style.display = "none";
 $("body").appendChild(a); //prototype shortcut
 a.click();
}*/
function secureString(str) {
	if (str.match('((\%3C)|<)[^\n]+((\%3E)|>)')) {
		return false;
	} else {
		return true;
	}
}


JRapid.prototype.validate = function(form) {
    var elements = form.elements;
    var n = elements.length;
    var msg = '';
    var first = null;
    for (var i=0; i < n; i++) {
        var validation = elements[i].getAttribute('validate');
        var currentStyle = elements[i].parentNode.currentStyle ? elements[i].parentNode.currentStyle : window.getComputedStyle(elements[i].parentNode,null);
        if (validation && currentStyle.color != 'green' && currentStyle.color != 'rgb(0, 128, 0)') {    
            var validations = validation.split(',');
            var hasErrors = false;
            for (var j=0; j < validations.length; j++) {
                if (JRapid.validations[validations[j]]) {
                    var errorMessage = JRapid.validations[validations[j]](elements[i]);
                    if (errorMessage) {
                        msg += errorMessage + '\n';
                        first = elements[i];
                        hasErrors = true;
//                        elements[i].style.color = 'red';
                    }    
                }            
            }
//            elements[i].style.color = hasErrors ? 'red' : '';
        }    
        if (validation && !secureString(elements[i].value)) {
	        hasErrors = true;        
    	    msg += (dooyago.valM[7] + '\n');
    	}
    }
    if (msg.length) {
        alert(msg);
        try { first.focus(); } catch (e) {}
        return false;
    }
    
    return true;
    
};

var adFields = ["MainTopAd","MainBottomAd","MainMiddleAd","TopAd","BottomAd" ]; // removed: "MiddleAd",
var adFields2 = ["rightMiddleAdd"];
function showAd(ad) {
	  GA_googleFillSlot(ad);
}

function hideAds() {
	for(var i = 0; i < adFields.length; i++) {
		if($('table' + (adFields[i])) && (($(adFields[i]).innerHTML).indexOf('GA_googleCreateDomIframe') <= 0)) {
			$('table' + (adFields[i])).hide();
			
		}
	}
	for(var i = 0; i < adFields2.length; i++) {
		if($(adFields2[i]) != null && (($(adFields2[i]).innerHTML).indexOf('GA_googleCreateDomIframe') <= 0)) {
			$(adFields2[i]).hide();
			$(adFields2[i] + 'Space').hide();
			$(adFields2[i]+'2').show();
		}
	}
	
}

function showRegistration() {
	showForm('/forms.Main/Registration_form.htmli?lang=de', 'Registration','0', '');
	return false;
}

function displayMoreDates() {
	if($('moreDates').style.display == 'none') {
		$('moreDates').show();
		$('moreDatesLink').update('nur n\u00E4chste 7 Termine anzeigen');
	} else {
		$('moreDates').hide();
		$('moreDatesLink').update('alle Termine anzeigen');
	}
	
}	

function showTextMore(ev,url,centered) {
	var div = $('textMoreDiv');
	var coords = getTextMoreCoordinates(ev);
	div.setStyle('top:'+coords[0]+'px;left:'+coords[1]+'px;');
	div.show();
	div.firstChild.firstChild.innerHTML = url;

}

function getTextMoreCoordinates(ev) {
	var htmlElement = application.getDocumentElement();
	var top = ev.getClientY()+application.getScrollTop();
	var left = ev.getClientX()+application.getScrollLeft()+30;
	var overflowY = (ev.getClientY() + 40 + 25) - pageHeight();
	var width = pageWidth();
	var overflowX = (ev.getClientX() + 330 + 55) - width;	

	if (overflowY > 0) {
		top = top - (overflowY+30);
	}
	if (overflowX > 0) {
		left = left - (overflowX+350+30);
	}
	return [top,left];
}

jrapid.timeoutSeconds = 100;


function changeSel(index, div, total) {
	for(var i=0; i < total; i++) {
		if(i == (index - 1)) {
			$(div + (i + 1)).className = 'eventSel';
			$('events' + div + (i + 1)).show();	
		} else {
			$(div + (i + 1)).className = 'eventNotSel';
			$('events' + div + (i + 1)).hide();	
		}
	}
	return false;
}

function setSel(e) {
	e.setAttribute('oldClass',e.className);
	e.className='eventSel'
}


function restoreSel(e, div, total) {
	var sel = 0;

	for(var i=0; i < total; i++) { 
		if($(div + (i + 1)).className == 'eventSel') {
			sel++;
		}
	}
	if(sel > 1) {
		e.className=e.getAttribute('oldClass');
	}
}


function setTab(e) {
	e.setAttribute('oldClass',e.className);
	e.className='tabSel'
}

function restoreTab(e) {
	e.className=e.getAttribute('oldClass');

}

function addEventDates(me) {
	var multDates = me.getContainer().getElementById('createEvent_multDates').getValue();
	
	var container = me.getContainer();
    var sourcePrototype = container.getElementById('source').cloneNode(true);
    container.getElementById('formcanvas').appendChild(sourcePrototype);
    sourcePrototype.setUrl('../forms.Main/CreateEventDates_form.htmli?lang=de');
    
    // start console
    var txOpenForm = jrapid.startConsole('Opening form', false, 'green');
    
    sourcePrototype.open(function() {
    	// end console

    	jrapid.endConsole(txOpenForm);
    
    	if (!sourcePrototype.isOpened()) {
		    var tx = jrapid.startConsole('Network error', true, 'red');    		
		    return;
    	}
    
        var childContainer = sourcePrototype.getChildContainer();
        jrapid.loadForm(childContainer, 'CreateEventDates', '0', 'forEvent');
    });
    sourcePrototype.getChildContainer().node.listingContainer = container;
	
//	showForm('/forms.Main/CreateEventDates_form.htmli?lang=de', 'CreateEventDates','0', '');				
}

function deleteContent(me) {
	if(me.value == 'Events, Spots & Leute suchen...' || me.value == 'Deine Emailadresse eintragen') {
		me.value = '';
	}
}

function addContent(me) {
	if(me.value == '') {
		me.value = 'Deine Emailadresse eintragen';
	}
}

function addEventFeedback(eventId, fade) {
	$('myEvent' + eventId).show();
	$('notMyEvent' + eventId).hide();
	
	if(fade) {
		var div = $('fadeEvent' + eventId);
		new Effect.Fade(div);
	}
	
}

function addLocationFeedback(locationId, fade) {
	$('myLocation' + locationId).show(); 
	$('notMyLocation'+ locationId).hide();	
	if(fade) {
		var div = $('fadeLocation' + locationId);
		new Effect.Fade(div);
	}
	
}

var locEmbeddedContainer = null;
var evEmbeddedContainer = null;
function getSimilarEvents(container) {
	var locationId = container.getElementById('createEvent_location').getNextSibling().getValue();

	var title = container.getElementById('createEvent_title').getValue();
//	if(title != '' && locationId != '') {

	if(title != '') {
		dooyago.xmlrpc.executeAsync('Event.hasSimilar', function(ret, e) {
			if(e) {
				
			} else {
				if(ret != '' && ret != null) {
					evEmbeddedContainer = null;
					//alert(escape(title));
					showForm('/forms.Main/ConfirmEventSimilar_form.htmli', 'ConfirmEventSimilar','' + escape(title) + '/' + locationId + '' , 'forEvent','','source2');												
				}
			}
		}, locationId, title);
	}
}

function getSimilarLocations(name, entity) {
	if(name != '') {
		dooyago.xmlrpc.executeAsync('Location.hasSimilar', function(ret, e) {
			if(e) {
				alert(e);
			} else {
				if(ret != '' && ret != null) {
					locEmbeddedContainer = null;
					showForm('/forms.Main/' + entity + '_form.htmli', entity ,name, 'forLocation','','source2');							
				}
			}
		}, name);		
	}
}



function escapeSearch(url, search) {
	window.location.href = url + encodeURIComponent(search); //escape
}

function openLocation(id) {
		dooyago.xmlrpc.executeAsync('Location.getLink', function(ret, e) {
			if(e) {
				alert(e);
			} else {
				if(ret != '') {
					window.open(ret);
				}
			}
		}, id);		

}	

function openEvent(id) {
		dooyago.xmlrpc.executeAsync('Event.getLink', function(ret, e) {
			if(e) {
				alert(e);
			} else {
				if(ret != '') {
					window.open(ret);
				}
			}
		}, id);		

}	

function closeWindow(me) {
	me.getContainer().close();
}

function confirmLocationSimilar(me) {
	confirmSimilarMail(me, 'Location', locEmbeddedContainer);
}

function confirmEventSimilar(me) {
	confirmSimilarMail(me, 'Event', evEmbeddedContainer);
}


function confirmSimilarMail(me, entity, embeddedContainer) {

	if(!embeddedContainer) {
		return;
	}
	
	var repText = entity;
	if(entity == 'Location') {
		repText = 'Spot';
	}
	
	var ids = jrapid.getIds(embeddedContainer);

	if(ids == null || ids.length == 0) {
		var message = dooyago.similarTextM[0].replace(/__entity__/g, repText);
		alert(message);
		return;
		
	}
	
	unlock('' + ids + '', entity, true);
		
}

function unlock(ids, entity, closeSources, name, fakeUser, isPromoter, userId) {
	var repText = entity;
	var message = 'M\u00F6chtest Du den Event ' + name + ' freigeschaltet bekommen?';
	if(entity == 'Location') {
		repText = 'Spot';
		message = 'M\u00F6chtest Du den Spot' + name + ' freigeschaltet bekommen?';
	}
	
	
	if(confirm(message)) {
	
		if(fakeUser && isPromoter) {
			if(entity == 'Location') {
				dooyago.xmlrpc.executeAsync('LocationServices.assignToPromoter', function(ret, e) {
					if(e) {
						alert(e);
					} else {
					alert('Der Spot ist ab sofort auf Dich freigeschaltet.\r\n' +
					'Du kannst die Infos zu Deinem Spot nun nach Belieben anpassen.');
					 } }, '' + ids + '', '' + userId + '');
			}
			
			if(entity == 'Event') {
				dooyago.xmlrpc.executeAsync('EventServices.assignToPromoter', function(ret, e) {
					if(e) {
						alert(e);
					} else {
					alert('Der Event ist ab sofort auf Dich freigeschaltet.\r\n' +
					'Du kannst die Infos zu Deinem Event nun nach Belieben anpassen.');
					 } }, '' + ids + '', '' + userId + '');
			}
		}		
	
		dooyago.xmlrpc.executeAsync('Email.sendSimilarMail', function(ret, e) {
			if(e) {
				alert(e);
			} else {
				if(!fakeUser || !isPromoter) {
					var message = dooyago.similarTextM[1].replace(/__entity__/g, repText);
					alert(message);
				}
				if(closeSources) {
					var source = application.wrapNode($('source'));				
					var source2 = application.wrapNode($('source2'));				
					var source3 = application.wrapNode($('source3'));
					source3.close();
					source2.close();
					source.close();
				}
			}
			if(fakeUser && isPromoter) { 
				window.location.reload();
			}
		}, '' + ids + '', entity, isPromoter, fakeUser);	
	}		

};

function unlock_user_organizer(ids, entity, closeSources) {
	var repText = entity;

	dooyago.xmlrpc.executeAsync('Email.sendUnlockMail', function(ret, e) {
		if(e) {
			alert(e);
		} else {
			var message = 'Vielen Dank f\u00FCr Deinen Hinweis!\nDas wergehthin-Team pr\u00FCft nun Deine Anfrage und wird Dich informieren, sobald Du als Veranstalter freigeschaltet wurdest.';
			alert(message);
			if(closeSources) {
				var source = application.wrapNode($('source'));				
				var source2 = application.wrapNode($('source2'));				
				var source3 = application.wrapNode($('source3'));
				source3.close();
				source2.close();
				source.close();
			}
		}
	}, '' + ids + '', entity);		
}

function openConfirmation(actionId) {
	 var confirm = false;
	 showForm('/forms.Main/ConfirmationPopUp_form.htmli?lang=de', 'ConfirmationPopUp','' + actionId + '', 'actionId');
	 return confirm;
}

function setPlatform(me) {
	var platform = me.options[me.selectedIndex].value;
	window.location = '/' + platform + '/home.jsp';
	
	/*dooyago.xmlrpc.executeAsync('DooyagoUtil.changePlatform', function(ret, e) {
		if(e) {
			alert(e);
		} else {
			window.location.reload();		
		}
	}, platform);				
	
	return platform;*/
}

JRapid.SERVER_PATH = '/xml/';

JRapid.prototype.fileChange = function(me, entity, width, height) {
    width = width ? width : '';
    height = height ? height : '';
    var win = me.getContainer().getElementById('uploader'); 
    win.open(); 
    win.center(); 
    jrapid.uploadinput = me.outerNode.previousSibling.previousSibling;
    // window.frames['iframe' + entity].location = '../jrapid-runtime/upload.jsp?entity=' + entity + '&width=' + width + '&height=' + height;
    
    me.getContainer().getElementById('uploader').getFirstElementChild().setSrc('/jrapid-runtime/upload.jsp?entity=' + entity + '&width=' + width + '&height=' + height + '&rand=' + new Date().getTime());
}

function onupload(file) {
    var input = jrapid.uploadinput;
    input.value = file;
        
    if (input.nextSibling.tagName.toLowerCase() == 'img') {
        input.nextSibling.src = '/upload/' + file;
    } else {
        input.nextSibling.href = '/upload/' + file;
        input.nextSibling.innerHTML = file.substring(file.indexOf('!')+1);
    }
    
    var wrapped = application.wrapNode(input);
    //wrapped.sync();
    wrapped.dispatchChangeEvent();
    wrapped.getContainer().getElementById('uploader').close();
}

function displayCategories() {
	$('moreCategoriesDiv').show();
	$('mehrCats').hide();
	return false;
};

function displaySubCategories() {
	$('moreSubCategoriesDiv').show();
	$('mehrSubCats').hide();
	return false;
};