function UpdateEvents() {
	$('.date_has_event').each(function () {
		$(this).tooltip({tip: '#'+$(this).children().attr('id'), relative: true, offset: [15, 0]}).dynamic({bottom: { direction: 'down', bounce: true } });
	});
	$('.tooltip').each(function () {
		$(this).click(function(e){
			return false;
		});
	});

	if ($('#share_link').length > 0) {
		$('#share_link > li').hover(
			function() { $('ul', this).css('visibility', 'visible'); },
			function() { $('ul', this).css('visibility', 'hidden'); }
		);
	}
	if ($('#events_attenders').length > 0) {
		$('#events_attenders').hide();
	}
	if ($('#events_manage').length > 0) {
		$('#events_manage').hide();
	}
	$('.search_dropdown > li').hover(
		function() { $('ul', this).css('visibility', 'visible'); },
		function() { $('ul', this).css('visibility', 'hidden'); }
	);
	$('#search_filter > li > ul > li > a').click(function() { SelectFilter($(this).text()); });
	$('#search_filter > li > a').text($("#search_filter > li > ul > li > a[title='"+$('#search_filter > li > input').val()+"']").text());
	$('#search_input').result( function(event, data, formatted) { DoSearch(formatted); } );
}

function DoSearch(request) {
	request_send = request.replace(/\s/gi, "+");
	request_send = request_send.replace(/\//gi, "");
	request_send = request_send.replace(/\#/gi, "");
	request_send = request_send.replace(/\%/gi, "");
	//request_send = encodeURIComponent(encodeURIComponent(request_send)); //sorry this is ugly
	if (request_send.length > 0) {
		request = decodeURIComponent(request.replace(/\%/gi, ""));
		request = request.replace(/\+/gi, " ");
		$('#search_request').text(request);
		$('#search_input').val(request);
		searchData = 'events/'+request_send+'/mode/search';
		if ($('#search_filter').length > 0 && $('#search_filter > li > input').val().length > 0) {
			searchData += '/filter/'+$('#search_filter > li > input').val();
		}
		$.ajax({
			url: '/',
			data: searchData+'/xhr',
			success: function(msg) {
				$('#content').html(msg);
				UpdateInterface();
				UpdateEvents();
				document.title = winTitle +' > ' + request;
			}
		});
	}
}

function SelectFilter(sType) {
	$('#search_filter > li > input').val(sType.substring(0, sType.indexOf(' ')).toLowerCase());
	$('#search_filter > li > a').text(sType);
	$('#search_filter > li > ul').css('visibility', 'hidden');
	DoSearch($('#search_input').val());
}

function getCurrentDate() {
	var d = new Date();
	var curr_month = d.getMonth();
	var curr_year = d.getFullYear();

	curr_month = curr_month+1;
	if (curr_month.toString().length == 1) {
		curr_month = '0'+curr_month.toString();
	}
	return curr_year+'-'+curr_month.toString();
}

function UpdateManageMenu(key) {
	$.ajax({
		url: '/',
		data: 'events/'+key+'/action/manage_menu/xhr',
		success: function(msg){
			if (msg.length > 0) {
				$('#events_manage_link').html(msg);
				$('#events_manage').show();
			}
		}
	});
}

function UpdateAttenders(key) {
	$.ajax({
		url: '/',
		data: 'events/'+key+'/action/attenders/xhr',
		success: function(msg){
			if (msg.length > 0) {
				$('#events_attenders_link').html(msg);
				$('#events_attenders').show();
			} else {
				$('#events_attenders').hide();
			}
		}
	});
}

function ChangeTo(event, mode) {
	$('#content').block({ message: null, overlayCSS: { backgroundColor: '#FFF' }  });
	if (event == '') { event = getCurrentDate();	}
	if (!is_webid(event)) {
		if (mode == '') { mode = 'calendar';	}
		if (mode == 'search') { DoSearch(event); return; }
		destUrl = 'events/'+event+'/mode/'+mode+'/xhr';
	} else {
		destUrl = 'events/'+event+'/xhr';
	}
	$.ajax({
		url: '/',
		data: destUrl,
		success: function(msg){
			$('#content').unblock();
			$('#content').html(msg);
			UpdateEvents();
			UpdateInterface();
			if (is_webid(event)) {
				$('#event_this_week').hide();
				UpdateAttenders(event);
				if ($('#events_manage').length > 0) {
					UpdateManageMenu(event);
				}
			} else {
				$('#event_this_week').show();
			}
			document.title = winTitle +' > ' + $('#crumbs li:last').text();
		}
	});
}

function GoPage(key, page) {
	if (!$('#last_comments').length) {
		ChangeTo(key);
	}
	$('#last_comments').block({ message: null, overlayCSS: { backgroundColor: '#FFF' }  });
	$.ajax({
		url: '/',
		data: 'events/'+key+'/page/'+page+'/xhr',
		success: function(msg){
			$('#last_comments').unblock();
			$('#last_comments').html(msg);
			UpdateInterface();
		}
	});
}

function ChangeToDay(dDate) {
	$.address.value(dDate+'/list');
}

function customHistory(module) {
	var tableau=module.split('/');
	if (tableau.length == 1) {
		ChangeTo(tableau[0], 'calendar');
	} else if (tableau.length == 2 && tableau[1]) {
		ChangeTo(tableau[0], tableau[1]);
	} else if (tableau[1] == 'page' && tableau[0] !== null && tableau[2] !== null) {
		GoPage(tableau[0], tableau[2]);
	}
}

function SubmitEvent() {
	if ($('#name').val().length <= 0) {
		DisplayError($('#event_form_error'), 'Name must be filled.');
		$('#name').focus();
		return false;
	}
	if ($('#date').val().length <= 0) {
		DisplayError($('#event_form_error'), 'Event date must be filled.');
		$('#date').focus();
		return false;
	}
	if ($('#list_artist').val().length <= 0) {
		DisplayError($('#event_form_error'), 'Add a leat on artist.');
		$('#list_artist').focus();
		return false;
	}
	if ($('#venue').val().length <= 0) {
		DisplayError($('#event_form_error'), 'Event\'s venue must be filled.');
		$('#venue').focus();
		return false;
	}
	if ($('#address').val().length <= 0) {
		DisplayError($('#event_form_error'), 'Address must be filled.');
		$('#address').focus();
		return false;
	}
	if ($('#location').val().length <= 0) {
		DisplayError($('#event_form_error'), 'Location must be filled.');
		$('#location').focus();
		return false;
	}
	if ($('#country').val().length <= 0) {
		DisplayError($('#event_form_error'), 'Please select a country.');
		$('#country').focus();
		return false;
	}
	DeasactiveForm('#event_form');
	$('#event_form').submit();
}

function AddEvent() {
	$.ajax({
		url: '/',
		data: 'events/add/xhr',
		success: function(msg){
			$('#dialog_box').html(msg);
			$('#dialog_box').dialog('option', 'title', 'Add an event');
			$('#dialog_box').dialog('option', 'buttons', { "Create event": function() { SubmitEvent(); return false; }, "Cancel": function() { $(this).dialog('close'); } });
			$('#dialog_box').dialog('option', 'bgiframe', true);
			$('#dialog_box').dialog('option', 'width', 595);
			$('#dialog_box').dialog('option', 'height', 'auto');
			$('#dialog_box').dialog('open');
			UpdateInterface();
			$('.datepicker input').each(function (obj) {
				$(this).datepicker('option', 'minDate', '0');
			});
		}
	});
}

function SubmitContest() {
	if ($('#name').val().length <= 0) {
		DisplayError($('#contest_form_error'), 'Name must be filled.');
		$('#name').focus();
		return false;
	}
	if ($('#question').val().length <= 0) {
		DisplayError($('#contest_form_error'), 'Question must be filled.');
		$('#question').focus();
		return false;
	}
	DeasactiveForm('#contest_form');
	$('#contest_form').submit();
}

function SubmitPromote() {
	if ($('#flyer').val().length <= 0) {
		DisplayError($('#promote_form_error'), 'Flyer must be filled.');
		$('#flyer').focus();
		return false;
	}
	DeasactiveForm('#promote_form');
	$('#promote_form').submit();
}

function SendComment() {
	DeasactiveForm('#comment_form');
	$('#comment_form').submit();
}

function SubmitPlayContest() {
	DeasactiveForm('#contest_form');
	$('#contest_form').submit();
}

function SubmitDelete() {
	if (confirm("Sure ?")) {
		DeasactiveForm('#delete_form');
		$('#delete_form').submit();
	}
}

function UpdatePostedForm(formType, msg, key) {
	if (formType == 'add') {
		ActiveForm('#event_form');
		if (msg.indexOf('error:') > -1) {
			DisplayError($('#event_form_error'), msg);
		} else {
			window.location = "/events/"+msg;
		}
	} else if (formType == 'comment') {
		ActiveForm('#comment_form');
		if (msg.indexOf('error:') > -1) {
			DisplayError($('#comment_form_error'), msg);
		} else {
			$('#body').val('Write something...');
			GoPage(msg+'-'+key, -1);
		}
	} else if (formType == 'play_contest') {
		ActiveForm('#contest_form');
		if (msg.indexOf('error:') > -1) {
			DisplayError($('#contest_form_error'), msg);
		} else {
			$('#contest_html').html(msg);
			$('#dialog_box').dialog('option', 'buttons', { "Close": function() { $(this).dialog('close'); } });
		}
	} else if (formType == 'create_contest') {
		ActiveForm('#contest_form');
		if (msg.indexOf('error:') > -1) {
			DisplayError($('#contest_form_error'), msg);
		} else {
			window.location.reload(true);
		}
	} else if (formType == 'promote') {
		ActiveForm('#promote_form');
		if (msg.indexOf('error:') > -1) {
			DisplayError($('#promote_form_error'), msg);
		} else {
			window.location="/home";
		}
	} else if (formType == 'delete') {
		ActiveForm('#promote_form');
		if (msg.indexOf('error:') > -1) {
			DisplayError($('#delete_form_error'), msg);
		} else {
			window.location="/events";
		}
	} else {
		alert(msg);
	}
}

function UserAttends(key) {
	$.ajax({
		url: '/',
		data: 'events/'+key+'/action/user_attends/xhr',
		success: function(msg){
			if ($("#savtofav").html().indexOf('No') === 0) {
				$("#savtofav").html('No, I don\'t gonna come');
			} else {
				$("#savtofav").html('Tes I gonna come !');
			}
			UpdateAttenders(key);
		}
	});
}

function DisplayCover(key) {
	var imgTesting = new Image();
	function CreateDelegate(contextObject, delegateMethod) {
		return function() {
			return delegateMethod.apply(contextObject, arguments);
		};
	}

	function imgTesting_onload() {
		$('#dialog_box').dialog('option', 'buttons', { });
		$('#dialog_box').dialog('option', 'title', '');
		$('#dialog_box').html('<img src="'+this.src+'"/>');
		$('#dialog_box').dialog('option', 'bgiframe', true);
		$('#dialog_box').dialog('option', 'width', this.width + 21);
		$('#dialog_box').dialog('option', 'height', this.height + 57);
		$('#dialog_box').dialog('open');
		$(document).click(function() { $('#dialog_box').dialog('close'); $(document).unbind("click"); });
		$('#dialog_box').click(function(e) {e.stopPropagation();});
		$('#content').unblock();
	}
	$('#content').block({ message: null, overlayCSS: { backgroundColor: '#FFF' } });
	imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
	imgTesting.src = '/image/event/flyer/'+key;
}

function DeleteMessage(key, id) {
	$.ajax({
		url: '/',
		data: 'events/'+key+'/del_com/'+id+'/xhr',
		success: function(msg){
			GoPage(key, 1);
		}
	});
}

function EditEvent(key) {
	$.ajax({
		url: '/',
		data: 'events/'+key+'/action/edit/xhr',
		success: function(msg){
			$('#dialog_box').dialog('option', 'title', 'Edit this event');
			$('#dialog_box').html(msg);
			$('#dialog_box').dialog('option', 'buttons', { "Save Changes": function() { SubmitEvent(); return false; }, "Cancel": function() { $(this).dialog('close'); } });
			$('#dialog_box').dialog('option', 'bgiframe', true);
			$('#dialog_box').dialog('option', 'width', 595);
			$('#dialog_box').dialog('option', 'height', 'auto');
			$('#dialog_box').dialog('open');
			UpdateInterface();
			if ($('#country').attr('title').length > 0) {
				$('#country').val($('#country').attr('title'));
			}
		}
	});
}

function DeleteEvent(key) {
	$.ajax({
		url: '/',
		data: 'events/'+key+'/action/delete/xhr',
		success: function(msg){
			$('#dialog_box').dialog('option', 'title', 'Delete this event');
			$('#dialog_box').html(msg);
			$('#dialog_box').dialog('option', 'buttons', { "Yes, delete It !": function() { SubmitDelete(); return false; }, "Cancel": function() { $(this).dialog('close'); } });
			$('#dialog_box').dialog('option', 'bgiframe', true);
			$('#dialog_box').dialog('option', 'width', 595);
			$('#dialog_box').dialog('option', 'height', 'auto');
			$('#dialog_box').dialog('open');
			UpdateInterface();
		}
	});
}

function CreatePromote(key) {
	$.ajax({
		url: '/',
		data: 'events/'+key+'/action/promote/xhr',
		success: function(msg){
			if ($('#events_manage_link_promote').text().indexOf("Unpromote", 0) === 0) {
				$('#events_manage_link_promote').text('Promote this event');
				DisplayMsg('Promote Event', 'This event has been unpromoted on event page.');
			} else {
				$('#events_manage_link_promote').text('Unpromote this event');
				DisplayMsg('Promote Event', 'This event has been promoted on event page.');
			}
		}
	});
}

function CreateContest(key) {
	$.ajax({
		url: '/',
		data: 'events/'+key+'/action/create_contest/xhr',
		success: function(msg){
			$('#dialog_box').dialog('option', 'title', 'Create a contest for this event');
			$('#dialog_box').html(msg);
			$('#dialog_box').dialog('option', 'buttons', { "Create a contest": function() { SubmitContest(); return false; }, "Cancel": function() { $(this).dialog('close'); } });
			$('#dialog_box').dialog('option', 'bgiframe', true);
			$('#dialog_box').dialog('option', 'width', 595);
			$('#dialog_box').dialog('option', 'height', 'auto');
			$('#dialog_box').dialog('open');
			UpdateInterface();
		}
	});
}

function AddAnswer() {
	$('#answers_list input:last').after('<input type="text" name="answers[]" maxlength="255"/>');
}

function DisplayContest(key) {
	$.ajax({
		url: '/',
		data: 'events/'+key+'/action/play_contest/xhr',
		success: function(msg){
			$('#dialog_box').html(msg);
			if ($('#play_contest').length > 0) {
				$('#dialog_box').dialog('option', 'buttons', { "Participe !": function() { SubmitPlayContest(); return false; }, "Cancel": function() { $(this).dialog('close'); } });
			} else {
				$('#dialog_box').dialog('option', 'buttons', { "Close": function() { $(this).dialog('close'); } });
			}
			$('#dialog_box').dialog('option', 'title', 'Win free tickets for this event !');
			$('#dialog_box').dialog('option', 'bgiframe', true);
			$('#dialog_box').dialog('option', 'width', 595);
			$('#dialog_box').dialog('option', 'height', 'auto');
			$('#dialog_box').dialog('open');
			UpdateInterface();
		}
	});
}

function SubmitSearch() {
	$.address.value($('#search_input').val()+'/search');
}