var urlSuffix = '?';
var formsArray = new Array();
var h1buttons = new Array();
var formActions = new Array();
var jsFunctionsRegistry = new Array();


$(document).ready(function() {
		
	// find all the forms on the page and initialise all the 
	// links and buttons within the form
	var forms = document.getElementsByTagName("form");
	
 	for (i=0; i< forms.length; i++) {
 		
 	 	var thisFormID = '#' + $(forms[i]).attr('id');
		initialiseForm(thisFormID);
 	}
 	
	$( "form#login_form h1" ).bind( "click", slideForm );
	$( "form#login_form .buttonSet" ).bind( "click", slideForm );

});

function slideForm() {

	if($( "#loginpanel" ).css( 'marginTop' ) == "-75px") {
		$( "#loginpanel" ).animate( { marginTop:"-161px"}, 500, function() {
			$( ".alerts" ).fadeIn(300);	 
		});
	} else if($( "#loginpanel" ).css( 'marginTop' ) == "-161px") {
		if($( ".alerts" ).length > 0) $( ".alerts" ).fadeOut(300, function() {
			$( "#loginpanel" ).animate( { marginTop:"-75px"}, 500 );
		});
		else $( "#loginpanel" ).animate( { marginTop:"-75px"}, 500 );
	}

}

function registerFormFunction(functionName) {
	if (!in_array(functionName, jsFunctionsRegistry)) {
		var nextIndex = jsFunctionsRegistry.length + 1;
		jsFunctionsRegistry[nextIndex] = functionName;
	}
}

function initialiseForm(thisFormID) {

		// ! Run any funtion added to the array jsFunctionsRegistry
		
		for (var i in jsFunctionsRegistry) {
			eval(jsFunctionsRegistry[i] + "('" + thisFormID + "')");
		}
								
		formsArray[thisFormID] = new Array();
		formsArray[thisFormID]['targetUrl'] = $(thisFormID).attr('action');
		
		var formActions;
		inFormActions = new Array();
		
		// ! Date Pickers
		if ($('' + thisFormID + ' .date-pick').length > 0) {
			
			if ($('' + thisFormID + '_startDate').length > 0) {
				startDateValue = $('' + thisFormID + '_startDate').attr('value');
			} else {
				startDateValue = '01/01/1996';
			}
	
			if ($('' + thisFormID + '_endDate').length > 0) {
				endDateValue = $('' + thisFormID + '_endDate').attr('value');
			} else {
				endDateValue = '01/01/3000';
			}
			
			$('' + thisFormID + ' .date-pick').datePicker({
				clickInput:	true, 
				startDate:	startDateValue,
				endDate:	endDateValue
			});
		}
		
		// ! Update Recordset in Recordset Navigation
		inFormActions['updateNav'] = $('' + thisFormID + ' .setNavigation');
		inFormActions['updateNav'].bind('change', function() { 
			$('' + thisFormID + '').submit();
		});
		
		// ! Clear Text Filter Button
		inFormActions['textFilterClear']  = $('' + thisFormID + ' .textFilterClear');
		$(inFormActions['textFilterClear']).bind('click',  function() {
			$(this).prev().val('');
			$(this).parents('form').submit();
		});
		
		// ! Cancel, Return Button
		inFormActions['cancelReturn'] = $('' + thisFormID + ' .cancelReturn');
		inFormActions['cancelReturn'].bind('click', function() {
			history.go(-1);
		});
		
		// ! Icon Link Delete
		inFormActions['linkDelete'] = $('' + thisFormID + ' .linkDelete');
		inFormActions['linkDelete'].bind('click', function() { 
			if (confirm("Are you sure you want to delete this item?\n\nThis cannot be undone.")) return true;
			else return false;
			
		});
		
		// ! Star Picker
		if ($('.starContainer').length > 0) {
			inFormActions['stars'] = $('input:radio.star').rating();
		}
		
		// ! Currency
		inFormActions['currency'] = $('' + thisFormID + ' .inputCurrency');
		inFormActions['currency'].bind('blur', function() { 
			$(this).val( toCurrency( $(this).val() ) );
		});
		
		// ! Limited-length text fields
		inFormActions['textareaLimited'] = $('' + thisFormID + ' .textareaLimited');
		$(inFormActions['textareaLimited']).bind('keyup',  function() {
		
			var maxChars = $(this).next().attr('value');
			var currentChars = $(this).attr('value').length;
			var charRemaining = (((maxChars  - currentChars) == 1) ? '1 character remaining' : (maxChars  - currentChars) + ' characters remaining');
			
			if (currentChars > maxChars) {
				var newValue = $(this).attr('value').substr(0, maxChars);
				$(this).attr('value', newValue);
			} 
			
			$(this).siblings('.formNotice').attr('value', charRemaining);
			
		});
		
		// ! Colour Picker
		inFormActions['colourPicker'] = $('' + thisFormID + ' .colourPicker');
		if (inFormActions['colourPicker'].length > 0) inFormActions['colourPicker'].ColorPicker({
			color: $('.colourPicker').next('input').val(),
			onShow: function (colpkr) {
				$(colpkr).fadeIn(500);
				return false;
			},
			onHide: function (colpkr) {
				$(colpkr).fadeOut(500);
				return false;
			},
			onChange: function (hsb, hex, rgb) {
				$('.colourPicker').css('backgroundColor', '#' + hex);
				$('.colourPicker').next('input').val('#' + hex);
			}
		});
		
		
		// ! What is this ? Something to do with colour I think
		inFormActions['Text'] = $('' + thisFormID + ' .Text');
		inFormActions['Text'].bind('keyup', function() {
			if ( is_colour( $(this).val() ) ) $(this).prev('div').css('background-color', $(this).val() );
		});
		
		// ! Password Strength

		// var shortPass = 'Too short'
		// var badPass = 'Bad'
		// var goodPass = 'Good'
		// var strongPass = 'Strong'

		inFormActions['passwordStrength'] = $(thisFormID).find('.itemRow .passwordStrength').prev();
		inFormActions['passwordStrength'].bind('keyup', function() {
			strength = passwordStrength(inFormActions['passwordStrength'].val());
			strengthField = $(this).next();
			strengthField.html(strength);
			switch(strength) {
				case('Strong'):
					strengthField.attr('class', 'passwordStrengthStrong');
					break;
				case('Good'):
					strengthField.attr('class', 'passwordStrengthGood');
					break;
				case('Bad'):
					strengthField.attr('class', 'passwordStrengthBad');
					break;
				default:
					strengthField.attr('class', 'passwordStrength');
			}	
			
		});	
		
		
		// ! Input Integer
		inFormActions['inputInteger'] = $(thisFormID).find('.itemRow .inputInteger');
		$(inFormActions['inputInteger']).bind('keyup', function(event) {
			var testValue = ($(this).val());
			$(this).val( permittedCharacters(testValue, '1234567890' ) );
		});
		
		// ! Extended Select
		inFormActions['selectExtended'] = $(thisFormID).find('.itemRow .selectExtended');
		$(inFormActions['selectExtended']).change( function(event) {
		
			selectBoxValue = document.getElementById($(this).attr('id')).value;
			textArea = $(this).next();
			textInput = $(this).next().children(0);
			
			if (selectBoxValue == '|-----| Add New |-----|') {
				textInput.attr('value', '');
				textArea.attr('style', 'display: block');
				$(this).attr('style', 'display: none');
			} else {
				textInput.attr('value', selectBoxValue);
			}
			
		});
		
		inFormActions['selectExtendedCancel'] = $(thisFormID).find('.itemRow .selectExtendedCancel');
		$(inFormActions['selectExtendedCancel']).bind('click', function(event) {
		
			selectBox = ($(this).parent().prev().attr('id'));
			document.getElementById(selectBox).value = $('#' + selectBox).children('option:first-child').attr('value');
			
			$(this).prev().attr('value', '');
	    		$(this).parent().prev().attr('style', 'display: inline');
	    		$(this).parent().attr('style', 'display: none');
    
		});
		
		// ! Check box group		
		$(thisFormID + ' .checkboxGroup input').bind('click', function() {
		
			var boxesInGroup = $(this).parents('.checkboxGroup').find('input');
			var boxClicked = this;
			
			if (boxClicked.checked == true) {
				if (boxClicked.value == '') {
					
					boxesInGroup.each( function() {
						this.checked = false;
					}); 
					
					boxClicked.checked = true;
					
				} else {
					boxesInGroup.each( function() {
						if (this.value == '') this.checked = false;
					});
				}
			} else {
					var checkedCount = 0;
					boxesInGroup.each( function() {
						if (this.checked == true) checkedCount++;
					})
					if (checkedCount == 0) boxClicked.checked = true;
			}
			
		
		});
				
		// ! Form input FCK editor
		// if there are any fck fields on this form complete them now
			if ( $('.fckSimple').length >0 ) $('.fckSimple').ckeditor( {
					stylesCombo_stylesSet: 'default:/js/core.ckeditor.styles.js',
					customConfig: '/js/core.ckeditor.config.js',
					Height: '200'
			});
			if ( $('.fckArea').length >0 ) $('.fckArea').ckeditor({
					stylesCombo_stylesSet: 'default:/js/core.ckeditor.styles.js',
					customConfig: '/js/core.ckeditor.config.js',
					toolbar: 'Admin'
			});
			if ( $('.fckNarrow').length >0 ) $('.fckNarrow').ckeditor({
					customConfig: '/js/core.ckeditor.config.js',
					stylesCombo_stylesSet: 'default:/js/core.ckeditor.styles.js',
					Width: '250',
					Height: '300',
					toolbar: 'Narrow'
			});
			
			
/*
*/
		
}


function hideDescriptions(formID) {
	$('#' + formID + ' div.formDescription').addClass('revealed');
	$('#' + formID + ' div.formDescription').prev().before('<a class="revealDescription" href="javascript:;">i</a>');
	
	$('#' + formID + ' a.revealDescription').unbind('mouseover');
	$('#' + formID + ' a.revealDescription').unbind('mouseout');
	
	$('#' + formID + ' a.revealDescription').each(function() {
		$('#' + formID + ' a.revealDescription').click(function(i) {
			$(this).next().next('div').slideToggle('slow');
		});
	});
	
}

