// <![CDATA[
/*
* Copyright: 2005 - 2007 SI Works Internet Solutions
* If you have come across this page, its cause you are snooping through code, and are generally a developer as such
* If you would like to use some of the code on this page, please simply email support@siworks.co.za and ask permission
* it would be much appreciated, as we have worked very hard on these func.tions() and scri.pts()
* 
* Note: All functions below are to make sure that we are sticking to standards and are mainly
* for visual effects and loading events and handlers.
*
* General functions to use accross all sites and use for loading events
* @page common.functions.js
* @version 2.3.0
* @author Greg Shiers, Jarratt Ingram (SI Works Internet)
* @copyright: SI Works Internet Solutions 2005 - 2007
*/

/*
* Function to grab one or more elements
* @usage $('element1','element2')
* @returns Array
* @version 1.1
*/
/* function $( ) {
	var elements = new Array( );
	for ( var i = 0; i < arguments.length; i++ ) {
		var element = arguments[i];
		if ( typeof element == 'string' )
			element = document.getElementById ( element );
		if ( arguments.length == 1 )
			return element;
		elements.push ( element );
	}
	return elements;
} */
/**
* Function that creates an element
* @param element
* @version 1.2
* @returns string
* @author Greg Shiers
*/
function $_C ( element ){
	if ( typeof document.createElement != 'undefined' ) {
		return document.createElement(element);
	}
	else {
		alert('Your browser does not support document.createElement')
	}
}
/*
* 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 openWindow ( name , url , width , height , scroll ) {
	// Set Variables to position screen in the middle of the page
	var left = (screen.width) ? (screen.width-width)/2 : 0;
	var top = (screen.height) ? (screen.height-height)/2 : 0;

	// Open the new window
	// Set all to 0 except status cuase we need to show this for usability
	window.open(url,name,'left='+left+',top='+top+',toolbar=0,location=0,directories=0,status=1, menubar=0,scrollbars='+scroll+',resizable=0,width='+width+',height='+height);
}
/*
* Function to count charactors on a text field
* @usage countText ( field, countfield, maxlimit )
* @param ( field, countfield, maxlimit ) field: textarea that we are counting, countfield: field that updates with the true left charactors, maxlimit: max charactors
* @version 1.5
*/
function countText ( field, countfield, maxlimit ) {
	if ( document.getElementById && document.createTextNode ){
		// Lets set come variables
		var fld = $( field );
		var count = $( countfield );
		// if too long...trim it!
		( fld.value.length > maxlimit ) ? fld.value = fld.value.substring( 0, maxlimit ) : count.innerHTML = ( maxlimit - fld.value.length )
	}
}
/*
* Function to show or hide an element based on mouse event
* @usage showHideElement ( element )
* @param ( element ) element that needs the function applied
* @version 1.5
*/
function showHideElement ( element ) {
	var div = document.getElementById( element );
	( div.style.display == "block" || div.style.display == "" ) ? div.style.display = "none" : div.style.display = "block" ;
}
/*
* Function to show or hide an element based on mouse event via a checkbox
* @usage showHideCheckbox ( element )
* @param ( element ) checkbox that needs the function applied
* @version 1.4
*/
function showHideCheckbox ( element , checkbox ) {
	// set the element variables
	var div = document.getElementById ( element ), chk = document.getElementById ( checkbox );
	( chk.checked ) ? div.style.display = "none" : div.style.display = "block";
}
/*
* Function to show or hide an element based on mouse event via a radio button
* @usage showHideRadioButton ( element, show )
* @param ( element, show ) radio button that needs the function applied, show: if you want to show the element or hide it
* @version 1.2
*/
function showHideRadioButton ( element , show ) {
	// set the element variables
	var div = document.getElementById ( element );
	( show ) ? div.style.display = "block" :  div.style.display = "none";
}
/*
* Function to show or hide an element based on mouse event via a radio button
* @usage showHideRadioButton ( element , selectbox , index )
* @param ( element , selectbox , index ) element: element effected, selectbox: the select box that needs to be validated, index: which index is the one to be selected
* @version 1.5
*/
function showHideSelectBox ( effected , selectbox , index ) {
	// set the element variables
	var element = $( effected ), sel = $( selectbox );
	( sel.selectedIndex != index ) ? element.style.display = "none" : element.style.display = "block";
}
/*
* Function to show or hide an element based on mouse event via a radio button
* @usage showHideRadioButton ( element , selectbox , index )
* @param ( element , selectbox , index ) element: element effected, selectbox: the select box that needs to be validated, index: which index is the one to be selected
* @version 1.5
*/
function showHideSelectBoxStatic ( effected , selectbox , index, status ) {
	// set the element variables
	var element = $( effected ), sel = $( selectbox );
	if ( sel.selectedIndex == index ) {	
		element.style.display = "none"
	}
	else {	
		element.style.display = "block"
	}
	
}
/*
* Function to make you only check one checkbox for the package
* @version 1.0
* source: http://www.sitepoint.com/forums/showthread.php?t=163809&highlight=checkboxes+act+radio+buttons
*/
function checkOnlyOneCheckbox (which) {
	var form = $('client_add_step1_form');
	var input, i = 0, inputs = form.getElementsByTagName('input');
	while (input = inputs.item(i++))
	if (input.getAttribute('type') == 'checkbox' && input.getAttribute('name') == 'client_package_checks')
//	input.onclick = function() {
		if (which.checked) {
			$('client_package').value = which.value;
			var grp = which.form.elements[which.name];
			var grplen = grp.length;
				do
					if (grp[--grplen] != which)
						grp[grplen].checked = false;
				while (grplen);
		}
//	}	
}


/*
* Function document.getElementsByClassName to find all element with a certain className
* @usage element.getElementsByClassName ( clsName )
* @param ( clsName ) the class you want to find
* @version 1.5
* @author 
*/
document.getElementsByClassName = function( clsName ){
	// Make the return value into a new arry
	var retVal = new Array();
	// Go through ALL Elements in the DOM by using the *
    var elements = document.getElementsByTagName("*");
	// Loop through ALL elements as defined
    for( var i = 0;i < elements.length;i++ ) {
		// Find all elements with a className
        if( elements[i].className.indexOf(" ") >= 0 ){
            var classes = elements[i].className.split( " " );
            for( var j = 0; j < classes.length; j++ ){
                if( classes[j] == clsName )
					// Return all elements by using the push() method which adds the next
					// element to the array of elements with the same classname
                    retVal.push( elements[i] );
            }
        }
        else if(elements[i].className == clsName)
            retVal.push ( elements[i] );
    }
	// Return the value
    return retVal;
}
/*
* Function to add a load event to the page when it loads
* to load a function with parameters we need to use addLoadListener ( function () { loadfunction ( parameters ) })
* @usage addLoadListener ( func )
* @param ( func ) the function you want to load
* @version 1.4
* @author 
*/
function addLoadListener( func ) { 
	if (typeof window.addEventListener != 'undefined') { //Check for window.addEventListener (FireFox)
    	window.addEventListener('load', func, false); // Set for FF
  	}
  	else if (typeof document.addEventListener != 'undefined') { // Check for document.addEventListener (FireFox)
    	document.addEventListener('load', func, false);
  	}
  	else if (typeof window.attachEvent != 'undefined') { // Check for window.attachEvent (IE)
    	window.attachEvent('onload', func);
  	}
  	else {
    var oldfn = window.onload;
    	if (typeof window.onload != 'function') {
      		window.onload = func;
    	}
    	else {
      		window.onload = function() {
        		oldfn();
        		func();
      		};
    	}
  	}
}
/*
* Function to add a event to a certain element
* to load a event with parameters we need to use attachEventListener ( function () { loadfunction ( parameters ) })
* @usage attachEventListener (  target, eventType, functionRef, capture  ) target: which element, eventType: which event, functionRef: which function, capture: true / false;
* @param ( func ) the function you want to load
* @version 1.1
* @returns Boolean
* @author 
*/
function attachEventListener( target, eventType, functionRef, capture ) {
	if (typeof target.addEventListener != "undefined") { //Check for target.addEventListener (FireFox)
		target.addEventListener(eventType, functionRef, capture); // Set the listener
	}
	else if (typeof target.attachEvent != "undefined") { // Check for target.attachEvent (IE)
		target.attachEvent("on" + eventType, functionRef);
	}
	else {
		eventType = "on" + eventType;

		if (typeof target[eventType] == "function") {
			var oldListener = target[eventType];

			target[eventType] = function() {
				oldListener();
				return functionRef();
			}
		}
		else {
			target[eventType] = functionRef;
		}
	}
	return true;
}
/*
* Function to remove an event to a certain element
* to load a event with parameters we need to use attachEventListener ( function () { loadfunction ( parameters ) })
* @usage detachEventListener (  target, eventType, functionRef, capture  ) target: which element, eventType: which event, functionRef: which function, capture: true / false;
* @param ( func ) the function you want to load
* @version 1.2
* @author 
*/
function detachEventListener( target, eventType, functionRef, capture ) {
	if (typeof target.removeEventListener != "undefined") {
		target.removeEventListener(eventType, functionRef, capture);
	}
	else if (typeof target.detachEvent != "undefined") {
		target.detachEvent("on" + eventType, functionRef);
	}
	else {
		target["on" + eventType] = null;
	}
	return true;
}
/*
* Function to stop the default action of a element
* @usage stopDefaultAction ( event ) which event we want to stop
* @param ( event ) the event we want to stop
* @version 1.1
* @returns Boolean
* @author 
*/
function stopDefaultAction ( event ) {
	event.returnValue = false;
	if (typeof event.preventDefault != "undefined") {
	    event.preventDefault();
  	}
  return true;
}
/*
* Function to scroll to the top of the page once form is submitted
* @usage scrollToPagetop ( ) which event we want to stop
* @version 1.0
*/
function scrollToPagetop ( ) {
	scroll(0,0);
}
/*
* Function to clear the inner HTML of an element and focus on the next input
* @usage clearInnerHtml ( element , selectbox , index )
* @param element 
* @param focus_element 
* @version 1.5
*/
function clearInnerHtml ( element , focus_element ) {
	// If the element is defined then 
	if ( typeof element != "undefined" ) { 
		$( element ).innerHTML = '';
	}
	// If there is an element to focus on and its defined then focus on it
	if ( focus_element ) {	
		$ ( focus_element ).focus();
	}
}
// Array.prototype.inArray
// inArray Prototype Array object by EmbiMedia
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};



/*
* 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";
	}
}
// Load this function on page load
addLoadListener ( externalLinks );

/*
* Function to preload any icons / images that we might use for dynamic content
* @usage preloadImages (  ) 
* @version 1.5.2
* @author 
*/
function preloadImages () {
	// This is not a function, but will load images on the fly as we moive along parsing the page
	var names = ['progress'];
	// Create an object to pass the above array through the for loop below
	var objects = [];
	
	// Loop through all the images if there are more than 1
	for (var i = 0; i < names.length; i++) {
		objects[i] = new Image(); // Create the image
		objects[i].src = '/images/icons/'+names[i] + '.gif'; // Give it a src
	}
}
// Load this function on page load
addLoadListener ( preloadImages );

/**
* Swaps the main image on the products page
* @param targetID
* @param imageSRC
* @param imageID
* @param hintID
* @param productID
* @version 
* @returns 
* @type 
* @author Greg Shiers
*/
function swapImage( targetID , imageSRC , imageID , hintID , productID ){
	// Try and see if we've found the relevant images and divs
	try {
	// We make sure that the flower care box is hidden
	
		if( $( targetID ) ) {
			$( targetID ).setAttribute('src', imageSRC );
			if( $(hintID) ){
				$(hintID).setAttribute('href', '/hint/'+productID+'/'+imageID);
			}		
		}
		
	}
	catch ( error ) {
		return null;
	}
}

/**
* Swaps the main image on the products page
* @param elements
* @version 
* @returns 
* @type 
* @author Greg Shiers
*/

function clearForm ( form ){
	var form = document.forms[0];
		
	// Loop through all elements in the form
	for ( var i = 0; i < form.length; i++ ) {
		var inputs = form[i]; // Set inputs as each of the form[i]
		switch ( inputs.type ) {
			// Check for input
			case 'text' :
				inputs.value = '';
			break;
			// Check for radio box or checkbox
			case 'radio' :
			case 'checkbox' :
				inputs.checked = false;
			break;
			// Check for select boxes
			case 'select-one' :
			case 'select-multiple' :
				inputs.selectedIndex = 0;
			break;
		}
	}
}

/**
* Check if a select box is selected and then show or hide another element
* @param element
* @param selectbox
* @param selectindex
* @version 1.0
* @author Greg Shiers
*/
function checkSelectStatus ( element, selectbox, selectindex ) {	
	if ($(selectbox).selectedIndex == selectindex ) { 
		$(element).style.display = "none";
	}
	else {	
		$(element).style.display = "block";
	}
}
addLoadListener(function() { 
	if($('client_security')) {	
		checkSelectStatus('m_answer','client_security',0);
	}
});
/**
* Function to get the target of an Event
* @param event 
* @version 1.2
* @returns String
* @author Greg Shiers
*/
function getEventTarget( event ) {
	var targetElement = null;
	if (typeof event.target != "undefined") {
		targetElement = event.target;
	}
	else {
		targetElement = event.srcElement;
	}
	while (targetElement.nodeType == 3 && targetElement.parentNode != null) {
		targetElement = targetElement.parentNode;
	}
	return targetElement;
}

/**
* Fucntion to find the scroll position of an element
* @version 1.4
* @returns Array
* @author Greg Shiers
*/

function getScrollingPosition( ) {
	//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;
}


/**
* Function to find elements by an Attribute name
* @param attribute
* @param attributeValue
* @version 1.9
* @returns Array
* @type Array
* @author Greg Shiers
*/
function getElementsByAttribute( attribute , attributeValue ) {
	var elementArray = new Array();
	var matchedArray = new Array();
	if (document.all) {
		elementArray = document.all;
	}
	else {
		elementArray = document.getElementsByTagName("*");
	}
		for ( var i = 0; i < elementArray.length; i++ ) {
			if (attribute == "class") {
				var pattern = new RegExp("(^| )" + attributeValue + "( |$)");
				if (elementArray[i].className.match(pattern)) {
					matchedArray[matchedArray.length] = elementArray[i];
				}
			}
			else if (attribute == "for") {
				if (elementArray[i].getAttribute("htmlFor") || elementArray[i].getAttribute("for")) {
					if (elementArray[i].htmlFor == attributeValue) {
						matchedArray[matchedArray.length] = elementArray[i];
					}
				}
			}
			else if (elementArray[i].getAttribute(attribute) == attributeValue) {
				matchedArray[matchedArray.length] = elementArray[i];
			}
		}
	return matchedArray;
}

/**
This is where we add the funciton to create the tool tip that's available on all pages
There are 3 functions, one to load the functions to the page, and the other one to create the tip
The other to remove the tip
*/
/**
* Function to initialize the tool tips on the page
* @version 1.0
* @returns Boolean
* @type 
* @author Greg Shiers
*/
function initTooltips() {
	var tips = getElementsByAttribute("class", "hastooltip");
	for ( var i = 0; i < tips.length; i++ ) {
		attachEventListener(tips[i], "mouseover", showTip, false);
		attachEventListener(tips[i], "mouseout", hideTip, false);
	}
	return true;
}

/**
* Function that Generates the tool tip
* @param event
* @version 1.8
* @returns Boolean
* @author Greg Shiers
*/
function showTip( event ) {
	if (typeof event == "undefined") {
		event = window.event;
	}
	var target = getEventTarget(event);
	while (target.className == null || !/(^| )hastooltip( |$)/.test(target.className)) {
		target = target.parentNode;
	}
	var tip = document.createElement("div");
	var content = target.getAttribute("title");

	target.tooltip = tip;
	target.setAttribute("title", "");
	
	if (target.getAttribute("id") != "") {
		tip.setAttribute("id", target.getAttribute("id") + "tooltip");
	}

	tip.className = "tooltip";
	tip.appendChild( document.createTextNode( content ) );

	var scrollingPosition = getScrollingPosition();
	var cursorPosition = [0, 0];
	
	if (typeof event.pageX != "undefined" && typeof event.x != "undefined") {
		cursorPosition[0] = event.pageX;	
		cursorPosition[1] = event.pageY;
	}
	else {
		cursorPosition[0] = event.clientX + scrollingPosition[0];
		cursorPosition[1] = event.clientY + scrollingPosition[1];
	}
	// Lets create the tool tip now what we've got the scroll possie
	tip.style.position = "absolute";
	tip.style.left = cursorPosition[0] + 10 + "px";
	tip.style.top = cursorPosition[1] + 10 + "px";
	tip.style.zIndex = "3000";
	document.getElementsByTagName("body")[0].appendChild( tip );	
	return true;
}

/**
* Function that remove the tool tip once its been created above
* @param event
* @version 1.6
* @returns Boolean
* @author Greg Shiers
*/
function hideTip( event ) {
	if ( typeof event == "undefined" ) {
		event = window.event;
	}
	var target = getEventTarget( event );

	while ( target.className == null || !target.className.match(/(^| )hastooltip( |$)/) ) {
		target = target.parentNode;
	}
	if ( target.tooltip != null ) {
		target.setAttribute ( "title", target.tooltip.childNodes[0].nodeValue );
		target.tooltip.parentNode.removeChild ( target.tooltip );
	}
	return false;
}
addLoadListener (initTooltips);


/**
* Finds the view point size of an element
* @version 1.0
* @author Greg Shiers
*/
function getViewportSize() {
	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
*/
function getPageDimensions() {
	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;
}

function createEventDialog( width, height, message ) {
	var body = document.getElementsByTagName("body")[0];
	var pageDimensions = getPageDimensions();
	var viewportSize = getViewportSize();
	if (viewportSize[1] > pageDimensions[1]) {
		pageDimensions[1] = viewportSize[1];
	}
	var cover = $_C("div");
	cover.setAttribute("id", "cover");
	cover.style.position = "absolute";
	cover.style.left = "0";
	cover.style.top = "0";
	cover.style.zIndex = "2000";
	cover.style.width = pageDimensions[0] + "px";
	cover.style.height = pageDimensions[1] + "px";
	body.appendChild(cover);

	try {
		var dialog = $_C("div");
		dialog.className = "dialog";
		dialog.id = "event";
		dialog.style.visibility = "hidden";
		dialog.style.position = "absolute";
		dialog.style.width = width+"px";
		dialog.style.height = height+"px";
		dialog.style.zIndex = 4000;
		body.appendChild ( dialog );
		var scrollingPosition = getScrollingPosition();
		
		dialog.style.left = scrollingPosition[0] + parseInt(viewportSize[0] / 2) - parseInt(dialog.offsetWidth / 2) + "px";
		dialog.style.top = scrollingPosition[1] + parseInt(viewportSize[1] / 2) - parseInt(dialog.offsetHeight / 2) + "px";
		dialog.style.visibility = "visible";
		dialog.innerHTML = message;
	}
	catch(error) {
		cover.parentNode.removeChild(cover);
		return true;
	}
	return false;
}

function closeEventDialog() {
	var cover = $("cover");
	var event = $("event");
	cover.parentNode.removeChild(cover);
	event.parentNode.removeChild(event);
	return false;
}

// Check if there is a hidden field for login, if there is, then we show this dialog box
function firstLogin () {
	var html;
	var website = $('first_login').title;
	html = '<div class="success">Your registration was successfull!</div>';
	html += '<div class="pt10 pl10 pr10 pb10" style="font-weight: normal">Welcome to IPCO Web, your website has been created and you\'re ready to start adding and editing pages.</div>';
	html += '<div class="pt10 pl10 pr10 pb10" style="font-weight: normal">You can start sending SMSes immediately from your control panel, simply by clicking on "My mobile manager" and to start editing your your website click on "My website" to enter your new website in EDIT mode</div>';
	html += '<div class="pt10 pl10 pr10 pb10">Please take some time to read through our user manual, where you will find all the information you need<br /><a href="/downloader.php?file=manual" class="blue" style="color: #0099ff !important" title="Click here to download the manual"><img src="/images/icons/pdf.png" class="icor" /> Download the user manual </a></div>';
	html += '<hr />';
	html += '<input type="button" value="Thanks, I have everything I need (close)" onclick="closeEventDialog()" />&nbsp;&nbsp;&nbsp;';
	html += '<input type="button" value="Edit my website now" onclick="location.href=\''+website+'\'" />';
	createEventDialog('450','280', html);
}
addLoadListener (function() {
	
	if ( $('first_login') ) {
		firstLogin();
	}
	
})


// ]]>