// <![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: 159 $
* $Id: siworks.extention.js 159 2009-11-04 12:45:00Z greg $
* 
* Copyright:  SI Works internet var year = new Date(); year.getFullYear();
* 
* Email:  support@siworks.co.za
* Author: Greg Shiers, Jarratt Ingram
******************************************************************************************/
/*
* Opens a rel="external" in a new window, to validate in XHTML strict
* This code was found on http://www.sitepoint.com/article/standards-compliant-world in order to be able to validate a page with 
* opening a new link in a new window without target="_blank"
* @usage addLoadListener ( externalLinks );
* @version 1.0
* @author www.sitepoint.com
*/
function externalLinks () {
	if (!document.getElementsByTagName) return; // Check for DOM / Browser compatability
	var anchors = document.getElementsByTagName("a"); // Set var, which will narrow down all the a elements in the document
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "external")
		anchor.target = "_blank";
	}
}
/*
* Function to open a new window
* @usage openWindow(name, url, width, height, scroll )
* @param (name, url, width, height, scroll ) name: window name, url: page to be opened, width: window width, height: window height, scroll: window scroll
* @version 1.0
*/
function openProductWindow ( url , name ) {
	if ( $('reseller_product').selectedIndex != 0 ) {
		// Open the new window
		// Set all to 0 except status cuase we need to show this for usability
		window.open( url , name );
	}
	else {
		return false;
	}
}


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;
		}
	}
}

/**
* 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 )
		}
	},
	/**
	* loads the events onto the header rollover classes
	* @version 1.0
	* @author Greg Shiers
	*/
	loadHeadersAndSubMenu : function () {
		if ($('header')) {
			/**
			** Here we check wich of the headers is active.
			**/
			var origional = $$('#header div.active')[0].readAttribute('id');
			//var identity = this.readAttribute('id').split("_")[0];
			/**
			** create an array from the navigation's ul's childelements using prototype's
			** $A function, then loop through them each using .each itterator
			**/
			$A($('header').down('div').next().down('ul').childElements()).each (function ( element, index ) {
				element.down('a').observe("click", function ( event ) {
					/**
					** Stop the default event
					**/
					event.stop();
					if ( this.hasClassName('active') ) {
						return;
					}
					else {
						/**
						** navigate through the divs with active class, and remove the class.
						** remember to fade the element so that when it's opacity is set to 0
						** the element has display: none;
						**/
						$$('#header div.active')[0].removeClassName('active').fade({duration: 0.7});
						/**
						** loop through all li's with active class, and remove the active class
						** so that we can set the correct active class relevant to the link we 
						** click on
						**/
						$A($$('#header_options li a.active')).each(function ( element ) {
							element.removeClassName('active');
						});
						/**
						** set the active link on the correct li
						**/
						this.addClassName('active');
						
						/**
						** add the active class to the correct element (for the main header) and
						** use the appear effect to fade it in.
						**/
						$(this.readAttribute('class').split(' ')[0]).addClassName('active').appear({duration: 0.7});
					}
				})
			})
		}
	},
	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 } );
	},
	swapRegion: function (element, target , selects ) {
		if(!SI_Works_Validation.selected_index($(element), 197)) {
			$(target).setStyle({'display' : 'block'});
			$(selects).setStyle({'display' : 'none'});}
		else {
			$(target).setStyle({'display' : 'none'});
			$(selects).setStyle({'display' : 'block'});
		}
	},
	resellerFilter : function ( sectionID ) {
		
		var page = location.pathname;
		var page_stripped = page.split('/section');
		
		if (page_stripped[1]) {
			page = page_stripped[0];
		}
		
		location.href = page+'/section/'+sectionID;
	},
	resellerListFilter : function ( sectionID ) {
		var address;
		if ( sectionID == '' ) {
			address = '/resellers/index/list';
		}
		else {
			address = '/' + sectionID + '/resellers/index/list';
		}
		location.href = address;
	}
}


/**
* 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>' + Config.delete_message + '</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" />' + Config.delete_confirm + '</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) {
														window.reload();
														//$( 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)
		});
	}
	if ($('header')) { Element.loadHeadersAndSubMenu(); }
	externalLinks();
})

document.observe ( 'dom:loaded' , function () {
	if ($('multi_members')) { 
		new Carousel($('multi_members').down('#inf_members'), $('multi_members').select('.profile'), $('multi_members').select('a.carousel-control'), {
			duration: 0.5,
			circular: false,
			visibleSlides: 4,
			wheel: false
		})
	}
	
	if ($('icon_legend') && $('icon_legend_block')) {
		new Tip($('icon_legend'), $('icon_legend_block').innerHTML, {
			width: 200,
			offset: { x: 0, y: -2 },
			radius: 5,
			border: 4,
			stem: 'bottomLeft',
			hook: { tip: 'bottomLeft', mouse: true }
		});
	}
	$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())
		})
	});
	
	/** 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)
			}
		})
		
	}
	/**
	** Check for the logout element for the admin tool
	**/
	if ( $('logout_link') ) {
		/**
		** If we have the element then we fire the lightview logout
		**/
		$('logout_link').observe ("click", function ( event ) {
			Event.stop(event);
			Lightview.show({ 
				href: '/admin/logout.php', 
				rel: 'ajax', 
				options: { 
					topclose: true,
					width: 400, 
					height: 80
				}
			});		
		})
	}
	/**
	** Check if there is a newsletter tems element
	**/
	if ( $('newsletter_terms') ) {
		/**
		** If there is, we need to fire lightview.
		**/
		$('newsletter_terms').observe ("click", function ( event ) {
			Event.stop(event);
			Lightview.show({ 
				href: '/ajax/index/terms', 
				rel: 'ajax', 
				options: { 
					topclose: true,
					width: 600, 
					height: 500
				}
			});		
		})
	}
	if ( $('product_list')) {
		
		$('swap_image').observe('click', function ( event ) {
			event.stop();
			Lightview.show({ 
				href: '/image.php?module=product&id=10',
				options: { 
					topclose: true,
					autosize: true,
					width: 220, 
					height: 240
				}
			});
		})
		
		$('product_list').observe('change', function() {
			var ID = this.value;
			$('swap_image').writeAttribute('src', '/image.php?module=product&id='+ID+'&resize=150')
			$('swap_image').up().writeAttribute('href', '/image.php?module=product&id='+ID);
			$('swap_image').stopObserving('click');
			$('swap_image').observe('click', function ( event ) {
				event.stop();
				Lightview.show({ 
					href: '/image.php?module=product&id='+ID,
					options: { 
						topclose: true,
						autosize: true,
						width: 220, 
						height: 240
					}
				});
			})
		})
	}
	if ( $('protofade') ) {
		new Protofade('protofade');
	}

});



// ]]>

