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');
 	 	if(thisFormID != '#')
 	 		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;
			
		});
		
		// ! Icon Link Delete
		inFormActions['linkRemove'] = $('' + thisFormID + ' .linkRemove');
		inFormActions['linkRemove'].bind('click', function() { 
			if (confirm("Do you wish to remove this instance of this item?\n\nThe item will not be deleted from the system because it is used elsewhere.")) 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');
    
		});
		
		// ! Multiple Select
		
		var multipleSelect = {
			start: function(thisFormID) {
				// form
				var form = $(thisFormID);
			
				// initial state
				form.find('.itemRow').each(function(i, el) {
					el = $(el);
					if(el.find('.selectMultipleValue').length > 0)
						multipleSelect.updateValues(el);
				});
				
				// select box event
				form.find('.selectMultiple').change(multipleSelect.selectChanged);
 
				// add event
				form.find('.selectMultipleAdd').click(multipleSelect.addClicked);
				
				// cancel event
				form.find('.selectMultipleCancel').click(multipleSelect.cancelClicked);
			},
			
			selectChanged: function() {
				// dom elements
          		var select = $(this);
          		var itemRow = select.parents('.itemRow');
	        	var tb = itemRow.find('.selectMultipleText');
	        	  
	        	// are we selecting an existing item or adding a new one?
	        	if(select.val() == '|-----| Add New |-----|') {
	        		// clear selection and update UI
	        		itemRow.find('select option:selected').attr('selected', false);
	        		tb.css('display', 'block');
	        		select.css('display', 'none');
	        	} else {
	        		multipleSelect.addValue(itemRow, select.val());
        		}
	        	
	        	return false;
			},
			
			addClicked: function() {
				// dom elements
				var itemRow = $(this).parents('.itemRow');
				var tb = itemRow.find('.selectMultipleText input');
				multipleSelect.addValue(itemRow, tb.val());
				tb.val('');
				return false;
			},
			
			cancelClicked: function() {
				// dom elements
				var itemRow = $(this).parents('.itemRow');
				var tb = itemRow.find('.selectMultipleText');
				var select = itemRow.find('select');
				
				// update UI
				tb.css('display', 'none').val('');
				select.css('display', 'block');
				
				return false;
			},
			
			removeClicked: function() {
				var link = $(this);
				var itemRow = link.parents('.itemRow');
				multipleSelect.removeValue(itemRow, link.text());
				return false;
			},
			
			addValue: function(itemRow, value) {
				// dom elements
				var hf = itemRow.find('.selectMultipleValue');
				var select = itemRow.find('select');
				var tb = itemRow.find('.selectMultipleText');
				
				// basic UI
				tb.css('display', 'none').val('');
				select.css('display', 'block');
				
				// ensure item not in select
				select.find("option[value='" + value + "']").remove();
				
				// add to hidden field
				hf.val(hf.val() + '###' + value);
				hf.val(hf.val().replace('######', '###'));
			
				// update remove links
				multipleSelect.updateValues(itemRow);
			},
			
			removeValue: function(itemRow, value) {
				// dom elements
				var hf = itemRow.find('.selectMultipleValue');
				var select = itemRow.find('select');
				var tb = itemRow.find('.selectMultipleText');
				
				// update hidden field
				hf.val(hf.val().replace(value, '').replace('######', '###'));
				
				// add to select box
				itemRow.find("select option:last").before('<option value="' + value + '">' + value + '</option>');

				// update remove links
				multipleSelect.updateValues(itemRow);
			},
			
			updateValues: function(itemRow) {
				// dom elements
				var hf = itemRow.find('.selectMultipleValue');
				var select = itemRow.find('select');
				var selectedValues = itemRow.find('.selectMultipleValues');
								
				// clear current links
				selectedValues.find('a').remove();
				$(hf.val().split('###')).each(function(i, el) {
					if(el.length > 0) {
						selectedValues.append('<a href="#">' + el + '</a>');
						select.find("option[value='" + el + "']").remove();
					}
				});
				selectedValues.find('a').click(multipleSelect.removeClicked);
			}
		};
		
		multipleSelect.start(thisFormID);
		
		// ! 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',
					Width: '600'
			});
			if ( $('.fckArea').length >0 ) $('.fckArea').ckeditor({
					stylesCombo_stylesSet: 'default:/js/core.ckeditor.styles.js',
					customConfig: '/js/core.ckeditor.config.js',
					toolbar: 'Admin',
					Height: '200',
					Width: '758'
			});
			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');
		});
	});
	
}

