
programfilter = '';
useremail = '';

function omrScenSelect() {
	$('select#nav-omr-select').show(0);
	$('select.nav-scen-select').hide(0);
	$('select#nav-scen-select-' + $('select#nav-omr-select').val()).show(0);
}

function getOmrId() {
	if ($('select#nav-scen-select-' + $('select#nav-omr-select').val()).size() == 0) return '';
	return $('select#nav-omr-select').val();
}

function getScenId() {
	var omr = getOmrId();
	if (omr == '') return '';
	return $('select#nav-scen-select-' + omr).val();
}

$(document).ready(function() {

	syncScheme();

	$('input[suggest]').ready (function () {

		omrScenSelect();

		$('select#nav-omr-select').change(function() {
			omrScenSelect();
		});

		$('input[suggest]').each (function () {
			if ($(this).attr('id')) {
				$(this)
				.keydown (function (e) {

					if (($(this).val() == '') || ((e.which != 38) && (e.which != 40))) {
						return;
					}

					$(this).attr('suggest_position', '-1');
					$(this).attr('suggest_max_positions', '0');

					$("div#" + id + "-suggestions li").each (function() {
						if ($(this).hasClass('marked')) {
							$(this).removeClass('marked');
							if (e.which == 38) {
								$(this).prev().addClass('to-be-marked-for-suggestion');
							} else if (e.which == 40) {
								$(this).next().addClass('to-be-marked-for-suggestion');
							}
						}
					});
					if ($("div#" + id + "-suggestions li.to-be-marked-for-suggestion").size() == 0) {
						if (e.which == 38) {
							$("div#" + id + "-suggestions li:last").addClass('to-be-marked-for-suggestion');
						} else {
							$("div#" + id + "-suggestions li:first").addClass('to-be-marked-for-suggestion');
						}
					}

					$("div#" + id + "-suggestions li.to-be-marked-for-suggestion")
						.removeClass('to-be-marked-for-suggestion')
						.addClass('marked');

				})
				.keyup (function (e) {

					if (($(this).val() != '') && (e.which == 13)) {
						$("div#" + id + "-suggestions li.marked:first a:first").each(function() {
							document.location.href = $(this).attr('href');
						});
						return;
					}

					if ((e.which == 13) || (e.which == 38) || (e.which == 40)) return;

					$.ajax({
						type: "GET",
						data: ({
							q: $(this).val(),
							id: $(this).attr('id')
						}),
						url: $(this).attr ('suggest'),
						success: function (data) {
							data = data.split('&');
							id = data[0];
							suggestions = new Array();
							suggestindex = -1;

							maxSuggestions = -1;
							if ($("#" + id).attr('suggest_max') > 0) maxSuggestions = parseInt($("#" + id).attr('suggest_max'));

							for (i = 1; i < data.length; i++) {

								d = data[i].split('=')
								if (d.length == 2) {
									if (d[0] == 'title') {
										suggestindex++;
										suggestions[suggestindex] = new Array();
									}
									if (suggestindex >= 0) {
										suggestions[suggestindex][d[0]] = decodeURIComponent(d[1].split('+').join(' '));
									}
								}

							}
							if ($("div#" + id + "-suggestions").size() == 0) {
								$("body").append('<div id="' + id + '-suggestions" class="suggestions"></div>');
								$("div#" + id + "-suggestions").fadeOut(0);
							}
							html = '<ul>';
							suggestioncounter = 0;
							for (i = 0; i < suggestions.length; i++) {
								suggestion = suggestions[i];
								if (suggestion['title']) {
									if (suggestion['url']) {
										html += '<li class="';
										if (suggestioncounter == 0) {
											html += 'first-suggestion ';
										}
										if ((suggestioncounter == suggestions.length - 1) || (suggestioncounter == maxSuggestions - 1)) {
											html += 'last-suggestion ';
										}
										html += '"><span><a href="' + suggestion['url'] + '">' + suggestion['title'] + '</a></span></li>';
										suggestioncounter++;
										if (suggestioncounter == maxSuggestions) break;
									}
								}
							}
							html += '</ul>';
							if (suggestioncounter == 0) {
								$("div#" + id + "-suggestions").fadeOut();
								if ($("#" + id).val() == '') {
									$("#" + id)
										.removeClass('no-suggestions');
								} else {
									$("#" + id)
										.addClass('no-suggestions');
								}
							} else {
								$("#" + id)
									.removeClass('no-suggestions');
								$("div#" + id + "-suggestions")
									.css({position: "absolute", left: $("#" + id).offset().left, top: $("#" + id).offset().top + $("#" + id).outerHeight() })
									.html(html)
									.fadeIn();
								$("div#" + id + "-suggestions ul li").each(function() {
										$(this)
										.hover(function() {
											$(this).parent().children('li').each(function() {
												$(this).removeClass('marked');
											});
											$(this).addClass('marked');
										});
								});
							}
						}
					});


				});
				$(this).blur(function() {
					$("#" + id).removeClass('no-suggestions');
					$("div#" + $(this).attr('id') + "-suggestions").each(function () {
						$(this).fadeOut();
					});
				});
			}
		});
	});




	$("input#sendnewsletter").click(function() {
		email = $('input#newslettermail').val();
		$.ajax({
			url: '/malmo.php',
			type: 'POST',
			data: {'newsletter': email},
			dataType: 'text',
			timeout: 2000,
			success: function(data) {
				if (data == 'invalid') {
					alert ('Du angav inte en korrekt e-postadress. Försök igen!');
				} else {
					$('input#newslettermail').val('')
					$("#newsletter-signup").css ('display', 'none');
					alert('Tack för att anmälde dig till vårat nyhetsbrev!');
				}
			},
			error: function() {
				$('input#newslettermail').val('')
				$("#newsletter-signup").css ('display', 'none');
				alert('Ett fel uppstod - försök anmäla dig igen senare.');
			}
		});
	});

	$("input#filterprogrambutton").click(function() {
		programfilter = '';
		$("input.filterprogramcheckbox:checked").each(function() {
			if (programfilter != '') programfilter += ',';
			programfilter += $(this).attr('id').substring(3);
		});
		goto = '?';
		if ($(document).getUrlParam('d')) {
			goto += 'd=' + $(document).getUrlParam('d') + '&'
		}
		if ($(document).getUrlParam('h')) {
			goto += 'h=' + $(document).getUrlParam('h') + '&'
		}
		goto += 'c=' + programfilter;
		goto += '&o=' + getOmrId() + '&s=' + getScenId();
		document.location.href = goto;
	});

	$('input#addschemeuser').click(function() {
		useremail = $('input#addschemeuseremail').val();
		$('input#addschemeuseremail').val('')
		$.ajax({
			url: '/malmo.php',
			type: 'POST',
			data: {'addemail': useremail},
			dataType: 'text',
			timeout: 2000,
			success: function(data) {
				if (data == 'error') {
					alert('You did not supply a correct e-mail address.');
				} else if (data == 'exists') {
					alert('User already exists, please login with your password!');
				} else {
					$("#add-explain").css ('display', 'none');
					$.cookie('schemeuser', useremail, { path: '/', expires: 10 });
					$.cookie('schemepassword', data, { path: '/', expires: 10 });
					$.cookie('scheme', '', { path: '/', expires: 10 });
					$.cookie('schemeremove', '', { path: '/', expires: 10 });
				}
				syncScheme();
			},
			error: function() {
				$("#add-explain").css ('display', 'none');
				alert('Error: Could not add you as an user. Try again in a couple av minutes.');
			}
		});
	});

	$('input#schemelogin').click(function() {
		user = $('input#schemeuser').val();
		password = $('input#schemepassword').val();
		$('input#schemeuser').val('');
		$('input#schemepassword').val('');
		$.cookie('schemeuser', user, { path: '/', expires: 10 });
		$.cookie('schemepassword', '', { path: '/', expires: 10 });
		$.cookie('scheme', '', { path: '/', expires: 10 });
		$.cookie('schemeremove', '', { path: '/', expires: 10 });
		$.ajax({
			url: '/malmo.php',
			type: 'POST',
			data: {'schemeuser': user, 'schemepassword': password},
			dataType: 'text',
			timeout: 2000,
			success: function(data) {
				if (data == 'error') {
					alert('Login username or password error. Please try again!');
				} else {
					$("#login-explain").css ('display', 'none');
					$.cookie('schemepassword', data, { path: '/', expires: 10 });
					syncScheme();
				}
			},
			error: function() {
				alert('Could not log in at this moment, please try again in a couple of minutes.');
			}
		});
	});

});

Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}

function loginBox(link) {
	important.activate (link, $('#login-explain'));
	important.deactivate (0, $('#add-explain'));
}

function addToScheme(id) {
	return;
	boxlinkid = id;
	if (($.cookie('schemepassword') == null) || ($.cookie('schemeuser') == null) || ($.cookie('schemepassword') == '') || ($.cookie('schemeuser') == '')) {
		important.activate ($('#add-link-' + boxlinkid)[0], $('#add-explain'));
	} else {
		$.cookie('scheme', $.cookie('scheme') + ',' + id, { path: '/', expires: 10 });
		schemeremove = ',' + $.cookie('schemeremove') + ',';
		$.cookie('schemeremove', schemeremove.replace(',' + id + ',', ','), { path: '/', expires: 10 });

		$("#add-to-scheme-" + id).hide("fast", function() {
			$(this).parent().children("div.remove-from-scheme").css({visibility:"visible", display:"block"}).show(0);
		});
		syncScheme();
	}
}

function removeFromMy(id) {
	$("li#my-scheme-" + id).hide("fast");
	removeFromScheme(id);
}

function removeFromScheme(id) {
	return;
	$("#remove-from-scheme-" + id).hide("fast", function() {
		$(this).parent().children("div.add-to-scheme").css({visibility:"visible", display:"block"}).show(0);
	});
	scheme = ',' + $.cookie('scheme') + ',';
	$.cookie('scheme', scheme.replace(',' + id + ',', ','), { path: '/', expires: 10 });
	$.cookie('schemeremove', $.cookie('schemeremove') + ',' + id, { path: '/', expires: 10 });
	syncScheme();
}

function my() {
	if (($.cookie('schemeuser') != null) && ($.cookie('schemeuser') != '') && ($.cookie('schemepassword') != null) && ($.cookie('schemepassword') != '')) {
		document.location.href="/malmo.php?my=";
	} else {
		important.activate ($('a#my-link')[0], $('#add-explain'));
	}
}

function syncScheme() {
	return;
	if (($.cookie('schemeuser') != null) && ($.cookie('schemeuser') != '') && ($.cookie('schemepassword') != null) && ($.cookie('schemepassword') != '')) {
		$.ajax({
			url: '/malmo.php',
			type: 'POST',
			data: {'user': $.cookie('schemeuser'), 'password': $.cookie('schemepassword'), 'scheme': $.cookie('scheme'), 'schemeremove': $.cookie('schemeremove')},
			dataType: 'text',
			timeout: 2000,
			success: function(data) {
				data = data.replace(/^\s+|\s+$/g, '');
				$.cookie('scheme', data, { path: '/', expires: 10 });
				$.cookie('schemeremove', ',', { path: '/', expires: 10 });
				if (data == '') {
					$("span#scheme-counter").html('00');
					$("span#logout-text").html('Logga ut ' + $.cookie('schemeuser'));
				} else {
					nr = data.split(',').length;
					if (nr < 10) nr = '0' + nr;
					$("span#scheme-counter").html(nr);
					$("span#logout-text").html('Logga ut ' + $.cookie('schemeuser'));
				}
				fixLoginViewStuff();
			}
		});
	} else {
		$("span#scheme-counter").html('00');
		$("span#logout-text").html('');
	}
	fixLoginViewStuff();
}

function fixLoginViewStuff() {
	if ($("span#scheme-counter").html() == '00') {
		if ($("h1#my-scheme-title").length > 0) {
			if ($('h1#my-scheme-title span').html() == 'Mitt festivalschema') {
				important.activate ($('h1#my-scheme-title span')[0], $('#empty-scheme'));
			}
		}
	}
	$('.add-or-remove-scheme').each(function() {
		id = $(this).attr('id');
		if (id.substring(0, 1) == 'a') id = id.substring(14, 100);
		if (id.substring(0, 1) == 'r') id = id.substring(19, 100);
		if (($.cookie('scheme') != null) && ($.cookie('scheme').split(',').in_array(id))) {
			if ($(this).hasClass('add-to-scheme')) {
				$(this).hide("fast", function() {
					$(this).parent().children("div.remove-from-scheme").css({visibility:"visible", display:"block"}).show(0);
				});
			}
		} else {
			if ($(this).hasClass('remove-from-scheme')) {
				$(this).hide("fast", function() {
					$(this).parent().children("div.add-to-scheme").css({visibility:"visible", display:"block"}).show(0);
				});
			}
		}
	});
}

function logout() {
	$.cookie('scheme', '', { path: '/', expires: 10 });
	$.cookie('schemeremove', '', { path: '/', expires: 10 });
	$.cookie('schemeuser', '', { path: '/', expires: 10 });
	$.cookie('schemepassword', '', { path: '/', expires: 10 });
	syncScheme();
}

function fbs_click() {
	u=location.href;
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

function stopRKey(evt) {
	var evt = (evt) ? evt : ((event) ? event : null);
	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
	if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
}

document.onkeypress = stopRKey;

$(document).ready(function() {
});

