// JavaScript Document
var formFadeTimeoutId;
var regionHelper;

/**
 * Default value of the submit button
 * 
 * @var string
 */
var submitdefaultValue;

$(document).ready(function(){
	fadeFormErrors();
	initTopnav();
	initTablerows();
	initToggleDiv('a.toggle, area.toggle, input.toggle');//pass where to apply visibility toggle
	initPopup('a.popupwindow, area.popupwindow, input.popupwindow');//pass where to apply visibility toggle
	initPopupselector();
});

function initPopupselector() {
	$('a.popupwindow').unbind('click');
	$('a.popupwindow').click(function(){regionHelper = $(this).parent().find('select, input');});
	initPopup('a.popupwindow');
}

$.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};

function globalMessage(msg)
{
	$('body').append("<div class='globalMessage'>" + msg + "</div>");
	var globalTimeoutId = setTimeout("$('div.globalMessage').animate({opacity:'hide', height:'hide'}, 500)", 2500);
}

function initTopnav()
{
	$('#banner ul li').hover(
			function() { $('ul', this).slideDown(100); },
			function() { $('ul', this).slideUp(100); });
}

function initTablerows()
{
	$('tbody tr').hover(
			function() { $(this).addClass('mouseover'); },
			function() { $(this).removeClass('mouseover'); });
}

function initPopup(domChunk)
{
	$(domChunk).click(function(){
		return windowOpen(this);
	});	
}

function windowOpen(el)
{
	var a = el.href;
	var width	= a.match("width=([0-9]+)");
	var height	= a.match("height=([0-9]+)");
	var params	= "resizable=1,toolbar=0,location=0,status=1,scrollbars=1";
			
	if (width.length) params += "," + width[0];
	if (height.length) params += "," + height[0];
	window.open(a.substring(0, a.indexOf("?")), "", params);
	return false;
}

function initToggleDiv(domChunk)
{
	$(domChunk).unbind('click');
	$(domChunk).click(function(){
		var current = this.href || this.alt;
		current	= current.substring(current.lastIndexOf('#'));
		
		$(domChunk).each(function(){
			var a = $(this).attr('href') || $(this).attr('alt');
			a	= a.substring(a.lastIndexOf('#'));
			if (current != a) {
				$(a).slideUp('slow');
				$(this).removeClass('toggleselected');
			}
		});
		
		$(current).slideToggle('slow');
		$(this).toggleClass('toggleselected');
		
		return false;
	});	
}

function alertMessages(messages)
{
	var msg	= "";
	for(var a = 0; a < messages.length; a++){
		if (messages[a]) {
			msg	+= messages[a] + "\n";
		}
	}
	
	if (msg) {
		alert(msg);
	}
}

function formErrors(form, data)
{
	$('ul.form-errors').remove();
	
	var msg	= "<ul class='form-errors'>";
	
	if (data == '[object Object]') {
		for (elem in data) {
			msg += "<li><b>" + elem + "</b>";
			msg += "<ul class='errors'>";

			for (err in data[elem]) {
				if (data[elem][err] == '[object Object]') {
					for (suberr in data[elem][err]) {
						msg += "<li>" + data[elem][err][suberr] + "</li>";
					}
				} else {
					msg += "<li>" + data[elem][err] + "</li>";
				}
			}

			msg += "</ul></li>";
		}
	} else {
		msg += "<li>" + data + "</li>";
	}
	
	msg	+= "</ul>";
	
	$(form).prepend(msg);
	$(".form-errors").hide();
	$(".form-errors").show(250);
	fadeFormErrors();
}

function fadeFormErrors()
{
	clearTimeout(formFadeTimeoutId);
	formFadeTimeoutId	= setTimeout("$('ul.form-errors').animate({opacity:'hide', height:'hide'}, 500)", 10000);
}

function clearSearchForm(submit)
{
	if ($('form.searchform #displayno')) {
		var displayno = $('form.searchform #displayno').val();
	}

	$('form.searchform :input[type=text]').val('');
	$('form.searchform :select').attr('selectedIndex', 0);

	if (displayno) {
		$('form.searchform #displayno').val(displayno);
	}

	if (submit) {
		$('form.searchform #fieldset-submit input').click();
	}
}

function confirmRedirect(msg, url)
{
	var answer = confirm(msg);
	if (answer){
		window.location = url;
	} else{
		return false;
	}

}

function objToString(o) {
    var s = '{\n';
    for (var p in o)
        s += '    ' + p + ': ' + o[p] + '\n';
    return s + '}';
}

/**
 * AJAX form submission, requesting JSON response
 *
 * All responses look for the following JSON keys:
 * 'status'			=> REQUIRED "success"|"fail"
 * 'message'		=> OPTIONAL Object of strings which proxies to alertMessages()
 * 'formMessage'	=> OPTIONAL Object of Zend_Form errors which proxies to formErrors()
 * 'redirect'		=> OPTIONAL URL to redirect to on status success
 * 'load'			=> OPTIONAL Load HTML from a remote file and inject it into the DOM on status success
 * 
 * The load option which proxies to jQueries load() method is an object in itself requiring two options:
 * 'element'	=> REQUIRED Containing element to replace the HTML content
 * 'url'		=> REQUIRED The URL of the HTML page to load.
 *
 * @param  [object HTMLFormElement] form
 * @return boolean false To prevent a HTTP form submission
 */
function submitForm(form)
{
	// Submit the form to the action specified in the forms action attrib
	$(form).ajaxSubmit({
		// Set the AJAX data response to request
		dataType:  'json',
		// Set some actions before the actual submission takes place
		beforeSubmit: function(a,f,o) {
			// Set the submit button to disabled
			submitButtonToggle(form, true);
		},
		// Get the AJAX response
		success: function(data, status) {
			// If the JSON request is an error, there was a problem.
			// Lets alert the user
			if (typeof data == "error") {
				console.warn("error!", status);	
			}
			
			// Check if there were any form messages
			// If there are, lets display them
			if (data.formMessage) {
				formErrors(form, data.formMessage);
			}
			
			switch (data.status) {
				// All is well, and the form was successfully processed
				case "success":
					// If there was a redirect var, lets send the user to that,
					// Otherwise, check if there was any replacement HTML, if not,
					// just reload the page
					try {
						if (data.redirect) {
							window.location	= data.redirect;
						} else if (data.load) {
							if (!data.load.element) {
								throw "No element";
							}
							$(data.load.element).load(data.load.url);
						}
						
						// We also want to add an extra method, in case
						// we want to add any extra functionality to a specific page
						// By adding the method filetransfer_response in a try/catch,
						// if it exists, execute it, otherwise, carry on
						try {
							submitForm_response(form, data);
						} catch (e) {
							//window.location.reload(false);
						}
						
					} catch(e) {
						window.location.reload(false);
					}
				break;
				
				case "fail":
					// data.error is a thrown error from the action
					// Lets alert it to the user
					if (!data.formMessage && data.message) {
						alertMessages(data.message);
					}
				break;
			}
			
			// We are done processing, so lets re-initialize the
			// submit button, restoring it to its original state
			submitButtonToggle(form, false);
		}
	});

	return false;
}

/**
 * Toggles the submit button to disabled or
 * enabled.
 *
 * @param  [object HTMLFormElement] form
 * @param  boolean state TRUE is disabled, FALSE is to enable
 * @return void
 */
function submitButtonToggle(form, state)
{
	if (!submitdefaultValue) {
		submitdefaultValue	= $(form).find('input[type=submit]').val();
	}
	$(form).find('input[type=submit]').val(state ? 'Please Wait...' : submitdefaultValue).attr('disabled', state);
}

function register(id)
{
	if (regionHelper) {
		$(regionHelper).val(id);
	}
	
	regionHelper = null;
}

/**
 * Preloads images
 *
 * @return void
 */
jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

/**
 * Auto Logout
 *
 * @return void
 */
var t;

function destroySession() {
	$.getJSON('/login/destroy', function(data){
		if (data.message.status == 'OK') {
			clearTimeout(t);
			tb_show('Login', '/login/index/popup/true&TB_iframe=true', '');
		}
	});
}

$(document).ready(function() {
	if (!$('#login').length) {
		t = setInterval(destroySession, 1800000);
	}
});
