// <![CDATA[
/******************************************************************************************
* Module: siworks.extention.js
* Version: 1.0
* Created: 20081118
* Description: We are now going to further extend the DOM via prototype.js much
* more effective way of doing things, we bind everything together this way
* @copyright		2009 SI-Works, All rights reserved
* @author			$Author: greg $
* @email			<support@siworks.co.za>
* @link				http://www.siworks.co.za
* @version			$Revision: 55 $
* $Id: siworks.extention.js 55 2009-08-25 18:42:58Z greg $
* 
* Copyright:  SI Works internet var year = new Date(); year.getFullYear();
* 
* Email:  support@siworks.co.za
* Author: Greg Shiers, Jarratt Ingram
******************************************************************************************/
var SI_Works_Tables = {
	checkAllCheckboxesInTableColumn : function ( trigger, tbl, column ) {	
	var index;
	if (column) {
		index = column;
	}
	else {
		index = 0;
	}
	var trigger = $(trigger);
		$A($$('#'+tbl+' tbody tr')).each (function ( element ) {
			if ( trigger.checked ) {
				element.down('input',index).checked = true
				element.addClassName('active');
			}
			else {
				element.down('input',index).checked = false;
				element.removeClassName('active');
			}
		})
	},
	setCheckAllStatus : function ( trigger , target , checkbox ) { 
		if ( typeof $( trigger ) != null ) {	
			var checked = $$('#'+trigger+' tbody tr');
			if ( $(checkbox).checked) {
				$(checkbox).up('tr').addClassName('active');
			}
			else {
				$(checkbox).up('tr').removeClassName('active');
			}
			var count = 0;
			$A($$('#'+trigger+' tbody tr')).each (function ( element ) {
				count += element.down('input').checked ? 1 : 0;
			});
			return ( count == checked.length ) ? $(target).checked = true : $(target).checked = false;
		}
	}
}
/**
** ERROR OBJECT
** Object that is going to control the form validation on gogrow
**/
var SI_Works_Error = {
	/* Here we create an error which simply changes the colors of the labels and inputs to red */
	createError: function ( element , message ) {
		/** We can use scriptaculous's Morph function to make a transition between 2 colours **/
		new Effect.Morph(element, { style: 'border-color: #ff0000;', duration: 0.8 });
		/** Update the label with the error message **/
		element.previous().update( message);
		/** We can use scriptaculous's Morph function to make a transition between 2 colours **/
		new Effect.Morph(element.previous(), { style: 'color: #ff0000;', duration: 0.8 });
	},
	/* Here we remove an error if it exsists which simply changes the colors of the labels and inputs to normal, from red */
	removeError: function ( element , message ) {
		/** We can use scriptaculous's Morph function to make a transition between 2 colours **/
		new Effect.Morph(element, { style: 'border-color: #333c43;', duration: 0.8 });
		/** Update the label with the error message **/
		element.previous().update( message);
		/** We can use scriptaculous's Morph function to make a transition between 2 colours **/
		new Effect.Morph(element.previous(), {  style: 'color: #8a8b8c;', duration: 0.8 });
	}
}

/**
* These methods add custom effects through the RSVP website
**/
var SI_Works_Custom = {
/**
	* counts the amount of charactors and updates a span with the value
	* @param trig
	* @param tbl
	* @param column
	* @version 1.4.2
	* @author Greg Shiers
	*/
	countCharacters : function ( field, countfield, maxlimit ) {
		// if too long...trim it!
		if ( $F(field).length > maxlimit ) {
			$(countfield).up('small').addClassName('red');
			$(field).value = $F(field).substring( 0, maxlimit )
		}
		else {
			$(countfield).up('small').removeClassName('red');
			$(countfield).innerHTML = ( maxlimit - $F(field).length )
		}
	},

	/**
	** @details	that selects or de-selected all options in a select box
	** @copyright 2009 SI-Works, All rights reserved
	** @param text
	** @param select
	** @version 1.3
	** @author Greg Shiers // SI Works Internet
	**/
	selectDeselectAll : function ( text, select ){
		/**
		** first if statement checks if the element's innerHTML is in select all status
		**/
		var text = $(text)
		if( text.innerHTML == "Select All" ) {
			/**
			** We do a small validation to check if there are infact options 
			** in the target select box
			**/
			if ( $(select).childElements().length > 0 ){
				text.next('span').update('');
				/**
				** Loop through all the option element and make them selected
				**/
				$A($(select).childElements()).each(function( e ) {
					e.selected = true;
				});
				/**
				** Set the title of the span tag to read correctly
				** and set the text or innerHTML to "De-Select All"
				**/
				text.writeAttribute('title','Click here to de-select all options');
				text.update("De-Select All");
			}
			/**
			** This is the validation to throw an error if there are no
			** options inside the select box
			**/
			else {
				/**
				** First check if there is a span next to the trigger span
				** and see if it's empty, if it's empty, then insert the text
				**/
				if ( text.next('span').innerHTML == '' ){
					text.next('span').insert('Nothing selected');
				}
			}

		}
		else if ( text.innerHTML == "De-Select All" ) {
			$A($(select).childElements()).each(function( e ) {
				e.selected = false;
			});
			text.update("Select All").writeAttribute('title','Click here to select all options');

		}
		/**
		** If all the above is not valid, then we have an unknown problem
		**/
		else {
			throw('An unknown Error has occured, the administrator has been emailed');
		}
	},
	updatedAccpetCommentCheckbox: function ( element, message ) {
		element = $(element);
		if ( element.checked ) {
			element.next('label').update('Yes, allow the public to comment');
		}
		else {
			element.next('label').update('No, don\'t allow the public to comment');
		}
	},
	closeMessage: function (element) {
		new Effect.Fade( element , { duration: 0.5 } );
	},
	/**
	** @details	functio that retrieves section parent menu options via Ajax
	** @copyright	2009 SI-Works, All rights reserved
	** @param 
	** @version 1.0	
	** @author	Greg Shiers // SI Works Internet
	**/
	getSectionParentMenuOptions : function ( ) {
		if ( $('section') ) {
			$('section').observe('change', function () {
				new Ajax.Request('/admin/menu/index/returnsectionselectbox/section/'+this.value, {
					method: 'get',
					onCreate : function () {
						$('parent_menu_holder').update('<select id="section" disabled="disabled"><option>Loading...</option></select>');
					},
					onComplete: function(transport) {
						$('parent_menu_holder').update(transport.responseText);
					},
					onFailure : function () {
						alert('ajax failed');
					}
				});	
			})
		}
	},
	/**
	** @details	function to change the latest news items on the homepage
	** @copyright	2009 SI-Works, All rights reserved
	** @param 
	** @version 1.0	
	** @author	Greg Shiers // SI Works Internet
	**/
	swapLatestNewsItem : function ( ID, page ) {
		$A($$('.news_blocks')).each(function ( element ) {
			element.setStyle({'display' : 'none'});
			$(ID).setStyle({'display' : 'block'})
		});
		$A($$('.page')).each(function ( element, index ) {
			element.removeClassName('active');
			$(page).addClassName('active');
		});
	}
}


/**
* set up the validation object to exend onto prototype framework.
**/
var SI_Works_Validation = {
	/**
	* Function to check weather a field is empty
	* RegEx includes validation to check if they have added multipe white spaces to the text field.
	* if(validation.empty(field){...}
	* @param field
	* @version 1.2
	* @author Greg Shiers
	*/
	emptyString: function ( field ) {
		var re = /^\s*$/;
		return re.test( $F(field) );
	},
	/**
	* Check that the field contains no illegal charactors
	* Allows "_", " " and "." otherwise other charactors are not allowed
	* if(!validation.alpha_numeric(field)){...}
	* @param field
	* @version 1.2
	* @author Greg Shiers
	*/
	alphaNumeric: function ( field ) {
		var re = /^[A-Za-z0-9_ \.]+$/
		return re.test( field.value );
	},
	/**
	* Function to check for a valid email address, includes a check for @ and . in the string
	* if(validation.email(field)){...}
	* @param field
	* @version 1.5
	* @author Greg Shiers
	*/
	isEmailAddress: function ( field ) {
		var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/
		return re.test( $F(field) );
	},
	/**
	* Function to check for a valid phone number
	* Can include a number, spaces, dashes, and an extention
	* if(!validation.phone_number(field)){...}
	* @param field
	* @version 1.5
	* @author Greg Shiers
	*/
	phoneNumber: function( field ) {
		var re  = /^(\+\d{1,3} ?)?(\(\d{1,5}\)|\d{1,5}) ?\d{3,4} ?\d{0,7} ?(x|xtn|ext|extn|extension)??\.? ?\d{1,5}?$/i;
		return re.test( field.value );
	},
	/**
	* Function to check that 2 fields match eachtoher
	* Generally used for when asking confirmation for an email address or password
	* if(Element.fieldsMatch(field1,field2){...}
	* @param field
	* @version 1.2
	* @author Greg Shiers
	*/
	fieldsMatch: function ( field1 , field2 ) {
		return ( field1.value != field2.value ) ? true : false;
	},
	/**
	* Function to check the length of a field
	* if (validation.fieldLength ( field , min , max)) {...}
	* @param field1
	* @param field2
	* @version 1.2
	* @author Greg Shiers
	*/
	fieldLength: function ( field , min , max ) {
		return ( ( field.value.length < min ) || ( field.value.length > max ) ) ? true : false;
	},
	/**
	* Function to check the length of a field
	* if (validation.minLength ( field , min )) {...}
	* @param field
	* @param min
	* @version 1.2
	* @author Greg Shiers
	*/
	minLength: function ( field , min ) {
		return ( ( field.value.length < min ) ) ? true : false;
	},
	/**
	* Function to check the length of a field
	* if (Element.maxLength ( field , min , max)) {...}
	* @param field
	* @param max
	* @version 1.2
	* @author Greg Shiers
	*/
	maxLength: function ( field , max ) {
		return ( ( field.value.length != max ) ) ? true : false;
	},
	/**
	* To check that input type is a word document
	* if(!Element.word(field){...}
	* @param field
	* @version 1.2
	* @author Greg Shiers
	*/
	word: function ( field ) {
		var re = /(.doc$)/; // allow only word
		return re.test( field.value );
	},
	/**
	* Checks that input has an image extention
	* if(!Element.safeWebImageInput(field){...}
	* @param field
	* @version 1.2
	* @author Greg Shiers
	*/
	safeWebImageInput: function ( field ) {
		var re = /(.jpe?g$)|(.gif$)|(.png$)/; // allow jpg / jpeg / gif / png
		return re.test( field.value );
	},
	/**
	* Checks that input is an safe web file upload
	* if(!Element.safeWebFileUpload(field){...}
	* @param field
	* @version 1.2
	* @author Greg Shiers
	*/
	safeWebFileUpload: function ( field ) {
		var re = /(.pdf$)|(.txt$)|(.csv$)|(.doc$)/; // allow pdf / txt / csv / doc
		return re.test( field.value );
	},

	// Function to group a bunch of check boxes
	// Use this function is conjunction with is_minimum_checked & is_minimum_selected to group and make an array
	// group = group_it(field.getElementsByTagName('option')) // group = group_it(field);
	groupElements: function ( obj ) {
		return (typeof obj[0] != 'undefined') ? obj : [obj];
	},
	
	// Function to validate that one of the groups are checked
	// first we must make sure that create an array of the elements that we want to check
	// by using the above group_it function
	isMinimumChecked: function ( min , grp ) {
	var checked = 0, i = grp.length;
	do
		if (grp[--i].checked)
			if (++checked >= min)
				return false;
	while (i);
	return true;
	},
	
	// Object/ Namespsace that checks that the min options are selected in a multiple select.
	// to call this function Call function
	// group = group_it(field.getElementsByTagName('option')) this will group the elements
	// validation.is_min_selected(min,field)
	// remember to set the selected variable to 0 to initialize that it starts on 0
	is_min_selected: function ( grp , min ) {
	
		var selected = 0, i = grp.length; // set "selected" to 0 so as to initialize the variable
		do {
			if ( grp[--i].selected ) {
				if ( ++selected >= min ) {
					return false;
				}
			}
		}
		while ( i );
		return true;
	},
	
	// Function to check that a singe checkbox is checked.
	// if(validation.checked(field)){...}
	checked: function ( field ) {
		return ( field.checked ) ? false : true;
	},
	// Function to make sure that an option is selected.
	// if(validate.selected(field)){...};
	selected: function ( field ) {
		return (field.selectedIndex == 0) ? true : false;
	},
	// Function to check for a certain selected index
	// if(validate.selected(field)){...};
	selected_index: function ( field , index) {
		return (field.selectedIndex == index) ? true : false;
	},

	// validate that the user has checked one of the radio buttons
	radio: function ( radio ) {		
		// Run a for loop through the array of radio buttons to check if they 1 is checked
   		for ( var i = 0; i < radio.length; i++ ) {
			if ( radio[i].checked ) {
				return true;
       		}
   		}
	},
	
	// Object that converts m to mm
	// IE is we have a date function that spits out 2 as the month of february
	// This funtion will make the value now 02.
	friendly_date: function ( string ) {
		if ( string < 10 ) {
			string='0'+string;
		}
	 	return string;
	},
	// Object to validate that the date formatt has been entered correctly (dd/mm/yyyy)
	dateFormatted : function ( field ) {
		var re = /^(\d{2,2})\/(\d{2,2})\/(\d{4,4})$/
		return re.test( field.value );
	},
	// Object to validate that the date formatt has been entered correctly (dd-mm-yyyy hh:mm)
	isoDate : function ( field ) {
		var re = /^(\d{4,4})\-(\d{2,2})\-(\d{2,2}) (\d{2,2}):(\d{2,2})$/
		return re.test( $F(field) );
	},
	createError : function ( element, message ) {
		if ( $('created_error') ) {
			$('created_error').remove();
		}
		Element.insert(element,{'before': '<div id="created_error" class="errors"><div class="errors_left"></div><div class="errors_right"></div><p>'+ message +'</p></div>'})
	},
	throwError : function ( element , message ) {
		var element = $(element);
		element.addClassName("form_error").previous("label").update(message).addClassName('red');
	},
	discardError: function ( element ) {
		var element = $(element);
		element.removeClassName("form_error").previous("label").update( element.previous("label").readAttribute('title') ).removeClassName('red');
	},
	createLabelError : function ( element, message ) {
		$( element ).addClassName("form_error").previous("label").update( message ).addClassName('red');
	},
	removeLabelError : function ( element ) {
		if ( $(element).previous("label").readAttribute("label") != null ) {
			$(element).removeClassName("form_error").previous("label").update("")
		}
		else {
			$(element).removeClassName("form_error").previous("label").update( $(element).previous("label").readAttribute('title') ).removeClassName('red');
		}
	},
	deleteMultipleRecords : function ( table , button, form ) {
		var count = 0, message = '';
		$A($$('#'+ table +' tbody tr')).each (function ( element ) {
			count += element.down('input').checked ? 1 : 0;	
		});
		if ( count == 0 ) {
			message = '<p class="red">Please use the checkboxes to check which results you would like to delete</p>';
			message += '<a href="/" title="OK" class="green nu" onclick="$(\''+button+'\').prototip.hide();return false;"><strong><img src="/admin/images/icons/tick.png" width="16" height="16" alt="Tick icon" class="icor" />OK, let me select</strong></a>';
		}
		else {
			message = '<p>Are you sure you want to delete the selected rows</p>';
			message += '<a href="/" title="Delete forever" onclick="$('+form+').submit();return false;" class="green nu"><strong><img src="/admin/images/icons/tick.png" width="16" height="16" alt="Tick icon" class="icor" />Yes, delete them</strong></a>&nbsp;&nbsp;&nbsp;';
			message += '<a href="/" title="No, dont want to delete anymore" class="red nu" onclick="$(\''+button+'\').prototip.hide();return false;"><img src="/admin/images/icons/cross.png" width="16" height="16" alt="Cross icon" class="icor" /><strong>No, leave them</strong></a>';
		}
		new Tip(button, 
				message , 
				{  
					stem: 'bottomLeft', 
					showOn: 'click', 
					hideOn : 'click',
					width: 280,
					radius: 3,
					border: 3,
					hook: { target: 'Right', tip: 'bottomLeft' },
					offset: { x: 10, y: 0 }
				});
		$(button).prototip.show();
	}
}
/**
**	These methods will control the way that we post information to 
**  the database from an ajax call
**/
var SI_Works_Ajax_Forms = {
	/**
	* Function that will insert a new row to the database
	* From the ajax opener
	* @param element
	* @version 1.0
	* @author Greg Shiers
	*/
	loadSimpleAjaxPostForm : function ( element, type ) {
		/**
		** Fire the first lightbox window, which fetches the form and displays it
		**/
		Lightview.show({
			href: '/admin/ajax/quickadd/?option='+type+'&call=form',
			rel: 'ajax',
			options: {
				autosize: true,
				topclose: true,
				ajax: {
				/**
				** when the first lightbox object has finished the ajax call, we have to fire another one
				** to fetch the contents of the error message or the thank you for adding message
				**/
				onComplete: function( ) {						
					// once the request is complete we observe the form for a submit, here we will send another Ajax Call.
						$('ajax_form').observe('submit', function ( event ) {
							/**
							** Stop the default event from submitting the form
							**/
							Event.stop(event);
							/**
							** Fire the second lightview window which calls the message
							**/
							Lightview.show({
								href: '/admin/ajax/quickadd/?option='+type+'&call=message',
								rel: 'ajax',
								options: {
									menubar: false,
									topclose: true,
									autosize: true,
									ajax : {
										parameters: Form.serialize('ajax_form'),
										/**
										** Finally when the ajax has completed itself, we fire a ajax call via
										** prototype's ajax handler to refresh the base content and whichever
										** element it is that needs to be refreshed with the new content from the DB
										**/
										onComplete: function () {
											/**
											** Here is where we set the time out for the new inner HTML tow refresh
											**/
											setTimeout(function () {
												new Ajax.Request('/admin/ajax/quickadd/?option='+type+'&call=response', {
													method: 'get',
													onComplete: function(transport) {
														location.reload(true);
														$( element ).update(transport.responseText);
													},
													onFailure : function () {
														alert('ajax failed');
													}
												});
											},2500); // end setTimeOut
											/**
											** We make sure to remove the lightbox object once we've refreshed the innerHTMl
											**/
											setTimeout(function () {
												Lightview.hide();
											},3000); // end SetTimeOut
										}
									}
								}
							});// End lightview object set up
						}); // End submit observe on second for submission
					}
				}
			}
		}); // End first lightview object set up
	}
}
/* Add these methods to the JS page */
Element.addMethods(SI_Works_Custom);
Element.addMethods(SI_Works_Validation);
Element.addMethods(SI_Works_Tables);
/**
* Lets add some event listeners to the pages when we need them
**/
Event.observe ( window , "load" , function ( event ) {
	// Check on this checkall 
	if ( $('checkall') ) {
		$('checkall').observe ("click", function () {
			Element.checkAllCheckboxesInTableColumn('checkall','guest_list',0)
		});
	}
})


document.observe ( 'dom:loaded' , function () {
	$A($$('[class="tip"]')).each(function( element ) {
		var content = element.getAttribute('title');
			element.writeAttribute('title','');
		new Tip(element, content, {
			width: 200,
			offset: { x: 0, y: -2 },
			radius: 5,
			border: 4,
			stem: 'bottomLeft',
			hook: { tip: 'bottomLeft', mouse: true }
		});
	});
	$A($$('.close')).each(function( element ){
		element.observe('click', function() {
			Element.closeMessage(element.up())
		})
	});
	
	if ($('slide_container')) { 
		new Carousel($('slide_container').down('#slides_holder'), $('slide_container').select('.slide'), $('slide_container').select('a.carousel-control'), {
			duration: 0.3,
			visibleSlides: 5,
			auto: true,
			frequency : 4,
			wheel: false
		});
	}
	new Protofade('protofade', { duration: 1, delay: 5.0 });
	
	
	/** Check here if we're in the content, and if there is the publish between 2 dates checkbox **/
	if ( $('publish_dates') ) {
		$('publish_dates').observe('click',function () {
			if ( $('publish_date_drops').getStyle('display') == 'none' ) {
				$('publish_dates').disabled = true;
				$('publish_date_drops').appear({duration: 0.3});
				setTimeout(function() {
					$('publish_dates').disabled = false;
				},500)
			}
			else {
				$('publish_dates').disabled = true;
				$('publish_date_drops').fade({duration: 0.3});
				setTimeout(function() {
					$('publish_dates').disabled = false;
				},500)
			}
		})
		
	}
	if ( $('logout_link') ) {
		$('logout_link').observe ("click", function ( event ) {
			Event.stop(event);
			Lightview.show({ 
				href: '/admin/logout.php', 
				rel: 'ajax', 
				options: { 
					topclose: true,
					width: 320, 
					height: 80
				}
			});		
		})
	}
	if ( $('section') ) {
		Element.getSectionParentMenuOptions();
		
	}
	
	
	if ( $('search_keyword') ) {
		$('search_keyword').observe('focus', function () {
			if( $F('search_keyword') == 'Quicksearch' ) {
				$('search_keyword').value = '';
			}
		});
		$('search_keyword').observe('blur', function () {
			if( $F('search_keyword') == '' ) {
				$('search_keyword').value = 'Quicksearch';
			}
		});
	}
});



// ]]>


