// <![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: peter $
* @email			<support@siworks.co.za>
* @link				http://www.siworks.co.za
* @version			$Revision: 148 $
* $Id: siworks.entention.js 148 2009-03-19 08:36:42Z peter $
* 
* Copyright:  SI Works internet var year = new Date(); year.getFullYear();
* 
* Email:  support@siworks.co.za
* Author: Greg Shiers, Jarratt Ingram
******************************************************************************************/
/**
* These methods add custom effects through the why trade in 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.2
	* @author Greg Shiers
	*/
	countCharacters : function ( field, countfield, maxlimit ) {
		// Lets set come variables
		var field = $( field );
		var count = $( countfield );
		// if too long...trim it!
		( field.value.length > maxlimit ) ? field.value = fld.value.substring( 0, maxlimit ) : count.innerHTML = ( maxlimit - field.value.length )
	},
	showHideElementStatic : function ( element , show ) {
		/* set the element variables */
		var element = $( element );
		( show ) ? element.setStyle({'display':'block'}) : element.setStyle({'display':'none'});
	},
	selectUnselectAll : function ( element , sel ) {
			// find the table to select from
		var element		= $(element);
		
		if( element.innerHTML == "Select All" ) {
			$A($(sel).childElements()).each(function(el) {
				el.checked = true;
			});
			element.update("De-Select All");
		}
		else if ( element.innerHTML == "De-Select All" ) {
			$A($(sel).childElements()).each(function(el) {
				el.checked = false;
			});
			element.update("Select All");
		}
		else {
			alert('There has been an error, administrators have been notified, sorry about it');
			return false;
		}
	},
	getContentFromIframe : function (iframe) {
		return $('ajaxFrame').contentWindow.document.body.innerHTML;
	}
}

/**
* 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 that the entry is a positive or negative number
	* @usage !Element.numericWithSpaces(field)
	* @param (field) which field needs to be checked
	* @version 0.3
	* @returns Boolean
	*/
	numericWithSpaces: function ( field ) {
		var re  = /^[0-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
   		$A($$('.'+radio)).each(function(e){
			return (e.checked ? true : false);
		});
	},
	
	// 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');
		}
	}
}
/**
**	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 column
	* @version 1.0
	* @author Greg Shiers
	*/
	
}

var SI_Works_Dialog_Controls = {
	/**
	* updates the value of the submit button on adding users to address book
	* @param content
	* @version 1.2
	* @author Greg Shiers
	*/
	createCoverSheet : function ( ) {
		/* This is where we create the two divs for the cover sheet */
		var cover = document.createElement('div');
		/* Using prototype's extend, we add attribues as below */
		Element.extend(cover);
		/* Add some attributes to the cover sheet */
		cover.writeAttribute('id','cover');
		cover.observe("click", function () {
			Element.removeCoverSheet();
		});
		cover.setStyle({
			width: Element.getPageDimensions()[0]+"px",
			height: Element.getPageDimensions()[1]+"px"
		});
		// insert it in the document
		document.body.appendChild(cover);
	},
	/**
	* removes the cover sheet
	* @param content
	* @version 1.2
	* @author Greg Shiers
	*/
	removeCoverSheet : function ( event ) {
		/* First check if the cover sheet and dialog elements exist */
		if( $('dialog')) {
			/** Grab the above elements push them into an array
			** using the $A function then perform the fade() function from
			** scriptolios to remove the cover sheet and fading it out */

				/* fade them out now */
				$('dialog').fade({duration: 0.5});
				setTimeout(function() {
						$('dialog').remove();
				},700);
		}
		else {
			Event.stop( event );
		}
	},
	createDialog : function ( width, title ) {
		this.dialog = document.createElement('div');
		this.dialog_contents;
		Element.extend(this.dialog);
		/* Add the attribues to the dialog that sits on top of the cover */
		this.truewidth = (width < 300 ) ? this.truewidth = 300 : this.truewidth = width;
		this.dialog.writeAttribute('id','dialog');
		this.dialog.setStyle ({
			left: ((Element.getViewportSize()[0] - 986) / 2) + 182 + "px",
			top: Element.getScrollingPosition()[1] + parseInt(Element.getViewportSize()[1] / 2) - parseInt(this.dialog.offsetHeight / 2) - 245 +"px",
			width: this.truewidth+"px"
		});
		// try and create the innerHTML of the table that hold the results
		try {
			this.dialog_contents =  '<table cellpadding="0" cellspacing="0" id="dialog_table" width="'+(this.truewidth)+'"><tbody>';
			this.dialog_contents += '<tr id="draghandle"><td class="top_left" width="145"><!-- --></td><td class="top" width="'+(this.truewidth-145-129)+'">'+title+'</td><td class="top_right" width="129"><!-- --></td></tr>';
			this.dialog_contents += '<tr>';
				this.dialog_contents += '<td colspan="3">';
					this.dialog_contents += '<table cellpadding="0" cellspacing="0" id="dialog_inner" width="'+(this.truewidth)+'">';
						this.dialog_contents += '<tr>';
							this.dialog_contents += '<td class="content_left" width="16"></td>';
							this.dialog_contents += '<td class="content" id="dialog_content" width="'+(this.truewidth-16)+'">';
								this.dialog_contents += '<div class="clear" id="dialog_main_content">';
										
								this.dialog_contents += '</div>';
							this.dialog_contents += '</td>';
						this.dialog_contents += '</tr>';
					this.dialog_contents += '</table>';
				this.dialog_contents += '</td>';
			this.dialog_contents += '<tr><td class="bottom_left" width="145"></td><td class="bottom" width="'+(this.truewidth-145-129)+'"></td><td class="bottom_right" width="129"></td></tr></tbody></table>';
		}
		catch ( error ) {
			this.dialog_contents = 'Unable to load the contents on this window';
		}
		document.body.appendChild(this.dialog);
		$('dialog').update(this.dialog_contents);
		new Draggable('dialog', { handle: 'draghandle', scroll: window });
	},
	/**
	* Creates the middle dialog box that sits on top of the cover sheet
	* @version 1.0
	* @author Greg Shiers
	*/
	createDialogWindow : function ( width , title, page ) {
		/* Create the cover sheet that we've previously defined. */
		//this.createCoverSheet();
		this.createDialog( width, title );
		if ( page ) {
			new Ajax.Request(page, {
				method: 'get',
				onLoading : function () {
					$("dialog_main_content").update('<div class="pr10 pl10 pt10 pb10"><img src="/images/icons/progress.gif" class="icor" />Loading...</div>');
				},
				onComplete: function(transport) {
					$("dialog_main_content").update(transport.responseText).setStyle({'display':'none'});
					
					new Effect.Parallel([
					new Effect.BlindDown("dialog_main_content",{ sync: true}), 
					new Effect.Opacity("dialog_main_content", { sync: true, from: 0, to: 1 }) 
					], { duration: 0.4 });

				},
				onFailure : function () {
					alert('Could not create Ajax Call to retrieve dialog contents');
					Element.removeCoverSheet();
					return false;
				}
			});
		}
	}
}
var SI_Works_Window_Objects = {
	/**
	* Fucntion to find the scroll position of an element
	* @version 1.4
	* @returns Array
	* @author Greg Shiers
	*/
	getScrollingPosition : function() {
		//array for X and Y scroll position
		var position = [0, 0];
		//if the window.pageYOffset property is supported
		if( typeof window.pageYOffset != 'undefined' ) {
			//store position values
			position = [
			window.pageXOffset,
			window.pageYOffset
			];
		}
		//if the documentElement.scrollTop property is supported
		//and the value is greater than zero
		if(typeof document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop > 0) {
			//store position values
			position = [
			document.documentElement.scrollLeft,
			document.documentElement.scrollTop
			];
		}
		//if the body.scrollTop property is supported
		else if(typeof document.body.scrollTop != 'undefined') {
			//store position values
			position = [
			document.body.scrollLeft,
			document.body.scrollTop
			];
		}
		//return the array
		return position;
	},
	/**
	* Finds the view point size of an element
	* @version 1.0
	* @author Greg Shiers
	*/
	getViewportSize : function() {
		var size = [0,0];
	
		if (typeof window.innerWidth != 'undefined') {
			size = [
				window.innerWidth,
				window.innerHeight
				];
		}
		else if (typeof document.documentElement != 'undefined'
				&& typeof document.documentElement.clientWidth != 'undefined'
				&& document.documentElement.clientWidth != 0) {
			size = [
				document.documentElement.clientWidth,
				document.documentElement.clientHeight
			];
		}
		else {
			size = [
				document.getElementsByTagName('body')[0].clientWidth,
				document.getElementsByTagName('body')[0].clientHeight
			];
		}
		return size;
	},
	/**
	* Gets the dimenstions of the page
	* @version 1.0
	* @returns Array
	* @author Greg Shiers
	*/
	getPageDimensions : function() {
	var body = document.getElementsByTagName("body")[0];
	var bodyOffsetWidth = 0;
	var bodyOffsetHeight = 0;
	var bodyScrollWidth = 0;
	var bodyScrollHeight = 0;
	var pageDimensions = [0, 0];
		if (typeof document.documentElement != "undefined" && typeof document.documentElement.scrollWidth != "undefined") {
			pageDimensions[0] = document.documentElement.scrollWidth;
			pageDimensions[1] = document.documentElement.scrollHeight;
		}
		bodyOffsetWidth = body.offsetWidth;
		bodyOffsetHeight = body.offsetHeight;
		bodyScrollWidth = body.scrollWidth;
		bodyScrollHeight = body.scrollHeight;
		if (bodyOffsetWidth > pageDimensions[0]) 	{ pageDimensions[0] = bodyOffsetWidth; }
		if (bodyOffsetHeight > pageDimensions[1]) 	{ pageDimensions[1] = bodyOffsetHeight; }
		if (bodyScrollWidth > pageDimensions[0]) 	{ pageDimensions[0] = bodyScrollWidth; }
		if (bodyScrollHeight > pageDimensions[1]) 	{ pageDimensions[1] = bodyScrollHeight; }
		return pageDimensions;
	}
}
/* Add these methods to the JS page */
Element.addMethods(SI_Works_Custom);
Element.addMethods(SI_Works_Validation);
//Element.addMethods(SI_Works_Tables);
Element.addMethods(SI_Works_Window_Objects);
Element.addMethods(SI_Works_Dialog_Controls);

Event.observe ( window, "load" , function ( e ) {
	
})




// ]]>

