var base_url = 'http://itemio.de/';
var Dom = YAHOO.util.Dom;
var loading_gif = '<img src="'+base_url+'bttns/loading.gif">';

// addEvent/removeEvent written by Dean Edwards, 2005
// with input from Tino Zijdel
// http://dean.edwards.name/weblog/2005/10/add-event/

function addEvent(element, type, handler) {
	// assign each event handler a unique ID
	if (!handler.$$guid) handler.$$guid = addEvent.guid++;
	// create a hash table of event types for the element
	if (!element.events) element.events = {};
	// create a hash table of event handlers for each element/event pair
	var handlers = element.events[type];
	if (!handlers) {
		handlers = element.events[type] = {};
		// store the existing event handler (if there is one)
		if (element["on" + type]) {
			handlers[0] = element["on" + type];
		}
	}
	// store the event handler in the hash table
	handlers[handler.$$guid] = handler;
	// assign a global event handler to do all the work
	element["on" + type] = handleEvent;
};
// a counter used to create unique IDs
addEvent.guid = 1;

function removeEvent(element, type, handler) {
	// delete the event handler from the hash table
	if (element.events && element.events[type]) {
		delete element.events[type][handler.$$guid];
	}
};

function handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(window.event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};



/* GRUPPEN ANZEIGEN IN QUICKLIST ----------------------------------------------------------*/

var groupsObject = {
	handleSuccess:function(o){
		Dom.get('quicklist_form').innerHTML = o.responseText;
	},
	handleFailure:function(o){
	},
	startRequest:function() {
		YAHOO.util.Connect.asyncRequest('GET', base_url+'ajax_quicklist_groups/', callbackGroups);
	}
};
var callbackGroups = {
	success:groupsObject.handleSuccess,
	failure:groupsObject.handleFailure,
	scope: groupsObject
};


/* QUICKLIST LEEREN ------------------------------------------------------------------------*/

var cleanObject = {
	handleSuccess:function(o){
		var formatted = YAHOO.lang.JSON.parse(o.responseText);
		if(!formatted['error']){
			Dom.get('quicklist_content').innerHTML = '';
			Dom.get('quicklist_count').innerHTML = formatted['count'];
		}

	},
	handleFailure:function(o){
	},
	startRequest:function() {
		Dom.get('quicklist_content').innerHTML = '<img src="'+base_url+'bttns/loading.gif">';
		YAHOO.util.Connect.asyncRequest('GET', base_url+'ajax_quicklist_clean/', callbackClean);
	}
};
var callbackClean = {
	success:cleanObject.handleSuccess,
	failure:cleanObject.handleFailure,
	scope: cleanObject
};


/* ITEMS IN GRUPPE VERSCHIEBEN --------------------------------------------------------------*/

var moveObject = {
	handleSuccess:function(o){
		var formatted = YAHOO.lang.JSON.parse(o.responseText);
		if(!formatted['error']){
			Dom.get('quicklist_content').innerHTML = formatted['message'];
			Dom.get('quicklist_count').innerHTML = formatted['count'];
		} else {
			Dom.get('quicklist_content').innerHTML = formatted['message'];
		}

	},
	handleFailure:function(o){
	},
	startRequest:function(group_id) {
		Dom.get('quicklist_content').innerHTML = '<img src="'+base_url+'bttns/loading.gif">';
		$('quicklist_wrapper').toggle();
		$('quicklist_link').removeClassName('quicklist_link_on').addClassName('quicklist_link_off');
		$('cancel_quicklist').toggle();
		YAHOO.util.Connect.asyncRequest('GET', base_url+'ajax_quicklist_move/'+group_id+'/', callbackMove);
	}
};
var callbackMove = {
	success:moveObject.handleSuccess,
	failure:moveObject.handleFailure,
	scope: moveObject
};


/* ITEM ZU QUICKLIST HINZUFÜGEN -----------------------------------------------------------*/

var addQLObject = {
	handleSuccess:function(o){
		var formatted = YAHOO.lang.JSON.parse(o.responseText);
		if(!formatted['error']){
			Dom.get('rem_'+formatted['id']).innerHTML = 'gespeichert';
			Dom.get('quicklist_count').innerHTML = formatted['count'];
		}
	},
	handleFailure:function(o){
	},
	startRequest:function(id) {
		Dom.get('rem_'+id).innerHTML = '<img src="'+base_url+'bttns/loading_flat.gif">';
		YAHOO.util.Connect.asyncRequest('GET', base_url+'ajax_remember/'+id+'/', callbackAdd);
	}
};
var callbackAdd = {
	success:addQLObject.handleSuccess,
	failure:addQLObject.handleFailure,
	scope: addQLObject
};


/* ITEM AUS QUICKLIST ENTFERNEN ------------------------------------------------------------*/

var remQLObject = {
	handleSuccess:function(o){
		var formatted = YAHOO.lang.JSON.parse(o.responseText);
		if(!formatted['error']){
			Dom.get('item_'+formatted['id']).innerHTML = '';
			Dom.get('quicklist_count').innerHTML = formatted['count'];
		}
	},
	handleFailure:function(o){
	},
	startRequest:function(id) {
		Dom.get('rem_'+id).innerHTML = '<img src="'+base_url+'bttns/loading_flat.gif">';
		YAHOO.util.Connect.asyncRequest('GET', base_url+'ajax_unremember/'+id+'/', callbackRem);
	}
};

var callbackRem = {
	success:remQLObject.handleSuccess,
	failure:remQLObject.handleFailure,
	scope: remQLObject
};


/* GRUPPEN ANZEIGEN IN USER ZUM EINLADEN ----------------------------------------------------*/

var inviteObject = {
	handleSuccess:function(o){
		Dom.get('invite_form').innerHTML = o.responseText;
	},
	handleFailure:function(o){
	},
	startRequest:function(invited_user) {
		YAHOO.util.Connect.asyncRequest('GET', base_url+'ajax_invite_groups/'+invited_user+'/', callbackInvite);
	}
};
var callbackInvite = {
	success:inviteObject.handleSuccess,
	failure:inviteObject.handleFailure,
	scope: inviteObject
};


/* MAIL VERSCHICKEN ----------------------------------------------------------------------*/

var sendMail = {
	handleSuccess:function(o){
		$('send_form').innerHTML = o.responseText;
	},
	handleFailure:function(o){
	},
	startRequest:function() {
		if($('subject').value == ''){
			alert('Du musst den Betreff ausfuellen!');
			return;
		}
		if($('message').value == ''){
			alert('Eine Mail ohne Inhalt macht wenig Sinn!');
			return;
		}
		var data = 'subject='+$('subject').value+'&message='+$('message').value+'&receiver='+$('receiver').value;
		$('send_form').innerHTML = '<img src="'+base_url+'bttns/loading.gif">';
		YAHOO.util.Connect.asyncRequest('POST', base_url+'send_mail/', callbackSendMail, data);
	}
};
var callbackSendMail = {
	success:sendMail.handleSuccess,
	failure:sendMail.handleFailure,
	scope: sendMail
};


/* MAIL BEANTWORTEN ----------------------------------------------------------------------*/

var answerMail = {
	handleSuccess:function(o){
		$('send_form_'+this.id).innerHTML = o.responseText;
	},
	handleFailure:function(o){
	},
	startRequest:function(id) {
		this.id = id;
		if($('subject').value == ''){
			alert('Du musst den Betreff ausfuellen!');
			return;
		}
		if($('message').value == ''){
			alert('Eine Mail ohne Inhalt macht wenig Sinn!');
			return;
		}
		var data = 'subject='+$('subject').value+'&message='+$('message').value+'&receiver='+$('receiver').value;
		$('send_form_'+id).innerHTML = '<img src="'+base_url+'bttns/loading.gif">';
		YAHOO.util.Connect.asyncRequest('POST', base_url+'send_mail/', callbackAnswerMail, data);
	}
};
var callbackAnswerMail = {
	success:answerMail.handleSuccess,
	failure:answerMail.handleFailure,
	scope: answerMail
};


/* ALLE MAILS LÖSCHEN ----------------------------------------------------------------------*/

var cleanMails = {
	handleSuccess:function(o){
		$('mails').innerHTML = o.responseText;
	},
	handleFailure:function(o){
	},
	startRequest:function() {
		$('mails').innerHTML = '<img src="'+base_url+'bttns/loading.gif">';
		YAHOO.util.Connect.asyncRequest('POST', base_url+'ajax_delete_mails/', callbackCleanMails);
	}
};
var callbackCleanMails = {
	success:cleanMails.handleSuccess,
	failure:cleanMails.handleFailure,
	scope: cleanMails
};


/* MAIL LÖSCHEN ----------------------------------------------------------------------*/

var deleteMail = {
	handleSuccess:function(o){
		$('mail_'+this.mail_id).innerHTML = o.responseText;
	},
	handleFailure:function(o){
	},
	startRequest:function(mail_id) {
		this.mail_id = mail_id;
		$('mail_'+mail_id).innerHTML = '<img src="'+base_url+'bttns/loading.gif">';
		var data = 'mail_id='+mail_id;
		YAHOO.util.Connect.asyncRequest('POST', base_url+'ajax_delete_mail/', callbackDeleteMail, data);
	}
};
var callbackDeleteMail = {
	success:deleteMail.handleSuccess,
	failure:deleteMail.handleFailure,
	scope: deleteMail
};


/* VOTING SPEICHERN -----------------------------------------------------------------------*/

function saveStar(event) {
	new Ajax.Request(base_url+'save_vote/', {
    	parameters: event.memo,
    	onComplete: function(xhr) {
      		// optional callback
      		//alert(xhr.responseText);
    	}
  	});
}


/* SORTIERUNG ----------------------------------------------------------------------------*/

function sorting() {
	$('items').innerHTML = '<img src="'+base_url+'bttns/loading.gif">';

	// falls die gleiche suchanfrage ausgeführt wurde, heißt das, dass die richtung geändert wurde
	// ansonsten die suchanfrage speichern in last_*
	if($('last_type').value == $('type').value
	&& $('last_offset').value == $('offset').value
	&& $('last_sorted').value == $('sorted').value
	){
		if($('direction').value == 'asc'){
			$('direction').value = 'desc';
		} else {
			$('direction').value = 'asc';
		}
	} else {
		// direction zurücksetzen
		$('direction').value = 'desc';
		// alte werte speichern
		$('last_type').value   = $('type').value;
		$('last_sorted').value = $('sorted').value;
		$('last_offset').value = $('offset').value;
	}

	var data = 	 'sorted='		+$('sorted').value
				+'&type='		+$('type').value
				+'&searched='	+$('searched').value
				+'&offset='		+$('offset').value
				+'&per_page='	+$('per_page').value
				+'&direction='	+$('direction').value;

	new Ajax.Updater('items', base_url+'ajax_items/', {
	  	method: 'post',
	  	evalScripts: true,
	  	parameters: data
	});
}

/* USER EINLADEN ---------------------------------------------------------------------------*/

var inviteUser = {
	handleSuccess:function(o){
		$('invite_form').innerHTML = o.responseText;
	},
	handleFailure:function(o){
	},
	startRequest:function(group) {
		var user = $('searched').value;
		var data = 'user='+user+'&group='+group;
		$('invite_form').innerHTML = '<img src="'+base_url+'bttns/loading.gif">';
		YAHOO.util.Connect.asyncRequest('POST', base_url+'invite/', callbackInviteUser, data);
	}
};
var callbackInviteUser = {
	success:inviteUser.handleSuccess,
	failure:inviteUser.handleFailure,
	scope: inviteUser
};

function editGroupTitle(){
	$('groupTitle').innerHTML;
}



/* EVENTS ----------------------------------------------------------------------*/
addEvent(window, "load", loaded);

function loaded(){

/* INLINE EDITING --------------------------------------------------------------*/
	// INLINE EDITING der user_description auf my/
	if($('user_description')){
		addEvent($('user_description'), 'mouseover', function(){
			this.style.cursor='pointer';
			this.style.backgroundColor='#FFFFD6';
		});
		addEvent($('user_description'), 'mouseout', function(){
			this.style.backgroundColor='#FFF';
		});
		addEvent($('user_description'), 'click', function(){
			var content = this.innerHTML;
			if(this.clicked) return;
			this.clicked = true;

			this.innerHTML = '<textarea id="user_description_textarea">'+content+'</textarea>';
			this.innerHTML += '<input type="submit" class="inline_submit" id="save_desc" value="speichern"><input type="submit" class="inline_submit" id="cancel_desc" value="abbrechen">';
			var that = this;
			// CANCEL
			addEvent($('cancel_desc'), 'click', function(e){
				fixEvent(e).stopPropagation();
				that.innerHTML = content;
				that.clicked = false;
			});
			// SAVE
			addEvent($('save_desc'), 'click', function(e){
				fixEvent(e).stopPropagation();
				var data = new Array();
				data['user_description'] = $('user_description_textarea').value;
				data['user_id'] = $('searched').value;
				if(data['user_description'] == content){
					that.innerHTML = content;
					that.clicked = false;
				} else {
					that.innerHTML = loading_gif;
					new Ajax.Request(base_url+'ajax_update_userdescription/', {
				    	parameters: data,
				    	onComplete: function(xhr) {
				      		that.innerHTML = xhr.responseText;
      						that.clicked = false;
				    	},
				    	onFailure: function(){
				    		that.innerHTML = 'Deine &Auml;nderungen konnten nicht gespeichert werden';
    						that.clicked = false;
				    	}
				  	});
				}
			});
		});
	}


	// INLINE EDITING der user_url auf my/
	if($('user_url')){
		addEvent($('user_url'), 'mouseover', function(){
			this.style.cursor='pointer';
			this.style.backgroundColor='#FFFFD6';
		});
		addEvent($('user_url'), 'mouseout', function(){
			this.style.backgroundColor='#FFF';
		});
		addEvent($('user_url'), 'click', function(){
			var content = this.innerHTML;
			if(this.clicked) return;
			this.clicked = true;
			this.innerHTML = '<input type="text" id="user_url_input" value="'+content+'" />';
			this.innerHTML += '<input type="submit" class="inline_submit" id="save_url" value="speichern"><input type="submit" class="inline_submit" id="cancel_url" value="abbrechen">';
			var that = this;
			// CANCEL
			addEvent($('cancel_url'), 'click', function(e){
				fixEvent(e).stopPropagation();
				that.innerHTML = content;
				that.clicked = false;
			});
			// SAVE
			addEvent($('save_url'), 'click', function(e){
				fixEvent(e).stopPropagation();
				var data = new Array();
				data['user_url'] = $('user_url_input').value;
				data['user_id'] = $('searched').value;
				if(data['user_url'] == content){
					that.innerHTML = content;
					that.clicked = false;
				} else {
					that.innerHTML = loading_gif;
					new Ajax.Request(base_url+'ajax_update_userurl/', {
				    	parameters: data,
				    	onComplete: function(xhr) {
				      		that.innerHTML = xhr.responseText;
      						that.clicked = false;
				    	},
				    	onFailure: function(){
				    		that.innerHTML = 'Deine &Auml;nderungen konnten nicht gespeichert werden';
    						that.clicked = false;
				    	}
				  	});
				}
			});
		});
	}


	// INLINE EDITING der group_description auf group/...
	if($('group_description')){
		addEvent($('group_description'), 'mouseover', function(){
			this.style.cursor='pointer';
			this.style.backgroundColor='#FFFFD6';
		});
		addEvent($('group_description'), 'mouseout', function(){
			this.style.backgroundColor='#FFF';
		});
		addEvent($('group_description'), 'click', function(){
			var content = this.innerHTML;
			if(this.clicked) return;
			this.clicked = true;

			this.innerHTML = '<textarea id="group_description_textarea">'+content+'</textarea>';
			this.innerHTML += '<input type="submit" class="inline_submit" id="save_desc" value="speichern"><input type="submit" class="inline_submit" id="cancel_desc" value="abbrechen">';
			var that = this;
			// CANCEL
			addEvent($('cancel_desc'), 'click', function(e){
				fixEvent(e).stopPropagation();
				that.innerHTML = content;
				that.clicked = false;
			});
			// SAVE
			addEvent($('save_desc'), 'click', function(e){
				fixEvent(e).stopPropagation();
				var data = new Array();
				data['group_description'] = $('group_description_textarea').value;
				data['group_id'] = $('searched').value;
				if(data['group_description'] == content){
					that.innerHTML = content;
					that.clicked = false;
				} else {
					that.innerHTML = loading_gif;
					new Ajax.Request(base_url+'ajax_update_groupdescription/', {
				    	parameters: data,
				    	onComplete: function(xhr) {
				      		that.innerHTML = xhr.responseText;
      						that.clicked = false;
				    	},
				    	onFailure: function(){
				    		that.innerHTML = 'Deine &Auml;nderungen konnten nicht gespeichert werden';
    						that.clicked = false;
				    	}
				  	});
				}
			});
		});
	}


	// INLINE EDITING der group_privacy auf group/...
	if($('group_privacy')){
		addEvent($('group_privacy'), 'mouseover', function(){
			this.style.cursor='pointer';
			this.style.backgroundColor='#FFFFD6';
		});
		addEvent($('group_privacy'), 'mouseout', function(){
			this.style.backgroundColor='#FFF';
		});
		addEvent($('group_privacy'), 'click', function(){
			var content = this.innerHTML;
			if(this.clicked) return;
			this.clicked = true;
			var type = this.className;
			var checked = new Array();
			checked[0] = ''; checked[1] = ''; checked[2] = '';
			checked[type] = ' checked="checked"';
			this.innerHTML = '<p class="small"><input type="radio" name="privacy" id="privacy0" value="0" '+checked[0]+'>&ouml;ffentlich&nbsp;<input type="radio" id="privacy1" name="privacy" value="1" '+checked[1]+'>halb-&ouml;ffentlich&nbsp;<input type="radio" name="privacy" id="privacy2" value="2" '+checked[2]+'>privat</p>';
			this.innerHTML += '<input type="submit" class="inline_submit" id="save_privacy" value="speichern"><input type="submit" class="inline_submit" id="cancel_privacy" value="abbrechen">';
			var that = this;
			// CANCEL
			addEvent($('cancel_privacy'), 'click', function(e){
				fixEvent(e).stopPropagation();
				that.innerHTML = content;
				that.clicked = false;
			});
			// SAVE
			addEvent($('save_privacy'), 'click', function(e){
				fixEvent(e).stopPropagation();

				var val;
				if($('privacy0').checked) val = 0;
				else if($('privacy1').checked) val = 1;
				else val = 2;

				var data = new Array();

				data['group_privacy'] = val;
				data['group_id'] = $('searched').value;
				if(data['group_privacy'] == type){
					that.innerHTML = content;
					that.clicked = false;
				} else {
					that.innerHTML = loading_gif;
					new Ajax.Request(base_url+'ajax_update_groupprivacy/', {
				    	parameters: data,
				    	onComplete: function(xhr) {
				      		that.innerHTML = xhr.responseText;
      						that.clicked = false;
				    	},
				    	onFailure: function(){
				    		that.innerHTML = 'Deine &Auml;nderungen konnten nicht gespeichert werden';
    						that.clicked = false;
				    	}
				  	});
				}
			});
		});
	}


	// INLINE EDITING group_delete auf group/...
	if($('group_delete')){
		addEvent($('group_delete'), 'mouseover', function(){
			this.style.cursor='pointer';
			this.style.backgroundColor='#FFFFD6';
		});
		addEvent($('group_delete'), 'mouseout', function(){
			this.style.backgroundColor='#FFF';
		});
		addEvent($('group_delete'), 'click', function(){
			var content = this.innerHTML;
			if(this.clicked) return;
			this.clicked = true;

			this.innerHTML += '<input type="submit" class="inline_submit" id="confirm_del" value="Gruppe l&ouml;schen"><input type="submit" class="inline_submit" id="cancel_del" value="abbrechen">';
			var that = this;
			// CANCEL
			addEvent($('cancel_del'), 'click', function(e){
				fixEvent(e).stopPropagation();
				that.innerHTML = content;
				that.clicked = false;
			});
			// DELETE
			addEvent($('confirm_del'), 'click', function(e){
				fixEvent(e).stopPropagation();

				if(!confirm("Das Löschen kann nicht rückgängig gemacht werden! Möchtest Du Diese Gruppe wirklich löschen?")){
					that.innerHTML = content;
					that.clicked = false;
					return;
				}

				var data = new Array();
				data['group_id'] = $('searched').value;
				new Ajax.Request(base_url+'ajax_delete_group/', {
			    	parameters: data,
			    	onComplete: function(xhr) {
			    		if(xhr.responseText == '1'){
							self.location.href=base_url+'create_group/';
							return;
			    		} else {
				    		that.innerHTML = 'Die Gruppe konnte nicht gel&ouml;scht werden.';
							that.clicked = false;
			    		}
			    	},
			    	onFailure: function(){
			    		that.innerHTML = 'Die Gruppe konnte nicht gel&ouml;scht werden.';
						that.clicked = false;
			    	}
			  	});
			});
		});
	}


/* SIDEBAR -----------------------------------------------------------------------*/

	var sidebar_z = 1000;

	// SIDEBAR LINK overview
	if($('overview_link')){
		addEvent($('overview_link'), 'click', function(){
			sidebar_z++;
			$('overview2_wrapper').style.zIndex = sidebar_z;
			$('overview2_wrapper').toggle();
			if($('overview_link').hasClassName('overview_link_on')){
				$('overview_link').removeClassName('overview_link_on').addClassName('overview_link_off');
				$('cancel_overview').toggle();
			} else {
				$('overview_link').addClassName('overview_link_on').removeClassName('overview_link_off');
				$('cancel_overview').toggle();
			};
		});
	}

	// SIDEBAR LINK profil
	if($('profil_link')){
		addEvent($('profil_link'), 'click', function(){
			sidebar_z++;
			$('profil2_wrapper').style.zIndex = sidebar_z;
			$('profil2_wrapper').toggle();
			if($('profil_link').hasClassName('profil_link_on')){
				$('profil_link').removeClassName('profil_link_on').addClassName('profil_link_off');
				$('cancel_profil').toggle();
			} else {
				$('profil_link').addClassName('profil_link_on').removeClassName('profil_link_off');
				$('cancel_profil').toggle();
			};
		});
	}

	// SIDEBAR LINK groups
	if($('groups_link')){
		addEvent($('groups_link'), 'click', function(){
			sidebar_z++;
			$('groups2_wrapper').style.zIndex = sidebar_z;
			$('groups2_wrapper').toggle();
			if($('groups_link').hasClassName('groups_link_on')){
				$('groups_link').removeClassName('groups_link_on').addClassName('groups_link_off');
				$('cancel_groups').toggle();
			} else {
				$('groups_form').innerHTML = loading_gif;
				new Ajax.Request(base_url+'ajax_sidebar_groups/', {
			    	onComplete: function(xhr) {
						$('groups_form').innerHTML = xhr.responseText;
			    	},
			    	onFailure: function(){
			    		that.innerHTML = 'Deine Gruppen konnten leider nicht angezeigt werden.';
			    	}
			  	});
				$('groups_link').addClassName('groups_link_on').removeClassName('groups_link_off');
				$('cancel_groups').toggle();
			};
		});
	}

}