function sendFilterForm() {
	$('#sortselect2').val($('#sortselect').val());
	$('#filterForm').submit();
}

function ratingComplete(linkId, ratingElm, ratingValue, ratingStarsId) {
	$(linkId).remove();
	ratingElm.text(ratingValue);
	setRatingStarWidth(ratingStarsId, ratingValue);
}

function setRatingStarWidth(ratingStarsId, ratingValue) {
	image = $("#"+ratingStarsId+" span.front");
	image.width(ratingValue);
}

function submitSignUp() {
	if ( $('#licence').attr('checked') ) {
		$('#userForm').submit();
	} else {
		showPopUpBox();
	}
}

function hidePopUpBox(back) {
	if (back == true) {
		history.back();
		return;
	}
	$.dimScreenStop();
	$('#popup_info').fadeOut();
	
}

function deleteStory(formElm) {
	if ( confirm('Diese Story wirklich löschen?') ) {
		formElm.submit();
		return true;
	}
	return false;
}

function saveStory() {
	$('#create_form').submit();
}

function saveStoryFromPreview() {
	lala = confirm('Wollen Sie wirklich speichern? Ein späteres Ändern ist nicht mehr möglich.');
	if ( lala ) {
		$('#preview').fadeOut(0);
		$('body').append($('#popup_info'));
		$('#popup_info').fadeIn();
		$('#create_form').submit();
	}
}

function preview(link) {
	$.dimScreen(1, 0.8, function() {});
	$.post(link, $('#create_form').serialize(),
		function(data) {
			prevElm = $('#preview');
			$('body').append(prevElm);
			prevElm.html(data);
			prevElm.fadeIn();
	  	}
	);
}

function removePreview() {
	$.dimScreenStop();
	$('#preview').fadeOut();
}

function showAddressbook() {
	$.dimScreen(1, 0.8, function() {});
	$('body').append($('#addressbook'));
	$('#addressbook').fadeIn();
}

function showPasswordreminder() {
	$.dimScreen(1, 0.8, function() {});
	$('body').append($('#passwordreminder'));
	$('#popup_info').css('display', 'block');
	$('#passwordreminder-popup').fadeIn();
}

function passwordReminderSubmit() {
	var email = $("#passwordreminder_email").val();
	$.get('/user/passwordreminder/email/' + email);
	hidePopUpBox();
}

function transferReceiverList() {
	if ($('#receiver').val().length == 0) {
		$('#receiver').val($('#receiver-list').val());
	}
	else {
		$('#receiver').val($('#receiver').val() + '; ' + $('#receiver-list').val());
	}
	removeAddressbook();
}

function removeAddressbook() {
	$.dimScreenStop();
	$('#addressbook').fadeOut();
	// reset
	$('#addressbook-personal').css('display', 'table');
	$('#addressbook-all').css('display', 'none');
	$('.alluser a').html('Alle User anzeigen');
}

function switchAddressbookList() {
	if ($('#addressbook-personal').css('display') != 'none') {
		$('#addressbook-personal').css('display', 'none');
		$('#addressbook-all').css('display', 'table');
		$('.alluser a').html('Persönliches Adressbuch anzeigen');
	}
	else {
		$('#addressbook-personal').css('display', 'table');
		$('#addressbook-all').css('display', 'none');
		$('.alluser a').html('Alle User anzeigen');
	}
}

function showRegisterComplete() {
	$.dimScreen(1, 0.8, function() {
		$('body').append($('#registercomplete'));
		$('#registercomplete').fadeIn();
	});
}

function showPopUpBox() {
	$.dimScreen(1, 0.8, function() {
		$('body').append($('#popup_info'));
		$('#popup_info').fadeIn();
	});
}

function hideRegisterComplete() {
	$.dimScreenStop();
	$('#registercomplete').fadeOut();
}

var bla = true;
var hoehe = "0px";
function showHideMission(dur) {
	dur = (dur) ? dur : 500;
	if ( bla ) {
		hoehe = $('#hidden').height()+"px";
		$('#lessinfo').css('display', 'none');
		$('#moreinfo').css('display', 'block');
		
		$('#hidden').animate({height:"15px", opacity:"0"}, dur, null, function(){
			$('#hidden').css('overflow', 'hidden');
			$('#hidden').css('visibility', 'hidden');
		});
	} else {
		$('#lessinfo').css('display', 'block');
		$('#moreinfo').css('display', 'none');
		$('#hidden').css('visibility', 'visible');
		$('#hidden').animate({height:hoehe, opacity:"1"}, dur, null, function(){
			$('#hidden').css('overflow', 'visible');
			
		});
	}
	
	bla = !bla;
}

function initShowHideMission() {
	if ( $.cookie('mission') ) {
		showHideMission(500);
	} else {
		$.cookie('mission', 2);
		$('#moreinfo').css('display', 'none');
	}
}

function submitLangChange() {
	$('#langChange').submit();
}


var first = true;
var firstHeight = 0;
function setFooter() {
	if ( $(window).height() > firstHeight ) {
		if ( first ) { 
			firstheight = $('body').height(); 
			first = false;
		}
		var newHeight = $(window).height() - firstheight - 35;
		$('#spacer').height(newHeight);
	}
}

this.tooltip = function(){	
	/* CONFIG */		
		xOffset = 10;
		yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$("a.tooltip").hover(function(e){
		this.t = $(this).parent().children("div.tooltip_content")[0].innerHTML;
		$("body").append("<div id='tooltip'>"+ this.t +"</div>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		$("#tooltip").remove();
    });	
	$("div.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};

function toogleControl(id, duration, linkElm) {
	if ( linkElm == undefined ) {
		return;
	}
	$(id).slideToggle(duration, function() {
		linkElm.parentNode.className = ( $.cookie(id) == 1 ) ? 'open' : 'close';
		$.cookie(id, (( $.cookie(id) == 1 ) ? 2 : 1), { path: '/' } );
	});
}

function initControl(id) {
	if ( $.cookie(id) == 2 || $.cookie(id) == null ) {
		$(id).slideUp(0);
		var elm = $(id).get(0);
		if ( elm != undefined) {
			elm.parentNode.childNodes[3].className = 'open';
		}
	}
}

// starting the script on page load
$(document).ready(function() {
	tooltip();
	setFooter();
	initShowHideMission();
	
	$('#user').focus(function(){
		if ($(this).val() == 'Username') {
			$(this).val('');
		}
	});
	$('#user').blur(function(){
		if ($(this).val() == '') {
			$(this).val('Username');
		}
	});
	
	$('#pw').focus(function(){
		if ($(this).val() == 'Passwort') {
			$(this).val('');
		}
	});
	$('pwsearchterm').blur(function(){
		if ($(this).val() == '') {
			$(this).val('Passwort');
		}
	});
	
	$('#searchterm').focus(function(){
		if ($(this).val() == 'Suche') {
			$(this).val('');
		}
	});
	$('#searchterm').blur(function(){
		if ($(this).val() == '') {
			$(this).val('Suche');
		}
	});
	
	// sortierung
	$('#sortselect').change(function(e){
		sendFilterForm();
	});
	
	$('.auto-submit-star').rating({
		callback: function(value, link){
			var temp = $(this).parent().parent();
			$.get('/story/rate/storyid/' + $('#storyid').val() + '/stars/' + value, function(data) {
				temp.fadeOut('slow', function(){
					$('#rate-message').fadeIn();
				});
			});
		}
	});
	
});

function deleteFromAddressBook(element, id, username) {
	if (confirm('Benutzer "' + username + '" wirklich aus dem Adressbuch löschen?') == true) {
		$.get('/user/addressbookdelete/' + id);
		$(element).parent().parent().fadeOut();
	}
	return false;
}

function deleteMail(subject) {
	return confirm('Nachricht "' + subject + '" wirklich löschen?');
}

$(window).resize(function() {
	setFooter();
});

/**
 * Add username to receiver list
 * 
 * @param username
 * @return
 */
function addToReceiverList(username) {
	if ($('#receiver-list').val().length > 0) {
		$('#receiver-list').val($('#receiver-list').val() + '; ' + username );
	}
	else {
		$('#receiver-list').val(username);
	}
}






//dimScreen()
//by Brandon Goldman
jQuery.extend({
    //dims the screen
    dimScreen: function(speed, opacity, callback) {
        if(jQuery('#__dimScreen').size() > 0) return;
        
        if(typeof speed == 'function') {
            callback = speed;
            speed = null;
        }

        if(typeof opacity == 'function') {
            callback = opacity;
            opacity = null;
        }

        if(speed < 1) {
            var placeholder = opacity;
            opacity = speed;
            speed = placeholder;
        }
        
        if(opacity >= 1) {
            var placeholder = speed;
            speed = opacity;
            opacity = placeholder;
        }

        speed = (speed > 0) ? speed : 500;
        opacity = (opacity > 0) ? opacity : 0.5;
        return jQuery('<div></div>').attr({
                id: '__dimScreen'
                ,fade_opacity: opacity
                ,speed: speed
            }).css({
            background: '#000'
            ,height: '100%'
            ,left: '0px'
            ,opacity: 0
            ,position: 'fixed'
            ,top: '0px'
            ,width: '100%'
            ,zIndex: 990
        }).appendTo(document.body).fadeTo(speed, opacity, callback);
    },
    
    //stops current dimming of the screen
    dimScreenStop: function(callback) {
        var x = jQuery('#__dimScreen');
        var opacity = x.attr('fade_opacity');
        var speed = x.attr('speed');
        x.fadeOut(speed, function() {
            x.remove();
            if(typeof callback == 'function') callback();
        });
    }
});










/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
