/**
 * @todo change to non global scope
 */
(function($x)
{
	/**
     * url of the current page
     * 
     * @type string
     * @private
     */
    var _url = window.location.href;
    
    /**
     * Parts of the url
     * 
     * @type array
     * @private
     */
    var _urlParts = _url.split('/');
    
	/**
	 * user vars
	 */
	vars = {
		'user' : null,
		'newsHash' : null,
		'wysiwyg' : {
			css: '/css/global.css',
			initialContent: ''
		},
		accountName : _urlParts[3],
        action : (typeof _urlParts[4] != 'undefined') ? _urlParts[4] : 'index'
	};
	
	/**
	 * get me out of here
	 */
	$x.goTo = function(url) {
		window.location.href = '/' + vars.user + '/' + url;
	};
	
	/**
	 * reload me baby
	 */
	$x.refresh = function() {
		window.location.href = window.location.href;
	};
	
	/**
	 * figures out  what id the target has
	 */
	getId = function(e) {
		return e.target.id.split('.')[1];
	};
	
	/**
	 * background control for hover Elements
	 */
	_hoverHelperBg = function(out) {
		if(!$('#hoverHelperBg').length) {
			$('<div>')
				.attr({'id' : 'hoverHelperBg'})
				.prependTo('body');
		}
		
		$('#hoverHelperBg').mouseover(out);
	};
	
	/**
	 * gives a hover element
	 */
	$x.infoIn = function(e,close) {
		$('.hoverHelper').hide();
		var tId = '#' + e.target.id;
		var top = $(tId).position().top + $(tId).height() / 2 + 27;
		var left = $(tId).position().left + $(tId).width() / 2 - $(tId + 'Info').width() + 830; //+15 because of padding
		
		$('#hoverHelperBubble')
		.fadeIn(100)
		.css({
			'top' : top - 7 + 'px',
			'left' : left + $(tId + 'Info').width() - 20 +'px'
		});
		
		$(tId + 'Info')
			.css({
				'top' : top + 'px',
				'left' : left +'px'
			})
			.show();		
	};
	
	$x.infoOut = function(e) {
		$('#' + e.target.id + 'Info').hide();
		$('#hoverHelperBubble').hide();
	};
	
	/**
	 * shows list of users
	 */
	_userListIn = function() {
		$('.hoverHelper').hide();
		var tId = '#userMenue';
		var top = $(tId).position().top + $(tId).height() / 2 + 30;
		var left = $(tId).position().left;
		
		$(tId).css({'background-color': '#8a8a8a'});
		
		var sel = 'selected';
		if($(tId).hasClass(sel)) {
			$(tId).removeClass(sel);
			$(tId).attr('marker', 1);
		}
		
		$('#userList')
			.show()
			.css({
				'top' : top + 'px',
				'left' : left +'px'
			});
		
		_hoverHelperBg(_userListOut);
	};
	
	_userListOut = function() {
		var tId = '#userMenue';
		
		$('#hoverHelperBg').remove();
		
		$('#userList').hide();
		
		$(tId).removeAttr('style');
		if(1 == $(tId).attr('marker')) {
			$(tId).removeAttr('marker');
			$(tId).addClass('selected');
		}
		
	};
	
	/**
	 * goes to a user in list
	 */
	$x.gotoUser = function() {
		window.location.href = '/' + this.id + '/';
	};

	/**
	 * login / logout hover item
	 */
	function _login(e) {
		$x.infoIn(e,true);
		$('#loggedOutInfo form').submit(function () {
			$('#loggedOutInfo form').before('<div>Logge ein...<br /><br /></div>');
			var values = $('#loggedOutInfo form').serializeArray();
			$('#loggedOutInfo form input').attr('disabled', 'disabled');
			$.post('/auth/login', values, function(json) {
				if(true == json) {
					$x.refresh();
				} else {
					$('#loggedOutInfo div').remove();
					$('#loggedOutInfo form').before('<div>' + json + '<br /><br /></div>');
					$('#loggedOutInfo form input').removeAttr('disabled');
				}
			}, 'json');
			
			return false;
		});
		$('#loggedOutInfo .close').click(function() { $x.infoOut(e); });
	}
	
	function _logout() {
		$.post('/auth/logout', $x.refresh);
	};
	
	/**
	 * Reload online users
	 */
	function _updateOnlineUsers(){
		setInterval(function() {
			 $.getJSON('/status/user-online', function(data){
				 $('#memberOnlineInfo').html(data['text']);
				 $('#memberOnline').html(data['count']);
			 });
		}, 11000);
	}
	
	/**
	 * handle news
	 */
	function _news(){
		$('#newsContent').slideToggle("slow");
	}
	
	function _deleteNews() {
		$.post('/status/delete-news');
		$('#newsContent').remove();
		$('#news').remove();
	}
	
	function _updateNews() {
		setInterval(function() {
			$.getJSON('/status/news', function(data){
				if($('#newsContent').length == 0) {
					$('#mainContainer').prepend(data['content']);
					$('#loggedIn').after(data['counter']);
				} else {
					// Prevent closing when replaced
					if('block' == $('#newsContent').css('display')) {
						data['content'] = data['content'].replace(/display: none/, 'display: block');
					}
					
					$('#newsContent').replaceWith(data['content']);
					$('#news').replaceWith(data['counter']);
				}
				
				//if(vars.newsHash !== null && vars.newsHash != data['hash']) {
					//$x.addMp3Player('/js/flashplayer/song.mp3', '#newsContent', 'block');
				//}
				
				vars.newsHash = data['hash'];
				$('#newsInfo').html(data['overview']);
				$('#news').hover($x.infoIn, $x.infoOut);
			});
		}, 10000);
	}
	
	$x.addMp3Player = function(mp3, insertInto, display) {
		$(insertInto).prepend('<span id="flashPlayer" style="display: ' + display + '; float: left;"></span>');
		
		var so = new SWFObject("/js/flashplayer/playerMini.swf", "mymovie", "75", "30", "7", "#FFFFFF");
		so.addVariable("autoPlay", "yes");
		so.addVariable("soundPath", mp3);
		so.write("flashPlayer");
	};
	
	/**
	 * comments handling
	 */
	$x.toggleComments = function(e) {
		$('#commentContainer\\.' + getId(e)).toggle();
	};

	$x.toggleNewComment = function(e) {
		//figure out the right action
		if('index' == vars.action || 'profile' == vars.action || 'artikel' == vars.action) {
			var action = 'profile';
		} else {
			var action = 'fotoalben';
		}
		
		if('fotoalben' == vars.accountName) {
			var action = 'fotoalben';
		}
		
		var id= '\\.' + getId(e);
		if (!$('#newCommentContent' + id).length) {
			$.get('/' + vars.user + '/' + action + '/comment/profileEntryId/' + getId(e) , function(html) { 
				if (!$('#newCommentContent' + id).length) {
					$('#newComment' + id).parent().parent().after(html);
					$('#commentContainer' + id).show();
				}
			});
		} else {
			$('#commentContainer' + id).hide();
			$('#newCommentContent' + id).remove();
		}
	};
	
	$x.saveNewComment = function(e, url) {
		var id = $(e).attr('id').split('.')[1];
		var selector = '\\.' + id;
		$.post('/' + vars.user + url + id, $('#newCommentContent' + selector + ' *').serializeArray(), 
			function(json){
				if (json.valid) {
					$('#newCommentContent' + selector).remove();
					$('#commentContainer' + selector).remove();
					$('#commentMenuContainer' + selector).replaceWith(json.response);
					alert('Kommentar erfolgreich gespeichert!');
				} else {
					$('#newCommentContent' + selector).replaceWith(json.response);
				}
			}, 
			'json');
		return false;
	};
	
	$x.editPanel = function(e, baseUrl, modal, callbackFunction) {
		$(e).find('.options').toggle();
		
		var id = e.id.split('.')[1];
		$(e).find('.options div').unbind();
		
		$(e).find('.options div').click(function() {
			var option = $(this).attr('class').split(' ')[0];
			if('delete' == option.split('-')[0] && !confirm('Diesen Eintrag wirklich entfernen?')) {
				return false;
			}
			if(-1 !== modal.search(option)) {
				$.modal(baseUrl + option + '/id/' + id);
			} else {
				$.post(baseUrl + option, {'id' : id}, callbackFunction, 'html');
			}
		});
	};
	
	function _newsletter() {
		$.modal('/newsletter/');
		return false;
	}
	
	function _subscribeNewsletter() {
		var callbackFunction = function(value) {
			$('#newsletterForm').replaceWith(value);
		};
		$.post('/newsletter/subscribe', $('#newsletterForm').serialize(), callbackFunction, 'html');
	}
	
	function _socialIt() {
		var t = $(this);
		var header = t.attr('linkheader');
		var id = t.attr('identifier');
		var user = t.attr('user');
		
		var fb = '<div class="socialFb"><fb:like href="http://www.x-hoch-n.de/' + user + '/artikel/' + header + '" ' +
			'layout="button_count" show_faces="false" width="140" font="lucida grande" ref="facebook_' + 
			id +  '" class="facebookLikeIt"></fb:like></div>';
		
		var google = '<div class="socialGoogle"><g:plusone size="medium" href="http://www.x-hoch-n.de/' + user + 
		'/artikel/' + header + '"></g:plusone></div>';
		
		t.unbind();
		t.append(fb + google);
		FB.XFBML.parse(this);
		gapi.plusone.go(this);
	}
	
	function _searchTermFocus() {
		if('' == this.value || 'Suche...' == this.value) {
			$(this).val('');
		}
	}
		
	$x.init = function(user) {
		vars.user = user;
		
		$('#userMenue').mouseover(_userListIn);

		$('#loggedIn').click(_logout);
		$('#loggedOut').click(_login);
		$('#news').live('click', _news);
		$('#deleteNews').live('click', _deleteNews);
		$('#memberOnline, #news, #loggedIn').hover($x.infoIn, $x.infoOut);
		
		$('.newsletterSubscription').click(_newsletter);
		$('#subscribeNewsletter').live('click', _subscribeNewsletter);
		
		$('#searchTerm').focus(_searchTermFocus);
		
		$('#performSearch').click(function() { 
		$('#searchForm').trigger('submit'); });
		
		$('.socialIt').click(_socialIt);
		
		_updateOnlineUsers();
		_updateNews();
	};
	
})(xhochn = {});
