
/*
 * jQuery Form Plugin
 * version: 2.38 (13-FEB-2010)
 */
(function($){
	$.fn.ajaxSubmit=function(options){
		if(!this.length){
			log("ajaxSubmit: skipping submit process - no element selected");
			return this;
		}
		if(typeof options=="function"){
			options={
				success:options
			};

	}
	var url=$.trim(this.attr("action"));
	if(url){
		url=(url.match(/^([^#]+)/)||[])[1];
	}
	url=url||window.location.href||"";
	options=$.extend({
		url:url,
		type:this.attr("method")||"GET",
		iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank"
		},options||{});
	var veto={};

	this.trigger("form-pre-serialize",[this,options,veto]);
	if(veto.veto){
		log("ajaxSubmit: submit vetoed via form-pre-serialize trigger");
		return this;
	}
	if(options.beforeSerialize&&options.beforeSerialize(this,options)===false){
		log("ajaxSubmit: submit aborted via beforeSerialize callback");
		return this;
	}
	var a=this.formToArray(options.semantic);
	if(options.data){
		options.extraData=options.data;
		for(var n in options.data){
			if(options.data[n] instanceof Array){
				for(var k in options.data[n]){
					a.push({
						name:n,
						value:options.data[n][k]
						});
				}
				}else{
			a.push({
				name:n,
				value:options.data[n]
				});
		}
		}
		}
	if(options.beforeSubmit&&options.beforeSubmit(a,this,options)===false){
	log("ajaxSubmit: submit aborted via beforeSubmit callback");
	return this;
}
this.trigger("form-submit-validate",[a,this,options,veto]);
if(veto.veto){
	log("ajaxSubmit: submit vetoed via form-submit-validate trigger");
	return this;
}
var q=$.param(a);
if(options.type.toUpperCase()=="GET"){
	options.url+=(options.url.indexOf("?")>=0?"&":"?")+q;
	options.data=null;
}else{
	options.data=q;
}
var $form=this,callbacks=[];
if(options.resetForm){
	callbacks.push(function(){
		$form.resetForm();
	});
}
if(options.clearForm){
	callbacks.push(function(){
		$form.clearForm();
	});
}
if(!options.dataType&&options.target){
	var oldSuccess=options.success||function(){};

	callbacks.push(function(data){
		$(options.target).html(data).each(oldSuccess,arguments);
	});
}else{
	if(options.success){
		callbacks.push(options.success);
	}
}
options.success=function(data,status,xhr){
	for(var i=0,max=callbacks.length;i<max;i++){
		callbacks[i].apply(options,[data,status,xhr||$form,$form]);
	}
	};

var files=$("input:file",this).fieldValue();
var found=false;
for(var j=0;j<files.length;j++){
	if(files[j]){
		found=true;
	}
}
var multipart=false;
if((files.length&&options.iframe!==false)||options.iframe||found||multipart){
	if(options.closeKeepAlive){
		$.get(options.closeKeepAlive,fileUpload);
	}else{
		fileUpload();
	}
}else{
	$.ajax(options);
}
this.trigger("form-submit-notify",[this,options]);
return this;
function fileUpload(){
	var form=$form[0];
	if($(":input[name=submit]",form).length){
		alert('Error: Form elements must not be named "submit".');
		return;
	}
	var opts=$.extend({},$.ajaxSettings,options);
	var s=$.extend(true,{},$.extend(true,{},$.ajaxSettings),opts);
	var id="jqFormIO"+(new Date().getTime());
	var $io=$('<iframe id="'+id+'" name="'+id+'" src="'+opts.iframeSrc+'" />');
	var io=$io[0];
	$io.css({
		position:"absolute",
		top:"-1000px",
		left:"-1000px"
	});
	var xhr={
		aborted:0,
		responseText:null,
		responseXML:null,
		status:0,
		statusText:"n/a",
		getAllResponseHeaders:function(){},
		getResponseHeader:function(){},
		setRequestHeader:function(){},
		abort:function(){
			this.aborted=1;
			$io.attr("src",opts.iframeSrc);
		}
	};

var g=opts.global;
if(g&&!$.active++){
	$.event.trigger("ajaxStart");
}
if(g){
	$.event.trigger("ajaxSend",[xhr,opts]);
}
if(s.beforeSend&&s.beforeSend(xhr,s)===false){
	s.global&&$.active--;
	return;
}
if(xhr.aborted){
	return;
}
var cbInvoked=0;
var timedOut=0;
var sub=form.clk;
if(sub){
	var n=sub.name;
	if(n&&!sub.disabled){
		opts.extraData=opts.extraData||{};

		opts.extraData[n]=sub.value;
		if(sub.type=="image"){
			opts.extraData[name+".x"]=form.clk_x;
			opts.extraData[name+".y"]=form.clk_y;
		}
	}
}
function doSubmit(){
	var t=$form.attr("target"),a=$form.attr("action");
	form.setAttribute("target",id);
	if(form.getAttribute("method")!="POST"){
		form.setAttribute("method","POST");
	}
	if(form.getAttribute("action")!=opts.url){
		form.setAttribute("action",opts.url);
	}
	if(!opts.skipEncodingOverride){
		$form.attr({
			encoding:"multipart/form-data",
			enctype:"multipart/form-data"
		});
	}
	if(opts.timeout){
		setTimeout(function(){
			timedOut=true;
			cb();
		},opts.timeout);
	}
	var extraInputs=[];
	try{
		if(opts.extraData){
			for(var n in opts.extraData){
				extraInputs.push($('<input type="hidden" name="'+n+'" value="'+opts.extraData[n]+'" />').appendTo(form)[0]);
			}
			}
			$io.appendTo("body");
	io.attachEvent?io.attachEvent("onload",cb):io.addEventListener("load",cb,false);
	form.submit();
}finally{
	form.setAttribute("action",a);
	t?form.setAttribute("target",t):$form.removeAttr("target");
	$(extraInputs).remove();
}
}
if(opts.forceSync){
	doSubmit();
}else{
	setTimeout(doSubmit,10);
}
var domCheckCount=50;
function cb(){
	if(cbInvoked++){
		return;
	}
	io.detachEvent?io.detachEvent("onload",cb):io.removeEventListener("load",cb,false);
	var ok=true;
	try{
		if(timedOut){
			throw"timeout";
		}
		var data,doc;
		doc=io.contentWindow?io.contentWindow.document:io.contentDocument?io.contentDocument:io.document;
		var isXml=opts.dataType=="xml"||doc.XMLDocument||$.isXMLDoc(doc);
		log("isXml="+isXml);
		if(!isXml&&(doc.body==null||doc.body.innerHTML=="")){
			if(--domCheckCount){
				cbInvoked=0;
				setTimeout(cb,100);
				return;
			}
			log("Could not access iframe DOM after 50 tries.");
			return;
		}
		xhr.responseText=doc.body?doc.body.innerHTML:null;
		xhr.responseXML=doc.XMLDocument?doc.XMLDocument:doc;
		xhr.getResponseHeader=function(header){
			var headers={
				"content-type":opts.dataType
				};

			return headers[header];
		};

		if(opts.dataType=="json"||opts.dataType=="script"){
			var ta=doc.getElementsByTagName("textarea")[0];
			if(ta){
				xhr.responseText=ta.value;
			}else{
				var pre=doc.getElementsByTagName("pre")[0];
				if(pre){
					xhr.responseText=pre.innerHTML;
				}
			}
		}else{
	if(opts.dataType=="xml"&&!xhr.responseXML&&xhr.responseText!=null){
		xhr.responseXML=toXml(xhr.responseText);
	}
}
data=$.httpData(xhr,opts.dataType);
}catch(e){
	ok=false;
	$.handleError(opts,xhr,"error",e);
}
if(ok){
	opts.success(data,"success");
	if(g){
		$.event.trigger("ajaxSuccess",[xhr,opts]);
	}
}
if(g){
	$.event.trigger("ajaxComplete",[xhr,opts]);
}
if(g&&!--$.active){
	$.event.trigger("ajaxStop");
}
if(opts.complete){
	opts.complete(xhr,ok?"success":"error");
}
setTimeout(function(){
	$io.remove();
	xhr.responseXML=null;
},100);
}
function toXml(s,doc){
	if(window.ActiveXObject){
		doc=new ActiveXObject("Microsoft.XMLDOM");
		doc.async="false";
		doc.loadXML(s);
	}else{
		doc=(new DOMParser()).parseFromString(s,"text/xml");
	}
	return(doc&&doc.documentElement&&doc.documentElement.tagName!="parsererror")?doc:null;
}
}
};

$.fn.ajaxForm=function(options){
	return this.ajaxFormUnbind().bind("submit.form-plugin",function(){
		$(this).ajaxSubmit(options);
		return false;
	}).bind("click.form-plugin",function(e){
		var target=e.target;
		var $el=$(target);
		if(!($el.is(":submit,input:image"))){
			var t=$el.closest(":submit");
			if(t.length==0){
				return;
			}
			target=t[0];
		}
		var form=this;
		form.clk=target;
		if(target.type=="image"){
			if(e.offsetX!=undefined){
				form.clk_x=e.offsetX;
				form.clk_y=e.offsetY;
			}else{
				if(typeof $.fn.offset=="function"){
					var offset=$el.offset();
					form.clk_x=e.pageX-offset.left;
					form.clk_y=e.pageY-offset.top;
				}else{
					form.clk_x=e.pageX-target.offsetLeft;
					form.clk_y=e.pageY-target.offsetTop;
				}
			}
		}
	setTimeout(function(){
		form.clk=form.clk_x=form.clk_y=null;
	},500);
});
};

$.fn.ajaxFormUnbind=function(){
	return this.unbind("submit.form-plugin click.form-plugin");
};

$.fn.formToArray=function(semantic){
	var a=[];
	if(this.length==0){
		return a;
	}
	var form=this[0];
	var els=semantic?form.getElementsByTagName("*"):form.elements;
	if(!els){
		return a;
	}
	for(var i=0,max=els.length;i<max;i++){
		var el=els[i];
		var n=el.name;
		if(!n){
			continue;
		}
		if(semantic&&form.clk&&el.type=="image"){
			if(!el.disabled&&form.clk==el){
				a.push({
					name:n,
					value:$(el).val()
					});
				a.push({
					name:n+".x",
					value:form.clk_x
					},{
					name:n+".y",
					value:form.clk_y
					});
			}
			continue;
		}
		var v=$.fieldValue(el,true);
		if(v&&v.constructor==Array){
			for(var j=0,jmax=v.length;j<jmax;j++){
				a.push({
					name:n,
					value:v[j]
					});
			}
			}else{
		if(v!==null&&typeof v!="undefined"){
			a.push({
				name:n,
				value:v
			});
		}
	}
	}
if(!semantic&&form.clk){
	var $input=$(form.clk),input=$input[0],n=input.name;
	if(n&&!input.disabled&&input.type=="image"){
		a.push({
			name:n,
			value:$input.val()
			});
		a.push({
			name:n+".x",
			value:form.clk_x
			},{
			name:n+".y",
			value:form.clk_y
			});
	}
}
return a;
};

$.fn.formSerialize=function(semantic){
	return $.param(this.formToArray(semantic));
};

$.fn.fieldSerialize=function(successful){
	var a=[];
	this.each(function(){
		var n=this.name;
		if(!n){
			return;
		}
		var v=$.fieldValue(this,successful);
		if(v&&v.constructor==Array){
			for(var i=0,max=v.length;i<max;i++){
				a.push({
					name:n,
					value:v[i]
					});
			}
			}else{
		if(v!==null&&typeof v!="undefined"){
			a.push({
				name:this.name,
				value:v
			});
		}
	}
	});
return $.param(a);
};

$.fn.fieldValue=function(successful){
	for(var val=[],i=0,max=this.length;i<max;i++){
		var el=this[i];
		var v=$.fieldValue(el,successful);
		if(v===null||typeof v=="undefined"||(v.constructor==Array&&!v.length)){
			continue;
		}
		v.constructor==Array?$.merge(val,v):val.push(v);
	}
	return val;
};

$.fieldValue=function(el,successful){
	var n=el.name,t=el.type,tag=el.tagName.toLowerCase();
	if(typeof successful=="undefined"){
		successful=true;
	}
	if(successful&&(!n||el.disabled||t=="reset"||t=="button"||(t=="checkbox"||t=="radio")&&!el.checked||(t=="submit"||t=="image")&&el.form&&el.form.clk!=el||tag=="select"&&el.selectedIndex==-1)){
		return null;
	}
	if(tag=="select"){
		var index=el.selectedIndex;
		if(index<0){
			return null;
		}
		var a=[],ops=el.options;
		var one=(t=="select-one");
		var max=(one?index+1:ops.length);
		for(var i=(one?index:0);i<max;i++){
			var op=ops[i];
			if(op.selected){
				var v=op.value;
				if(!v){
					v=(op.attributes&&op.attributes.value&&!(op.attributes.value.specified))?op.text:op.value;
				}
				if(one){
					return v;
				}
				a.push(v);
			}
		}
		return a;
}
return el.value;
};

$.fn.clearForm=function(){
	return this.each(function(){
		$("input,select,textarea",this).clearFields();
	});
};

$.fn.clearFields=$.fn.clearInputs=function(){
	return this.each(function(){
		var t=this.type,tag=this.tagName.toLowerCase();
		if(t=="text"||t=="password"||tag=="textarea"){
			this.value="";
		}else{
			if(t=="checkbox"||t=="radio"){
				this.checked=false;
			}else{
				if(tag=="select"){
					this.selectedIndex=-1;
				}
			}
		}
	});
};

$.fn.resetForm=function(){
	return this.each(function(){
		if(typeof this.reset=="function"||(typeof this.reset=="object"&&!this.reset.nodeType)){
			this.reset();
		}
	});
};

$.fn.enable=function(b){
	if(b==undefined){
		b=true;
	}
	return this.each(function(){
		this.disabled=!b;
	});
};

$.fn.selected=function(select){
	if(select==undefined){
		select=true;
	}
	return this.each(function(){
		var t=this.type;
		if(t=="checkbox"||t=="radio"){
			this.checked=select;
		}else{
			if(this.tagName.toLowerCase()=="option"){
				var $sel=$(this).parent("select");
				if(select&&$sel[0]&&$sel[0].type=="select-one"){
					$sel.find("option").selected(false);
				}
				this.selected=select;
			}
		}
	});
};

function log(){
	if($.fn.ajaxSubmit.debug&&window.console&&window.console.log){
		window.console.log("[jquery.form] "+Array.prototype.join.call(arguments,""));
	}
}
})(jQuery);


/*
 * loca.li custom js methods
 */
var Locali = function(){
	return {};
}();

Locali.segmentOfActiveImage = null;

Locali.loadFriendsBox = function(){
	$.ajax({
		method: "get",
		url: "/ajax/myfriends",
		success: function(html){
			$("#my-friends-box").html(html);
		}
	});
};

Locali.commentsRead = false;

Locali.initNotificationMenu = function(){
	// clicked trigger
	$("ul.notification-menu li span:not('.notification-numbers')").click(function(event) {
		// hide all activated elements
		$("ul.notification-submenu").not(this).hide();
		$("ul.notification-menu li span").not(this).removeClass('active');
		// remove number of opened item
		$(this).children('.notification-numbers').html('');

		event.stopPropagation();

		// get subnav
		var curSubmenu = $(this).parent().find("ul.notification-submenu");
		// show
		$(curSubmenu).slideDown('fast').show();
		$(this).addClass('active');

		// get parent element position
		var position = $('ul.notification-menu').position();
		$(curSubmenu).css('left', position.left);

		// remove last li border
		$(curSubmenu + 'li:last').css('border', 'none');

		if ($(this).attr('id') == 'notification-menu-comment' && !Locali.commentsRead) {
			var ids = [];

			$('input[name^="comment-ids"]').each(function(i, el) {
				ids.push(el.value);
			});

			$.post('/ajax/read-comments', {
				ids: ids
			}, function() {
				Locali.commentsRead = true;
			});
		}
	});

	// outside click closes menu
	$('body').click(function() {
		$("ul.notification-submenu").fadeOut('fast', function() {
			$("ul.notification-menu li span").removeClass('active');
		});
	});
};

Locali.initCommentForms = function () {
	$('.activity-comment-form .btn_send').live('click', function(event) {
		$(event.target).parents('form').ajaxSubmit({
			success: function () {
				Locali.reloadActivity();
			},
			dataType: 'json'
		});
	});
};

Locali.showInlineCommentForm = function(){
	$('.open-comment').live('click', function() {
		// get next inline-comment form and show it
		var nextCommentForm = $(this).nextAll('.comment-inline-form:lt(1)');
		$(nextCommentForm).slideDown('fast');
	});
};


Locali.addFriend = function(username){
	$.ajax({
		method: 'get',
		url: '/userprofile/addfriend/username/' + username,
		success: function(){
			document.location.reload();
		}
	});
};

Locali.newMessage = function(user_id) {
	$.ajax({
		method: "get",
		url: "/newmessage/index/receiver/"+user_id,
		success: function(html){
			$("#modalpopup").html(html);
			$('#modalpopup').center();
			loadPopup();
		}
	});
};

// toggle class and therefore image, when twitter icon is clicked
Locali.toggleTwitterControlIcon = function(){
	$('input[name="should_twitter"]').attr('value', 'on');
	
	$('#twitter-control').click(function() {
		$(this).toggleClass('not-post-on-twitter post-on-twitter');
	});

	// and change the title
	$('#twitter-control').toggle(function() {
		$('input[name="should_twitter"]').attr('value', 'off');
	}, function() {
		$('input[name="should_twitter"]').attr('value', 'on');
	});
};

//toggle class and therefore image, when Facebook icon is clicked
Locali.toggleFacebookControlIcon = function(){
	$('input[name="should_facebook"]').attr('value', 'on');
	
	$('#facebook-control').click(function() {
		$(this).toggleClass('not-post-on-facebook post-on-facebook');
	});

	// and change the title
	$('#facebook-control').toggle(function() {
		$('input[name="should_facebook"]').attr('value', 'off');
	}, function() {
		$('input[name="should_facebook"]').attr('value', 'on');
	});
};

// toggle active video in videomap. only one video can be activated at the same time
Locali.toggleVideoMapVideoActiveState = function(){
	$('#videomap img').click(function() {
		$('#videomap img').not(this).removeClass('active');

		if($(this).hasClass('active')) {
			$(this).removeClass('active');
			$('input[name="youtube-video-id"]').attr('value', '');
		} else {
			$(this).addClass('active');
			var currentVideoId = $(this).attr('rel');
			$('input[name="youtube-video-id"]').attr('value', currentVideoId);
		}
	});
};

// show horizontal pagebrowsers, when there are more than 7 videos
Locali.toggleShowHorizontalPageBrowser= function(){
	var intNumberOfVideos = $('#videomap img').size();
	if(intNumberOfVideos == 0) {
		$('#youtube-list').hide();
	}
};

//if in editmode, every inputfield and textarea content will be #000
Locali.prepareInputForInfoText= function(){
	if(!$(this).hasClass('fc')) {
		$('input:text, textarea').css({
			'color': '#33CCFF'
		});
	}
};

// insert dummy helptext to input and textarea, if field is empty
Locali.prepareFormValueOnFocus= function(){
	// if user clicks in input or textarea the first time, value data is written to rel
	$('textarea, input:text').focusin(function() {
		if(!$(this).hasClass('fc')) {
			if(!$(this).val().length == 0) {
				var elementValue = $(this).val();
			}
			// remove value from element
			$(this).val('');
			// temp-save value in rel
			$(this).attr('rel', elementValue);

			// prepare color
			$(this).css({
				'color': '#7B164E'
			});
		}
	});

	$('textarea, input:text').focusout(function() {
		// check if element is empty
		if($(this).val().length == 0) {
			// re-prepare color
			$(this).css({
				'color': '#33CCFF'
			});
			// rewrite value from rel
			var tempAttrRel = $(this).attr('rel');
			$(this).val(tempAttrRel);

			$(this).removeClass('fc');
		} else {
			$(this).addClass('fc');
		}
	});
};

// initialize the scrollable videolist
Locali.initializeScrollableVideoList= function(){
	// scrollable will circle in an infinite loop
	$(".scrollable").scrollable();
};

// check for active class in videolist and return the segment in which it is
Locali.getActiveElementSegmentInVideoList= function(){
	var i = 1;
	var imgPosition = 0;
	// get all images and check for active class
	$('.scrollable .items div:not([class=cloned]) img').each(function() {
		if($(this).hasClass('active')) {
			// this is the position of the active image
			imgPosition = i;
		}
		i ++;
	});
	// get the average number of images in each set
	var imagesPerSegment = $('.scrollable .items > div img').length / $('.scrollable .items > div').length;
	
	// get the exact segment in which the acitve image is
	this.segmentOfActiveImage = Math.floor(imgPosition / imagesPerSegment);

	return this.segmentOfActiveImage;
};


Locali.prepareSubmit = function() {
    var validationNotOk = 0;
    // check mandatory inputfields and return info, if the are empty
    $('input:text.validation-required, textarea.validation-required').each(function() {
        if(!$(this).hasClass('fc')) {
            validationNotOk ++;
            $(this).tooltip({
                effect: 'slide',
                offset: [0, 50],
                relative: true
            });
            var inputTooltipApi = $(this).data('tooltip');
            inputTooltipApi.show();
            $(this).click(function() {
                inputTooltipApi.hide();
            });
        } else {
            if(validationNotOk > 0){
                validationNotOk --;
            }
        }
    });

    // return true/false accordion to errors
    if(validationNotOk <= 0) {
        // remove dummytext from optional element before sending
        $('input:text:not([class=validation-required]), textarea:not([class=validation-required])').each(function() {
            if(!$(this).hasClass('fc')) {
                $(this).val('');
            }
        });
        return true;
    } else {
        return false;
    }
};

Locali.responseCreatePlace = function(response, statusText) {
};

// inserts a spinner-div after the element
Locali.insertSpinner = function(that){
	$(that).after('<div class="btn_spinner"></div>');
};


Locali.validateSearch = function(){
	/* no search with empty fields */
	var formInputQuery = $("input[name='search-query']");
	var currentFormValueWhere = formInputQuery.val();
	
	$('#form-search').submit(function() {
		// form values are empty
		if(formInputQuery.val() == '') {
			showMessageBoxError('Please enter \"where\" or \"what\"');
			return false;
		}
		// form values are too short
		if (formInputQuery.val().length < 3) {
			showMessageBoxError('Searchwords should at least have 3 characters');
			return false;
		}
		// form values are both in standard state
		if (formInputQuery.val() == currentFormValueWhere) {
			formInputQuery.val('New York');
		}
		// form value where in standard state
		if (formInputQuery.val() == currentFormValueWhere) {
			formInputQuery.val('');
		}
	});
};


var map;
function loadPopup(){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopup").fadeIn("fast");
		$("#modalpopup").fadeIn("fast");
}

function disablePopup(){  
		$("#backgroundPopup").fadeOut("fast");
		$("#modalpopup, .overlay, #exposeMask").fadeOut("fast");
}


function openPlaceDialog() {
	$.ajax({
		method: "get",
		url: "/createplacemodal",
		data: "",
		beforeSend: function(){
			$('#modalpopup').center();
			loadPopup();
		},
		success: function(html){
			$("#modalpopup").html(html);
			$('#modalpopup').center();
			loadPopup();
			$("#titleH2").html($('<div/>').html(address_gen).text());
			$("#auto_title").attr("value", $("#titleH2").html());
		}
	});
}

function openEditPlaceDialog(place) {
	if(place) {
		place = "/place/"+place;
	}
	else {
		place = "";
	}
	
	$.ajax({
		method: "get",
		url: "/createplacemodal/edit"+place ,
		data: "",
		beforeSend: function(){
			$('#modalpopup').center();
			loadPopup();
		},
		complete: function(){},
		success: function(html){
			$("#modalpopup").html(html);
			$('#modalpopup').center();
			loadPopup();
			$("#titleH2").html($('<div/>').html(address_gen).text());
			$("#auto_title").attr("value", address_gen);
		}
	});
}


function showMessageBoxOk(text) {
	var div = $('<div class="modalbox" id="feedback"><div class="modalbox-inner"><div class="ok" onclick=\"disablePopup()\">'+text+'</div></div></div>');
	
	$("#modalpopup").html(div); //show the html inside .content div
	$('#modalpopup').center();
	loadPopup();
	
	setTimeout(function(){
		disablePopup();
	}, 2000);
}

function showMessageBoxError(text) {
	var div = $('<div class="modalbox" id="feedback"><div class="modalbox-inner"><a href="javascript:disablePopup()" class="close"></a><div class="clear"></div><div class="error">'+text+'</div></div></div>');
	
	$("#modalpopup").html(div); //show the html inside .content div
	$('#modalpopup').center();
	loadPopup();
	
	$("#backgroundPopup").click(function(){
		disablePopup();
	});
	
	setTimeout(function(){
		disablePopup();
	}, 2000);
}

/* Scroll window to selector */
Locali.goToByScroll = function(selector) {
	$('html,body').animate(
	{
		scrollTop: $(selector).offset().top
		},
	'fast'
	);
};


Locali.initActivityStream = function(iterator){
	$.ajax({
		method: "get",
		url: "/ajax/newplaces/offset/"+iterator,
		success: function(html){
			if(html.length > 0) {
				$("#newPlacesBox > .content").append(html);
			}
			Locali.moveActivityStream(iterator, 0);
		}
	});
};

Locali.moveActivityStream = function(iterator, currentruns){
	if(currentruns == 16) {
		iterator += 1;
		Locali.initActivityStream(iterator);
	} else {
		setTimeout(function() {
			$("#newPlacesBox > .content").children(':first').fadeOut('slow', function() {
				$(this).remove();
			});
			currentruns += 1;
			Locali.moveActivityStream(iterator, currentruns);
		}, 5000);
	}
};

function showDetailImage(imageUrl) {
	$("#modalpopup").load(imageUrl);
}

// rate places internally
Locali.ratePlace = function(field, id, likeit) {   
	$.post('/ajax/rateplace/' + field + '/' + id + '/likeit/' + likeit);
};


function createPlaceBubble(point, imageUrl, subtitle, tags, id) {
	if(imageUrl.substring(0, 4) != "http") {
		imageUrl = host+imageUrl;
	}
	//alert(imageUrl);
	// Create a lettered icon for this point using our icon class
	//var letter = String.fromCharCode("A".charCodeAt(0) + index);
	var baseIcon = new GIcon();
	//baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(33, 33);
	baseIcon.shadowSize = new GSize(0, 0);
	baseIcon.iconAnchor = new GPoint(0, 25);
	baseIcon.infoWindowAnchor = new GPoint(164, 8);
	var myIcon = new GIcon(baseIcon);
	myIcon.iconSize = new GSize(33, 33);
	myIcon.image = imageUrl;
	
	// Set up our GMarkerOptions object
	markerOptions = {
		icon:myIcon
	};
	var marker = new GMarker(point, markerOptions);

	GEvent.addListener(marker, "click", function() {
		if(tags.length > 50) {
			tags = tags.substr(0,80)+ "...";
		}
		marker.openExtInfoWindow(map, "simple_example_window", "<div style=\"width: 290px; height: 62px; cursor: pointer;\" onclick=\"window.location = '/place/" + id + "'\"><img src=\""+imageUrl+"\" style=\"float: left; padding-right: 5px;\" width=\"45\" height=\"45\"/><h4>"+subtitle+"</h4><p>"+tags+"</p></div>", {
			beakOffset: 3
		});
	});
	return marker;
}

//open register box on certrain clicks
Locali.initOpenRegisterModal = function(){
	$('#registerAdBox, .action-register').live('click', function(){
		$.ajax({
			method: 'get',
			url: '/register',
			data: '',
			beforeSend: function(){},
			complete: function(){},
			success: function(html){
				$('#modalpopup').html(html);
				$('#modalpopup').center();
				loadPopup();
				$('#modalpopup #firstname').focus();
			}
		});
	});
};


Locali.initDeleteItems = function(){
	
    $('.delete-item-trigger[rel]').overlay({
        mask: {
            color:		'#000000',
            loadSpeed:	200,
            opacity:	0.8
        },
        closeOnClick: true,
        onBeforeLoad: function() {
            $('.overlay').width(325);
            // get box contents
            $.ajax({
                method: 'get',
                url: '/activities/deleteconfirmdialog',
                success: function(html){
                    $('.overlay').append(html);
                }
            });
			
            var a = this.getTrigger();
            var activity = a.attr('id').replace('activity-', '');
			
            $('.btn_yes').live('click', function(event) {
                event.preventDefault();
                $.post('myprofile/delete-activity-item', {
                    id: activity
                }, function () {
                    Locali.reloadActivity();
                    a.data('overlay').close();
                });
            });
			
            $('.btn_no').live('click', function(event) {
                event.preventDefault();
                a.data('overlay').close();
            });
        },
        onClose: function() {
            $('.confirmdialog').remove();
        }
    });
};

Locali.initDeleteProfile = function(){
	
    $('#delete-profile-trigger[rel]').overlay({
        mask: {
            color:		'#000000',
            loadSpeed:	200,
            opacity:	0.8
        },
        closeOnClick: true,
        onBeforeLoad: function() {
            // get box contents
            $('.overlay').width(325);
            $.ajax({
                method: 'get',
                url: '/settings/deleteconfirmdialog',
                success: function(html){
                    $('.overlay').append(html);
                }
            });
            var a = this.getTrigger();
            $('.btn_yes').live('click', function(event) {
                event.preventDefault();
                $.post('/settings/delete-profile', function () {
                    a.data('overlay').close();
                });
            });
			
            $('.btn_no').live('click', function(event) {
                event.preventDefault();
                a.data('overlay').close();
            });
        },
        onClose: function() {
            $('.confirmdialog').remove();
        }
    });
};


Locali.deleteFriendship = function(friendId) {	
    $('#delete-friendship-trigger[rel]').overlay({
        mask: {
            color:		'#000000',
            loadSpeed:	200,
            opacity:	0.8
        },
        load: true,
        closeOnClick: true,
        onBeforeLoad: function() {
            // get box contents
            $('.overlay').width(325);
            $.ajax({
                method: 'get',
                url: '/userprofile/deleteconfirmdialog',
                success: function(html){
                    $('.overlay').append(html);
                }
            });
            var a = this.getTrigger();
            $('.btn_yes').live('click', function(event) {
                event.preventDefault();
                $.get('/friends/deletefriendship/friend/' + friendId, function(data) {
                    a.data('overlay').close();
                    document.location.reload();
                });
            });
			
            $('.btn_no').live('click', function(event) {
                event.preventDefault();
                a.data('overlay').close();
            });
        },
        onClose: function() {
            $('.confirmdialog').remove();
        }
    });
};

function spotplace(title, lat, lng) {
    latitude_gen = lat;
    longitude_gen = lng;

    $.ajax({
        method: "get",
        url: "/createplacemodal",
        data: "",
        beforeSend: function(){
            $('#modalpopup').center();
            loadPopup();
        },
        complete: function(){},
        success: function(html){
            $("#modalpopup").html(html);
            $('#modalpopup').center();
            loadPopup();
            $("#titleH2").html($('<div/>').html(title).text());
            $("#auto_title").attr("value", $("#titleH2").html());
        }
    });
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
};


/* center element hor/ver on screen */
jQuery.fn.center = function () {
	this.css('position','absolute');
	// sometimes top is negative. set to 0 if negative
	var cssValueTop = ( $(window).height() - this.outerHeight() ) / 2+$(window).scrollTop();
	if(cssValueTop < 0) {
		cssValueTop = 0;
	}
	this.css('top', cssValueTop + 'px');
	this.css('left', ( $(window).width() - this.outerWidth() ) / 2+$(window).scrollLeft() + 'px');
	return this;
};



/* Imagegallery */

//overlay for image gallery
Locali.initImageGallery = function(place){	
    // initialize overlay
    $('a.singleplace-image-multi[rel]').overlay({
        mask: {
            color: '#000',
            loadSpeed: 300,
            opacity: 0.7
        },
        closeOnClick: true,
        fixed: false,
        onBeforeLoad: function(event) {

            $('.overlay').width(845);
            // get current href value
            var target = this.getTrigger().attr('href');
            // get data from imagegallery view
            $.ajax({
                method: 'get',
                url: '/ajax/picturegallery/place/' + place ,
                data: '',
                success: function(data) {
                    $('.overlay .close').after(data);
					
                    // if there is a target open that target in picturegallery, otherwise open the first element
                    if(target.length > 0) {
                        // videoItem matches only if there is a video target
                        var videoItem = $('#gallery-imagemap img[src="' + target + '"]').parent();
                        if(videoItem.length > 0) {
                            Locali.galleryLoadVideo(videoItem);
                        }
                        // this is an image target
                        var imageItem = $('#gallery-imagemap a[rel="' + target + '"]');
                        if(imageItem.length > 0) {
                            Locali.displayTargetInGallery(imageItem);
                        }
                    } else {
                        Locali.displayFirstImageInGallery();
                    }
                }
            });
        },
        // execute, when overlay is opened
        onLoad: function(event) {
            Locali.initializeClickToSingleView();
        },
        // empty overlay
        onClose: function() {
            $('.overlay .modalbox-inner').remove();
        }
    });
};

//load first image to gallery
Locali.displayFirstImageInGallery = function(){
	var firstLiASrc = $('#gallery-imagemap ul li:first a').attr('rel');
	$('#gallery-singleimage').html('<img src=' + firstLiASrc + ' alt="" />');
};
//load target image to gallery
Locali.displayTargetInGallery = function(target){
	var targetSrc = $(target).attr('rel');
	$('#gallery-singleimage').html('<img src=' + targetSrc + ' alt="" />');
};
//load YoutubeVideo into imagegallery
Locali.galleryLoadVideo = function(that){
	var videoSource = $(that).attr('rel');
	$('#gallery-singleimage').html('<object width="500" height="397"><param name="movie" value="' + videoSource + '?rel=0&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="' + videoSource + '?rel=0&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="500" height="397"></embed></object>');
};

//slide down file uploader, when icon is clicked
Locali.initializeClickToSingleView = function(){
    // swap image to singleView on hover
    $("#gallery-imagemap ul li a").click(function() {
        if($(this).hasClass('video')) {
            Locali.galleryLoadVideo(this);
        } else {
            var imageSource = $(this).attr('rel');
            $('#gallery-singleimage').html('<img src=' + imageSource + ' alt="" />');
        }
    });
};


Locali.initImageOverview = function(){
    $('a.singleplace-image-multi[rel]').overlay({
        mask: {
            color: '#000',
            loadSpeed: 300,
            opacity: 0.7
        },
        closeOnClick: true,
        fixed: false,
        onBeforeLoad: function() {
            // get current href value
            $('.overlay').css({
                'text-align':   'center',
                'width':        '540px'
            });

            var picture = this.getTrigger().attr('id').replace('picture-', '');
            // get data from imagegallery view
            $.get('/ajax/picture/picture_id/' + picture, function(data) {
                $('.overlay .close').after('<div class="modalbox-inner">' + data + '</div>');
            });
        },
        // empty overlay
        onClose: function() {
            $('.overlay .modalbox-inner').remove();
        }
    });
};

//show videomask Icon on every videoscreenshot
Locali.showVideoMaskIcon = function(that) {
    // timeout needed, or offset will fail when scrollbar showing up
    setTimeout(function() {
        //get position of the image
        var pos		= $(that).offset();
        var width	= $(that).width();
        var height	= $(that).height();
		
        var tooltipVideomask = '<div class="tooltip-videomask"></div>';
        // create videomask element and position it in the bottom right corner of the image
        $('body').append(
            $(tooltipVideomask).css( {
                "left": (pos.left + width - 38) + "px",
                "top": (pos.top + height - 38) + "px"
            })
            );
    }, 400);
};

Locali.initIndexSlider = function() {
    $('#index-slider .scrollable').scrollable({
        circular: true
    }).autoscroll({
        autoplay: true,
        autopause: true,
        steps: 1,
        interval: 7000
    });
};

//transform urls into links
Locali.linkifyLinks = function(selectors){
    $(selectors).each(function(){
        var that = $(this);
        var txt = that.html();
        var options = {
            callback: function(text, href) {
                if(href && text.length > 35) {
                    text = text.substring(0,35) + '...';
                }
                return href ? '<a href="' + href + '" title="' + href + '">' + text + '</a>' : text;
            }
        };
        that.html(linkify(txt, options));
    });
};

/* pageglobal document ready */
$(function() {
    Locali.initIndexSlider();
    Locali.initActivityStream(0);
    Locali.initNotificationMenu();
    // open register box on certain elements
    Locali.initOpenRegisterModal();
	
    $('#popupClose, #backgroundPopup').live('click', function() {
        disablePopup();
    });
	
    $('.addMoreLink, .btn_invitelocali').live('click', function() {
        $.ajax({
            method: "get",
            url: "/addfriendmodal/index",
            success: function(html){
                $("#modalpopup").html(html);
                $('#modalpopup').center();
                loadPopup();
                $("#modalpopup #nickname").focus();
            }
        });
    });
	
    $('#loginLink, #index-login, .open-comment-register').live('click', function(event){
        $.ajax({
            method: "get",
            url: "/loginmodal",
            success: function(html){
                $("#modalpopup").html(html);
                $('#modalpopup').center();
                loadPopup();
                $("#modalpopup #email").focus();
            }
        });
    });
});

function showAjaxLoader() {
    $('#ajax-loading').overlay({mask: {
            color: "#000",
            opacity: 0.1
        },
        closeOnClick: false,
        load: false,
        top: '35%',
        effect: 'apple'});
    $("#ajax-loading").overlay().load();
}

function hideAjaxLoader() {
    $("#ajax-loading").overlay().close();
}
