// <![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.3
* @author Greg Shiers, Jarratt Ingram (SI Works Internet)
* @copyright: SI Works Internet Solutions 2005 - this.year();
*/
/*
* Function to get the value of a cookie
* @usage GetCookie ( name )
* @param name
* @version 1.5
*/
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
/*
* Function to set a new Cookie
* @usage setCookie ( name, value, expires, path, domain, secure )
* @param name
* @param value
* @param expires
* @param path
* @param domain
* @param secure
* @version 1.0
*/
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );
}
/*
* Function to check all checkboxes within a table
* @usage selectCookie ( name , path , domain )
* @param name
* @param path
* @param domain
* @version 1.2
*/
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) {
		document.cookie = name + '=' +
		( ( path ) ? ';path=' + path : '') +
		( ( domain ) ? ';domain=' + domain : '' ) +
		';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	}
}

/*
* 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 select or deselect all options in a multiple select element
* @usage selectUnselectAll ( name , path , domain )
* @param txt
* @param sel
* @version 1.2
*/

function selectUnselectAll ( txt , sel ) {
		// find the table to select from
	var selectbox  	= $(sel).getElementsByTagName('option');
	var text		= $(txt);
	// Check if the innerHTML of the href is "Select all"
	if( text.innerHTML == "Select All" ) {
		for (i=0; i < selectbox.length; i++) {
			selectbox[i].selected = true;
		}
		text.innerHTML = "De-Select All";
	}
	else if ( text.innerHTML == "De-Select All" ) {
		for (i=0; i < selectbox.length; i++) {
			selectbox[i].selected = false;
		}
		text.innerHTML = "Select All";
	}
	else {
		alert('There has been an error, administrators have been notified, sorry about it');
		return false;
	}
}
/*
* Function to change the tabs on the articles page and swap between these tabs
* @usage swapTabContentByElementID ( ID )
* @param ID
* @version 1.2
*/
function swapTabContentByElementID ( ID ) {
	if ( ID == 'related_articles' ) {
		$('related_link').addClassName('selected_link').removeClassName('unselected_link');
		$('related_author_link').addClassName('unselected_link').removeClassName('selected_link');
		$('related_other_link').addClassName('unselected_link').removeClassName('selected_link');
		$('related_articles').removeClassName('none');
		$('related_by_this_author').addClassName('none');
		$('others_by_this_author').addClassName('none');
	}
	if ( ID == 'related_by_this_author' ) {
		$('related_link').addClassName('unselected_link').removeClassName('selected_link');
		$('related_author_link').addClassName('selected_link').removeClassName('unselected_link');
		$('related_other_link').addClassName('unselected_link').removeClassName('selected_link');
		$('related_articles').addClassName('none')
		$('related_by_this_author').removeClassName('none');
		$('others_by_this_author').addClassName('none');
	}
	if ( ID == 'others_by_this_author' ) {
		$('related_link').addClassName('unselected_link').removeClassName('selected_link');
		$('related_author_link').addClassName('unselected_link').removeClassName('selected_link');
		$('related_other_link').addClassName('selected_link').removeClassName('unselected_link');
		$('related_articles').addClassName('none')
		$('related_by_this_author').addClassName('none');
		$('others_by_this_author').removeClassName('none');
	}
}

/*
* getting elements by classname and attached to a certain element
* This code was found on http://www.sitepoint.com/article/rotate-content-with-dhtml/
* @version 1.0
* @author George Chiang / www.sitepoint.com
*/
var curcontentindex=0;
var messages=new Array();
/*
* getting elements by classname and attached to a certain element
* This code was found on http://www.sitepoint.com/article/rotate-content-with-dhtml/
* @version 1.0
* @param classname
* @author George Chiang / www.sitepoint.com
*/
function getElementByClass(classname){
	var inc=0;
	var alltags=document.all? document.all : document.getElementsByTagName("*");
	for (i=0; i<alltags.length; i++){
		if (alltags[i].className==classname)
		messages[inc++]=alltags[i];
	}
}
/*
* we are going to use this code to rotate articles on the homepage and mix it in with
* some effects for them to fade in / out
* This code was found on http://www.sitepoint.com/article/rotate-content-with-dhtml/
* @version 1.0
* @author George Chiang / www.sitepoint.com
*/
function rotatecontent(){
	/* get current message index (to show it): */
	curcontentindex = ( curcontentindex < messages.length-1 )? curcontentindex+1 : 0;
	/* get previous message index (to hide it) */
	prevcontentindex = ( curcontentindex==0 ) ? messages.length-1 : curcontentindex-1;
	messages[prevcontentindex].setStyle({display: "none"}); //hide previous message
	messages[curcontentindex].appear(); //show current message
}
/*
* dormat function with tteo cecimal places
* @version 1.0
* @author  www.siworks.co.za.com
*/
function formatNumber( num ) {
	num = num.toString().replace(/\$|\,/g,'');
	var cents,sign;
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();

	if( cents < 10 )
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3)) + 
	num.substring(num.length-(4*i+3));
	
	return (((sign)?'':'-') + num + '.' + cents);
}
	
/*
* we are going to use this code to calculate the Body mass index
* a formular for this calculation is:
* 
*  BMI = ( kg/mē ) weight in kilograms 
*
* @version 1.0
* @author  www.siworks.co.za.com
*/
function do_calculate_bmi(height, weight){
	 var bmi = weight / (height*height);
	 
	 $('bmi_results').innerHTML = "<strong>Your calculated BMI is:</strong> "+formatNumber(bmi);
}

/*
* we are going to use this code to calculate the waist / hip ratio
* a formular for this calculation is:
* 
*  WHR = ( waist/hips) Waist/Hip
*
* @version 1.0
* @author  www.siworks.co.za.com
*/
function do_calculate_whr(waist, hips){
	 var whr = waist / hips;
	 
	 $('whr_results').innerHTML = "<strong>Your calculated Waist- Hip Ratio is:</strong> "+formatNumber(whr);
}

/*
* 
*/
Event.observe (window, "load", function ( event ) {
	/*
	* set up the external links function to open rel="external" hrefs in a new window
	*/
	externalLinks();
	/*
	* On the view of the full articles, we are going to set up the function
	* first we check if the tabs exits and then load them to the browser
	*/
	if ( $('related_link') || $('related_author_link') || $('related_other_link')) {
		$('related_link').observe ("click", function ( event ) {
			swapTabContentByElementID('related_articles');
			Event.stop( event );
		})
		$('related_author_link').observe ("click", function ( event ) {
			swapTabContentByElementID('related_by_this_author');
			Event.stop( event );
		})
		$('related_other_link').observe ("click", function ( event ) {
			swapTabContentByElementID('others_by_this_author');
			Event.stop( event );
		})
	}
	/*
	* set up the roatateArticles() function for the homepage, first we check if the element
	* with the articles exists which it will only on the homepage
	* then we set up the rotating of articles
	*/
	if ($('features_articles')) {
		getElementByClass("articles");
		setInterval("rotatecontent()", 1*10000);	
	}
	/**
	** Lets check if we are on the buy page, so that we can load tips onto the information
	** icons that are displayed in the table.
	**/
	if ( $('purchase_table') ) {
		$A($$('.tips')).each (function ( key ) {
			var package = key.up(2).down().innerHTML;
			var duration = key.up(2).down(1).innerHTML;
			new Tip(key, 'Click on this icon for find our more information on the <strong>' + duration +'&nbsp;' + package +'</strong> package.', {
			  stem: 'bottomLeft',
			  hook: { tip: 'bottomLeft', mouse: true }
			});
		})
	}
	/*
	* When the page loads we are going to fetch the Forex and the Weather from
	** Ajax page, which will conrol the dispaly and read the information from a cache
	*/
	$('forex_feed').update("Fetching Forex...");
	$('weather_feed').update("Fetching Weather...");
	/*
	* set a timeout of 1 second after the page loads before the ajax is fired
	* just try to give the page a little time to load all the other functions
	* before we fire the ajax off, some browsers are a little tricky
	*/
	setTimeout(function() {
		try {
			/*
			* We fetch the forex feeds via Ajax 
			*/
			new Ajax.Request ('/ajax.php?menu=forex', {
				method : 'get',
				onSuccess : function ( transport ) {
					$('forex_feed').update(transport.responseText);
				},
				onFailure : function ( ) { 	
					$('forex_feed').update('Sorry feed unavailable');
				}
			});
			/*
			* We fetch the weather feeds via Ajax 
			*/
			new Ajax.Request ('/ajax.php?menu=weather', {
				method : 'get',
				onSuccess : function ( transport ) {
					$('weather_feed').update(transport.responseText);
				},
				onFailure : function ( ) { 	
					$('weather_feed').update('Sorry feed unavailable');
				}
			});
		}
		catch ( error ) {
			return false;
		}	
}, 1000 );

	/** check on click for body mass index calculators **/
	if ($('calculate_bmi')) {		
		/** check on focus of the calculate_bmi field **/
		$('calculate_bmi').observe('click', function() {
			do_calculate_bmi($F('bmi_height'),$F('bmi_weight'));
		});
	}
	
	/** check on click for waist/hip ration calculators **/
	if ($('calculate_whr')) {		
		/** check on focus of the calculate_bmi field **/
		$('calculate_whr').observe('click', function() {
			do_calculate_whr($F('whr_waist'),$F('whr_hips'));
		});
	}
});
/*
* Load the toggle checkbox functionality to the screen
*/
	Event.observe (window, "load", function () {
		var toggle = new Toggler('messages_etc');
			toggle.start();
	})
/* ==============================================================
    Toggler v0.1
    This is a proof of concept script for mimicking the toggle
    functionality of some desktop applications like Adobe Photoshop.

    Jonathan Snook
    http://snook.ca/
    June 4, 2007

    Usage:
    var toggle = new Toggler('elementId');
    toggle.start(); // start the toggler (enabled by default)
    toggle.stop(); // stop the toggler
*/

function Toggler(elId) {
	var _started = false;
	var _checked = false;
	var _firstTarget;
	var _el;

	init();

	/* hooks up the */
	function init(){
		_el = document.getElementById(elId);
		if(_el) _el.onmousedown = _checkInit;
	}

	function _checkInit(e) {
		e = e || window.event;
		_firstTarget = e.srcElement || e.target;
		if(_firstTarget && _firstTarget.nodeType == 1 && _firstTarget.type == 'checkbox' && !_started) {
			_checked = !_firstTarget.checked;
			_firstTarget.onmouseout = function(){_firstTarget.checked = _checked;}
			_el.onmouseup = _stop;
			_start();
		}
	}

	/* private method to actually toggle the checkbox */
	function _toggleCheckbox(e) {
		e = e || window.event;
		var target = e.srcElement || e.target;
		if(target && target.nodeType == 1 && target.type == 'checkbox') {
			target.checked = _checked;
		}
	}

	/* private method to start the toggle sequence */
	function _start() {
		_started = true;
		_el.onmouseover = _toggleCheckbox;
	}

	/* private method to stop the toggle sequence */
	function _stop(e) {
		e = e || window.event;
		var target = e.srcElement || e.target;
		if(target === _firstTarget) {
			target.checked = !_checked;
		}
		_started = false;
		_el.onmouseup = null;
		_el.onmouseover = null;
		_firstTarget.onmouseout = null;
	}

	/* public methods to start or stop the toggler */
	var o = { 
		start:function(){ 
			init(); 
		},
		stop:function(){ 
			_el.onmousedown = null; 
		}
	};
	return o;
}
/**
* Suckerfish menu loader
* @param 
* @version 
* @returns 
* @type 
* @author Greg Shiers
*/
/* 
sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);
*/
// ]]>