/*global $, window, setCookie, COMMON, gettext */
var op = window.op || {};

$('.autologin_delete').click(function(e) {
	var target = $(this);
	var url = target.attr('href');
	$.get(url);
	target.parent().remove();
	return false;
});

op.content = function() {
	var articles = $('#columns .content .articles');
	var menu = $('#columns .content ul.menu a');
	var selected = menu.filter('a.selected');

	if(selected.length != 1) {
		menu.removeClass('selected');
		if(this.menu !== undefined) {
			selected = this.menu.first().addClass('selected');
		}
	}

	var showSection = function() {
		var section = selected.attr('rel');
		articles.hide();
		articles.filter('.articles.' + section).show();
	};
	showSection();

	menu.click(function() {
		var current = $(this);

		if(current.attr('rel') == selected.attr('rel')) {
			return false;
		}

		menu.removeClass('selected');
		selected = current.addClass('selected');

		showSection();

		return false;
	});
};

$(document).ready(function() {
	$('#carousel ul').cycle({
		timeout : 24000,
		speed : 150,
		next : '#carousel a.arrow.right',
		prev : '#carousel a.arrow.left'
	});
	
	op.content();

	$("#login").hover(function() {
		$("#autologins").show();
	}, function() {
		$("#autologins").hide();
	});
	function show_alert(text) {
		$('#loading_dialog').text(text);
		$("#loading_dialog").dialog({
			modal : true,
			width : 500,
			buttons : {
				Ok : function() {
					$(this).dialog("close");
				}
			}
		});
		$("#loading_dialog").dialog('open');
	}

	function validate(formData, jqForm, options) {
		var form = jqForm[0];
		if(!form.pool_name.value || !form.password.value) {
			show_alert(gettext('Please enter a value for both Pool Name and Password'));
			return false;
		}
	}

	function login_success(data) {
		if (data.status === 'REDIRECT') {
			location.href = data.detail;
			return;
		} else {
			var message = COMMON.interpretLoginResult(data.status, data.detail, data.data);
			
			if (message !== '') {
				show_alert(message);
			}
		}
	}

	function login_error(jqXHR, textStatus, errorThrown) {
		alert('error');
	}

	var options = {
		beforeSubmit : validate,
		success : login_success,
		dataType : 'json',
		error : login_error
	};

	$('#login').submit(function() {
		$(this).ajaxSubmit(options);
		return false;
	});
});

