var $j = jQuery.noConflict();
//
//// Var to keep track of dynamically loaded files,
// to avoid loading the same file more than once
var loaded_files = [];

/**
*	Site-wide preparations
**/
$j(document).ready(function() 
{
	// Hide "filter" select just below menu in IE6
	// if user hovers on "Settings" menu item
	/*
	if ($.browser.msie && $.browser.version == '6.0')
	{
		$('a#submenu_settings').mouseover(function()
		{
			$('.page_filter select').css('visibility', 'hidden');
		});
		$('a#submenu_settings').mouseout(function()
		{
			$('.page_filter select').css('visibility', 'visible');
		});
	}
	*/

	// Row highlight rollover for list tables
	$j('table.list tr').mouseover(function()
	{
		$j(this).addClass('highlight');
	});
	$j('table.list tr').mouseout(function()
	{
		$j(this).removeClass('highlight');
	});

	// Clear period links - works on #<prefix, #<prefix>_start and #<prefix>_end
	$j('a.clear_date').click(function()
	{
		var prefix = $j(this).get(0).id.replace('clear_', '');
		$j('#' + prefix + ', #' + prefix + '_start, #' + prefix + '_end').val('');
		return false;
	});

	// Add event handler for 'recent pages' list
	$j('a#toggle_page_list').click(function()
	{
		$j('#recent_pages_box').slideDown();
		
		// Add timer to slide up automatically
		$j('#recent_pages_box').bind('mouseleave', function()
		{
			$j('#recent_pages_box').oneTime('1s', function()
			{
				$j('#recent_pages_box').fadeOut('slow');
			});
		});
		
		return false;
	});

});

// -------------------------------------------------------------------

/**
*	LoadBlock
*
*	- url: URL to load from
*	- target: element to load HTML into
*	- callback: function to execute after loading
**/
function LoadBlock(url, target, callback)
{
	if(typeof $ == "undefined") {
            var $ = jQuery.noConflict();
        }

        
        $j.get(WEB_ROOT + url, function(resp)
	{
		$j('#' + target).html(resp).show();
		
		if (callback)
		{
			callback();
		}
	});
}

// -------------------------------------------------------------------

/**
*	LoadNotes
*
*	Load the list of notes for a given entity.
*
*	- state: 'summary' or 'all'
**/
function LoadNotes(state)
{
	// Exit if there's no notes box
	if ($j('#box_notes').length == 0)
	{
		return;
	}

	var type = $j('#box_notes').attr('note-type');
	var parent_id = $j('#box_notes').attr('parent-id');
	var url = WEB_ROOT + '/note/view/' + state + '/' + type + '/' + parent_id;
	$j.get(url, function(resp)
	{
		$j('#box_notes').html(resp).show();

		// Event handler for 'add note' button
		$j('.btn_add_note').click(function()
		{
			LoadNoteForm();
		});
		
		// Event handler for 'delete note' link
		$j('a.remove_note').click(function()
		{
			if (confirm('Weet je zeker dat je deze notitie wilt verwijderen?'))
			{
				var id = $j(this).attr('note-id');
				$j.post(WEB_ROOT + '/note/remove', {id: id}, function(resp)
				{
					if (resp == 'OK')
					{
						// Remove row with note & refresh striping
						$j('#row_' + id).fadeOut(function() 
						{
							$j('#row_' + id).remove();
							ResetListStriping('notes_list');
						});
					}
					else
					{
						$j('#box_notes #process_error').html(resp).show();
					}
				});
			}
			return false;
		});
		
		// Set up event handlers for block fold/collapse
		SetupBlockEventHandlers();
	});
}

// -------------------------------------------------------------------

/**
*	LoadNoteForm
*
*	Load the form for adding a note.
**/
function LoadNoteForm()
{
	var type = $j('#box_notes').attr('note-type');
	var parent_id = $j('#box_notes').attr('parent-id');
	var url = WEB_ROOT + '/note/add/' + type + '/' + parent_id;
	var target = 'box_notes';
	LoadBlock(url, target, function() 
	{
		// Cancel button
		$j('#btn_cancel_note').click(function()
		{
			LoadNotes('all');
		});

		// Ajax form
		$j('#form_note').ajaxForm(
		{
			beforeSubmit: CheckNoteForm,
			success: function(msg)
			{
				if (msg == 'OK')
				{
					LoadNotes('all');
				}
				else
				{
					$j('#process_error').html(msg).show();
				}
			}
		});

		// Title link
		$j('.box_title a').click(function()
		{
			LoadNotes();
			return false;
		});
		
		HighlightActiveInput();

		// Focus first field
		$j('#text').focus();
	});	
}

// -----------------------------------------------------------------------

/**
*	Validates the note form
**/
function CheckNoteForm() 
{
	// Hide feedback
	$j('.feedback').hide();

	var errors = new Array();

	// Check text
	if (!CheckNotEmpty('text')) 
	{
		errors.push(CreateValidationErrorObject('text', 'Er is geen tekst ingevuld.'));
	}	

	// Check errors
	if (errors.length == 0)
	{
		return true;
	}
	else
	{	
		// Validation failed
		ShowValidationErrors(errors);
		return false;
	}
}

// -----------------------------------------------------------------------

/**
*	Validates the email form
**/
function CheckEmailForm() 
{
	// Hide feedback
	$j('.feedback').hide();

	var errors = new Array();

	// Check subject
	if (!CheckNotEmpty('subject')) 
	{
		errors.push(CreateValidationErrorObject('subject', 'Er is geen onderwerp ingevuld.'));
	}	

	// Check text
	if (!CheckNotEmpty('text')) 
	{
		errors.push(CreateValidationErrorObject('text', 'Er is geen tekst ingevuld.'));
	}	

	// Check errors
	if (errors.length == 0)
	{
		return true;
	}
	else
	{	
		// Validation failed
		ShowValidationErrors(errors);
		return false;
	}
}

// -------------------------------------------------------------------

/**
*	AttachEmailEventHandler
*
*	Adds an event handler for sending email to a.send_email.
**/
function AttachEmailEventHandler()
{
	/*
	// Event handler for 'send email' links
	$('a.send_email').click(function() 
	{
		ShowEmailLightbox(this);
		return false;
	});
	*/
}

// -------------------------------------------------------------------

/**
*	ShowEmailLightbox
*
*	Shows a lightbox in which the user can send an email to someone.
**/
function ShowEmailLightbox(link_obj)
{
	// Get type of note and parent id
	var data = {
		note_type: $(link_obj).attr('note-type'),
		note_parent: $(link_obj).attr('note-parent'),
		name: $(link_obj).attr('recipient'),
		email: $(link_obj).html()
	};
	
	// Load form
	$j.post(WEB_ROOT + '/email/form', data, function(resp)
	{
		$j('#emailbox').html(resp).jqm({overlay: 50}).jqmShow();
		
		// Debug: fill fields
		//$('#subject').val('Test onderwerp');
		//$('#text').val('Test tekst, bla bla bla');

		// Function for closing lightbox
		var close_func = function() 
		{
			$j('a.close').click(function()
			{
				$j('#emailbox').jqmHide();
				return false;
			});
		};
		
		// Ajax form
		$j('#form_email').ajaxForm(
		{
			beforeSubmit: CheckEmailForm,
			success: function(resp)
			{
				$j('#emailbox').html(resp);

				// Reload notes 
				LoadNotes('summary');

				close_func();				
			}
		});

		close_func();

		HighlightActiveInput();
		
		$j('#subject').focus();
	});
}

// -------------------------------------------------------------------

/**
*	SetupBlockEventHandlers
*
*	Adds event handlers to fold/collapse blocks.
**/
function SetupBlockEventHandlers()
{
	// Clear all event handlers first
	$j('.box_title a').unbind();

	// Block fold/collapse event handlers
	$j('.box_title a').click(function()
	{
		var box_title = this.parentNode;
		var box_id = box_title.parentNode.id;

		// Find out if we're folding or collapsing
		var action = 'collapse';
		if ($j(box_title).hasClass('box_title_open'))
		{
			action = 'fold';
		}
		
		// Fold: hide all, show summary, hide toolbar
		if (action == 'fold')
		{
			$j('#' + box_id + ' div.box_toolbar').fadeOut('fast');
			$j('#' + box_id + ' div.box_all').fadeOut('fast', function()
			{
				// Toggle "open" class on title div
				$j(box_title).toggleClass('box_title_open');

				$j('#' + box_id + ' div.box_summary').fadeIn('fast');
			});
		}

		// Collapse: show all, hide summary, show toolbar
		if (action == 'collapse')
		{
			// Toggle "open" class on title div
			$j(box_title).toggleClass('box_title_open');

			$j('#' + box_id + ' div.box_toolbar').fadeIn('fast');
			$j('#' + box_id + ' div.box_summary').fadeOut('fast', function()
			{
				$j('#' + box_id + ' div.box_all').fadeIn('fast');
			});
		}
		
		return false;
	});

	// Blur links on click
	$j('a, button').click(function()
	{
		if (this.blur)
		{
			this.blur();
		}
	});
}

// -------------------------------------------------------------------

// Helper for calendars
function SetCalendarPeriod(input) 
{ 
	// Get base name (cut off _start/_end)
	var name = input.id.replace('_start', '');
	name = name.replace('_end', '');
	
    return {minDate: (input.id == name +'_end' ? $j('#' + name + '_start').datepicker('getDate') : null), 
        maxDate: (input.id == name + '_start' ? $j('#' + name + '_end').datepicker('getDate') : null)}; 
} 

// -------------------------------------------------------------------

/**
*	HighlightActiveInput
*
*	Adds event handlers to all inputs with class 'text', that adds 
*	the class 'active-input'to them onfocus and removes it onblur.
**/
function HighlightActiveInput()
{
	// Target all inputs, but not selects on IE
	var inputs = 'input.text, select.text, textarea.text';
	if ($j.browser.msie)
	{
		inputs = 'input.text, textarea.text';
	}
	$j(inputs).each(function()
	{
		$j(this).focus(function()
		{
			$j(this).addClass('active-input');
		});
		$j(this).blur(function()
		{
			$j(this).removeClass('active-input');
		});
	});
}

// -------------------------------------------------------------------

/**
*	$$
*
*	Returns an object reference
*	for the given object id
**/
function $$(obj_id)
{
	return document.getElementById(obj_id);
}

// -------------------------------------------------------------------

/**
*	redirect
*
*	Redirects to the given page, with WEB_ROOT
**/
function redirect(url)
{
	window.location = WEB_ROOT + url;
}

// -------------------------------------------------------------------

/**
*	log
*
*	Logs to the console
**/
function log(str, to_div)
{
	if (window.console)
	{
		console.log(str);
	}
}

// -------------------------------------------------------------------

/**
*	ParseDate
*
*	Converts a string date (DD-MM-YYYY or YYYY-MM-DD) to Date object.
**/
function ParseDate(str)
{
	var parts = str.split('-');
	var d = new Date;
	d.setSeconds(0);
	d.setMinutes(0);
	d.setHours(0);
	
	if (parts[0].length == 4)
	{
		// YYYY-MM-DD 
		d.setDate(parts[2]);
		d.setMonth((parts[1] - 1));
		d.setFullYear(parts[0]);
	}
	else
	{
		// DD-MM-YYYY
		d.setDate(parts[0]);
		d.setMonth((parts[1] - 1));
		d.setFullYear(parts[2]);
	}
	return d;
}

// -------------------------------------------------------------------

/**
*	LoadFile
*
*	Loads a Javascript file. Filename is prefixed with
*	web root and JS file subdir (assets/js).
**/
function LoadFile(filename, async)
{
	if (loaded_files.hasValue(filename))
	{
		return;
	}

	var opt = {};
	
	// Load async by default, unless indicated otherwise
	opt.async = false;
	if (async)
	{
		opt.async = true;
	}
	
	// Add timestamp to URL to ensure reload
	timest = new Date;
	opt.url = WEB_ROOT + '/assets/js/' + filename + '?=' + timest.getTime();
	
	opt.type = 'GET';
	opt.success = function(resp)
	{
		var ref = document.createElement('script');
		ref.setAttribute('type', 'text/javascript');
		ref.text = resp;
		document.getElementsByTagName('head')[0].appendChild(ref);
		
		loaded_files.push(filename);
	}
	$j.ajax(opt);	
}

// -----------------------------------------------------------------------

/**
*	Flashes feedback for 2 secs.
**/
function FlashFeedback(msg, target)
{
	if (!target)
	{
		target = 'feedback';
	}

	$j('#' + target).html(msg).fadeIn();
	$j('#' + target).oneTime('2s', function() {
		$j(this).fadeOut();
	});
}

// -----------------------------------------------------------------------

/**
*	Scroll up parent page
**/
function ScrollParentPage()
{
	if (window.parent && window.parent.ScrollToTop)
	{
		window.parent.ScrollToTop();
	}
}

// -----------------------------------------------------------------------

/**
*	ResetListStriping
*
*	Iterates over the given table and resets the "odd"/"even" row classes.
*
*	- obj_id: ID of table object
**/
function ResetListStriping(obj_id)
{
	if (!$$(obj_id))
	{
		alert('ResetListStriping: There is no object with ID "' + obj_id + '".');
		return;
	}
	
	var row_class = 'odd';
	$j('#' + obj_id + ' tbody tr').each(function()
	{
		var opposite = (row_class == 'odd' ? 'even' : 'odd');
		$j(this).removeClass(opposite).addClass(row_class);
		row_class = (row_class == 'odd' ? 'even' : 'odd');
	});
}

// -----------------------------------------------------------------------

/**
*	AddChangeStatusHandler
*
*	Adds an event handler to the change status links.
**/
function AddChangeStatusHandler()
{
	// Event handler for archive links
	$j('a.change_status_link').click(function()
	{
		var type = $j(this).attr('itemtype');
		var id = $j(this).attr('itemid');
		var cur_status = $j(this).attr('curstatus');
		var link_obj = this;
		$j.post(WEB_ROOT + '/change-status', {type: type, id: id, cur_status: cur_status}, function(resp)
		{
			if (resp.msg == 'OK')
			{
				$(link_obj).text(resp.status_nl);
				$(link_obj).attr('curstatus', resp.status);
			}
			else
			{
				alert(resp.msg);
			}
		}, 'json');
		return false;
	});
}

// ----------------------------------------------

/**
*	Add in_array function to array
**/
Array.prototype.hasValue = function(value) 
{
	var len = this.length;
	for (var x = 0; x <= len; x++) 
	{
		if (this[x] == value) 
		{
			return true;
		}
	}
	return false;
};

String.prototype.trim = function() 
{
	return this.replace(/^\s+/, '').replace(/\s+$/, ''); 
}
