// <![CDATA[
/*
* Copyright: 2005 - this.year() 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@si-works.net and ask permission
* it would be much appreciated, as we have worked very hard on these fucntions and scripts
* 
* Note: We are not checking for DOM complience in any of these 
* functions, as all of the functions are called from another script
* where we will check for DOM (document.getElementById && document.createTextNode)
* this is generally called in the validation page per each form created.
*
* General class that performs and does all ajax calls
* @page dialog.control.class.js
* @version 1.4
* @author Greg Shiers, Jarratt Ingram, Roland Lovelock (SI Works Internet)
* @copyright: SI Works Internet Solutions 2005 - this.year()
*/
/* Define the variables as arrays */
var error 	= [];
var message = [];

/*
* No function, just a list of errors for alerys
* @usage error[number]
* @returns string
* @version 1.0
*/
error[0] = "- Please enter your name\n<br />";
error[1] = "- Please enter your email address.\n<br />";
error[2] = "- Email address incorrectly formatted, need @ and a .\n<br />";
error[3] = "- Please enter your web address.\n<br />";
error[4] = "- Please enter a comment\n<br />";
error[5] = "- UNDEFINED!\n";
error[6] = "- UNDEFINED!.\n";
error[7] = "- UNDEFINED!.\n";
error[8] = "- UNDEFINED!.\n";
error[9] = "- UNDEFINED!.\n";

/**
* @descripton create an overlay div with opacity
* @version 1.4
* @author Greg Shiers
*/
/*
* 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';
	}
}
function createCoverSheet () {
	var body = document.getElementsByTagName("body")[0];
	// find the correct page dimentions
	var pageDimensions = getPageDimensions();
	var viewportSize = getViewportSize();
	if (viewportSize[1] > pageDimensions[1]) {
		pageDimensions[1] = viewportSize[1];
	}
	// Create the cover, and place it right as the first element to the body tag
	// $_C function comes from common.functions.js it's to create a element
	var cover = $_C("div");
	// Set all the attribues of the new cover sheet
	cover.setAttribute("id", "cover");
	cover.style.position = "absolute";
	cover.style.left = "0";
	cover.style.top = "0";
	cover.style.zIndex = "200000";
	cover.style.width = pageDimensions[0] + "px";
	cover.style.height = pageDimensions[1] + "px";
	cover.style.filter = "alpha(opacity=\"50\")";
	cover.style.opacity = 0.5;
	body.appendChild(cover);
	var embed = document.getElementsByClassName("blog");
		for (var i = 0; i < embed.length; i++) {
			//embed[i].style.visibility = 'hidden';
			embed[i].style.display = 'none';
		}
}
/**
* @descripton create the actual dialog window this is now where we start to create the actual dialog box
* @param width
* @param height
* @param from_top
* @param id
* @param title
* @version 1.2
* @author Greg Shiers
*/
function createDialogWindow ( type, width, height, from_top, editor, id, title ) {
	var body = document.getElementsByTagName("body")[0];
	var pageDimensions = getPageDimensions();
	var viewportSize = getViewportSize();
	if (viewportSize[1] > pageDimensions[1]) {
		pageDimensions[1] = viewportSize[1];
	}
	// create the coversheet
	createCoverSheet ();
	// If the coversheet exsists, this means we are going to now create a dialog box
	// over the cover sheet
	if ( $('cover') ) { 
		try {
			var dialog = $_C("div");
			// set the properties of the dialog box we've just created, important we set it to
			// invisible to start with untill it's all set up
			dialog.setAttribute("id", "main_dialog");
			//dialog.style.visibility = "hidden";
			dialog.style.display = "none";
			dialog.style.position = "absolute";
			( width ) ? dialog.style.width = width+"px" : dialog.style.width = width+"px";
			( height ) ? dialog.style.height = height+"px" : dialog.style.height = "auto";
			dialog.style.zIndex = 400000;
			body.appendChild ( dialog );
			var scrollingPosition = getScrollingPosition();
			/**
			* old value: dialog.style.left = scrollingPosition[0] + parseInt(viewportSize[0] / 2) - parseInt(dialog.offsetWidth / 2) + "px";
			**/
			dialog.style.left = scrollingPosition[0] + parseInt(viewportSize[0] / 3.5) - parseInt(dialog.offsetWidth / 2) + "px";
			// if the from_top argument is set we will set the dialog
			// box centered, or a certain px value from the top
			( from_top ) ? dialog.style.top = from_top + scrollingPosition[1] + "px" : dialog.style.top = scrollingPosition[1] + parseInt(viewportSize[1] / 2) - parseInt(dialog.offsetHeight / 2) + "px";
			// Once we've set all the elements of the dialog up, we make is visible
			//dialog.style.visibility = "visible";
			dialog.style.display = "block";
					
			
			switch ( type ) {
				case 'form'	: 
					createDialogContents( "main_dialog",'POST','/blog.comments.ajax.php?id='+id, editor, id, title );
				break;
				case 'comments' :
					createDialogContents( "main_dialog",'GET','/blog.comments.ajax.php?menu=comments&blogid='+id, editor, id, title );
				break;
			}
		}
		// If there is an error with the above try method, then remove whatever's been created
		catch ( error ) {
			alert('Could not create dialog box, incorrect parameter, or function error in trying to create dialog');
			if ($("main_dialog") && $("cover")) {	
				body.removeChild($("main_dialog"));
				body.removeChild($("cover"));
				setTimeout(function(){
					var embed = document.getElementsByClassName("blog");
					for (var i = 0; i < embed.length; i++) {
						//embed[i].style.visibility = 'visible';
						embed[i].style.display = 'block';
					}
				},200)
			}
			
			return true;
		}
	}
	return false;
}
/**
* @descripton creates the contents of the dialog by sending an ajax call to retreive a template or form
* @param element
* @param method
* @param page
* @param editor
* @returns string
* @version 1.2
* @author Greg Shiers
*/
function createDialogContents ( element, method, page, editor,id,title ) {
	var dialog_contents;
	// try and create the innerHTML of the table that hold the results
	try {
		dialog_contents =  '<table cellpadding="0" cellspacing="0" id="dialog" width="100%"><tbody>';
		dialog_contents += '<tr><td class="top_left"></td><td class="top"></td><td class="top_right"></td></tr>';
		dialog_contents += '<tr><td class="content_left"></td><td class="content" id="dialog_content">';
			dialog_contents += '<div class="clear">';
				dialog_contents += '<div class="clear">';
					dialog_contents += '<h2 class="fl">'+ unescape(title)+'</h2><a href="/" onclick="removeDialogWindow(\'blog_post_comment\');return false;" class="fr"><img src="/images/icons/error.png" width="14" height="14" alt="Close this dialog" title="Close this dialog" /></a>';
				dialog_contents += '</div>';
				dialog_contents += '<div class="clear">';
					dialog_contents += '<div class="tab"><a href="/blog.comments.ajax.php?id='+id+'" onclick="return false" id="post">Post a comment</a></div>';
					dialog_contents += '<div class="tab"><a href="/blog.comments.ajax.php?menu=comments&blogid='+id+'" onclick="doSimpleAxajCall(\'Getting comments, please wait...\', \'GET\', \'/blog.comments.ajax.php?menu=comments&blogid='+id+'\', null, \''+id+'\');return false" class="off" id="list">View comments</a></div>';
				dialog_contents += '</div>';
				dialog_contents += '<div class="tabs" id="tabs"><div id="ajax_comments"></div><div id="ajax_blog_form"></div></div>';
			dialog_contents += '</div>';
		dialog_contents += '</td>';
		dialog_contents += '<td class="content_right"></td></tr>';
		dialog_contents += '<tr><td class="bottom_left"></td><td class="bottom"></td><td class="bottom_right"></td></tr></tbody></table>';
	}
	catch ( error ) {
		dialog_contents = 'Unable to load the contents on this window';
	}
	// first we check if the tabs element exists the, 
	// we start with our AJAX Object and get the results back
	// create the ajax object
	$(element).update(dialog_contents);
	if($('ajax_blog_form')){
		$("ajax_blog_form").update(showStatusBar("progress","Loading. Please wait..."));
		new Ajax.Request(page, {
			method: 'get',
			onComplete: function(transport) {
				$("ajax_blog_form").update(transport.responseText);
			},
			onFailure : function () {
				alert('Could not create Ajax Call to retrieve dialog contents');
				if ($("main_dialog") && $("cover")) {	
					body.removeChild($("main_dialog"));
					body.removeChild($("cover"));
					setTimeout(function(){
						var embed = document.getElementsByClassName("blog");
						for (var i = 0; i < embed.length; i++) {
							//embed[i].style.visibility = 'visible';
							embed[i].style.display = 'block';
						}
					},200)
				}
				return false;
			}
		});
	}
}
/**
* 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 to grab one or more elements
* @usage $_C( element )
* @version 1.0
*/
function $_C ( element ){
	if ( typeof document.createElement != 'undefined' ) {
		return document.createElement(element);
	}
	else {
		alert('Your browser does not support document.createElement');
	}
}
/**
* 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;
}
/**
* 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;
}
/**
* @descripton reloads the form to post a message once we've moved off the form to view commetns
* @param method
* @param page
* @param editor
* @returns string
* @version 1.2
* @author Greg Shiers
*/
function loadCommentPosting ( method, page, editor, id ) {
	if ($('list')) {	
		$('list').className = 'off';
		$('list').onclick = function() { 
			doSimpleAxajCall('Getting comments, please wait...', 'GET', '/blog.comments.ajax.php?menu=comments&blogid='+id, null, id);
			return false;
		};
	}
	if ($('post')) {	
		$('post').className = '';
		$('post').onclick = function() {	
			return false
		};
	}
	if($('tabs')){
		/** 
		*** First we check if the comments list is present
		*** if it is there then we simply hide it and show the 
		*** content of the form which should be present already
		**/
		if ($('full_comment_list')) {
			$('full_comment_list').hide();
			$('full_blog_form').show();
			return false;
		}
		else {
			$("ajax_blog_form").update(showStatusBar("progress","Loading. Please wait..."));
			new Ajax.Request(page, {
				method: 'get',
				onComplete: function(transport) {
					$("ajax_blog_form").update(transport.responseText);
				},
				onFailure: function () {
					alert('Could not create Ajax Call to retrieve dialog contents');
						if ($("main_dialog") && $("cover")) {	
							body.removeChild($("main_dialog"));
							body.removeChild($("cover"));
							setTimeout(function(){
								var embed = document.getElementsByClassName("blog");
								for (var i = 0; i < embed.length; i++) {
									//embed[i].style.visibility = 'visible';
									embed[i].style.display = 'block';
								}
							},200)
						}
					return false;
				}
			});
		}
	}
}
/**
* @descripton does an ajax callback to a php page to send data to the database
* @param loading_message
* @param success_message
* @param refresh
* @param method
* @param trigger_page
* @param stuff
* @param id
* @version 1.2
* @author Greg Shiers
*/
function doAjaxCallBack ( loading_message, refresh, method, trigger_page, postbody, id ) {
	var body = document.getElementsByTagName("body")[0];
	$("dialog_content").update(showStatusBar("progress",loading_message));
	new Ajax.Request(trigger_page, {
		method: 'post',
		postBody : postbody,
		onComplete: function( transport) {
			if ( transport.responseText ) {	
				$("dialog_content").update(showStatusBar("success", transport.responseText));
			}
			if ( refresh ) {
				performAfterAjaxCallBack ( 'comment_links_'+id, 5000, "GET", 'blog.comments.ajax.php?menu=count_comments&submenu='+id );
				performAfterAjaxCallBack ( 'comments_links_'+id, 5000, "GET", 'blog.comments.ajax.php?menu=count_comments&submenu='+id );
				performAfterAjaxCallBack ( 'comment_'+id, 5000, "GET", 'blog.comments.ajax.php?menu=count_comments&submenu='+id );
			}
			else {
				setTimeout (function() { removeDialogWindow () } , 3000);
			}
		},
		onFailure: function () {
			alert('Could not create Ajax Call to retrieve dialog contents');
			removeDialogWindow ();
		}
	});
}
/**
* @descripton does an ajax callback to a php page to send data to the database
* @param loading_message
* @param success_message
* @param refresh
* @param method
* @param trigger_page
* @param stuff
* @param id
* @version 1.2
* @author Greg Shiers

*/
function doSimpleAxajCall ( loading_message, method, page, post_variables , id ) {
	// create out ajax object and set parametors
	deactivateTinyMce('blog_post_comment');
	if ($('list')) {	
		$('list').className = '';
		$('list').onclick = function() {	
			return false
		};
	}
	if ($('post')) {	
		$('post').className = 'off';
		$('post').onclick = function() { 
			loadCommentPosting('GET', '/blog.comments.ajax.php?id='+id, 'blog_post_comment',id);
			return false
		};
	}
	if ($('ajax_comments').innerHTML == '') {
		$('full_blog_form').hide();
		$("ajax_comments").update(showStatusBar("progress",loading_message));
		new Ajax.Request (page, {
			method: 'get',
			onComplete: function(transport) {
				if ( transport.responseText ) {	
					$("ajax_comments").update(transport.responseText);
				}
			},
			onFailure: function () {
				alert('Could not create Ajax Call to doSimpleAxajCall');
				removeDialogWindow ();
			}
		});
	}
	else {
		$('full_blog_form').hide();
		$('full_comment_list').show();
		return false;
	}
}
/**
* @descripton performs a task one's the ajax callback has been completed
* @param results
* @param method
* @param page
* @returns string
* @version 1.2
* @author Greg Shiers
*/
function performAfterAjaxCallBack ( target_id , time, method, page ) {
	setTimeout(function() {
		try {
			$(target_id).update("refreshing...");
			new Ajax.Request (page, {
				method: 'get',
				onComplete: function(transport) {
					$(target_id).update(transport.responseText);
					removeDialogWindow();
				},
				onFailure: function () {
					return false;
				}
			});
		}	
		catch (error) {
			return false;
		}
	},time );
}

/**
* @descripton creates the status bars that we use
* @param type
* @param message
* @returns string
* @version 1.2
* @author Greg Shiers
*/
function showStatusBar ( type , message ) {
	var output;
	switch ( type ) {
		case 'progress' :
			output = "<div id=\"progress\">"+message+"</div>";
		break;
		case 'success' :
			output = "<div class=\"success\">"+message+"</div>";
		break;
		case 'error':
			output = "<div class=\"error\">"+message+"</div>";
		break;
		default:
			output = "<div class=\"success\">"+message+"</div>";
	}
	return output;
}
/**
* @descripton removes the dialog window that's over the cover sheet
* @param dialog_window
* @param editor
* @version 1.2
* @author Greg Shiers
*/
function removeDialogWindow ( editor ) {
	var parent = document.getElementsByTagName('body')[0];
	// If there is an instance of the editor loaded, then remove it
	if ( typeof $( editor ) != "undefined" ) {
		deactivateTinyMce( editor )
	}
	// remove the dialog
	parent.removeChild($("main_dialog"));
	parent.removeChild($("cover"));
	setTimeout(function(){
		var embed = document.getElementsByClassName("blog");
		for (var i = 0; i < embed.length; i++) {
			//embed[i].style.visibility = 'visible';
			embed[i].style.display = 'block';
		}
	},200)

}
/**
* Function that validates that all mandaory fields are filled in
* @version 1.1
* @author Greg Shiers
*/
function validateCommentPost ( id ) {
	// Check for event and define if not there
	var msg = [], focus_el = null;
	// Check if the author is not empty
	if ( validation.empty ( $('blog_post_author') ) ) {
		msg += error[0];
		focus_el = focus_el || $('blog_post_author');
	}
	// Check if the author email is not empty
	if ( validation.empty ( $('blog_post_email') ) ) {
		msg += error[1];
		focus_el = focus_el || $('blog_post_email');
	}
	// If the author email is not empty, then check if it's a valid email address
	if ( !validation.empty ( $('blog_post_email') ) ) {
		if ( !validation.email ( $('blog_post_email') ) ) {
			msg += error[2];
			focus_el = focus_el || $('blog_post_email');
		}
	}
	// If the author url is not empty, then check if its a valid url
	if ( !validation.empty ( $('blog_post_url') ) ) {
		if ( validation.domain_string ( $('blog_post_url') ) ) {
			msg += error[3];
			focus_el = focus_el || $('blog_post_url');
		}
	}
	// Check if the author comment is not empty
	if ( tinyMCE.getContent() == "" || tinyMCE.getContent() == null ) {
		msg += error[4];
		focus_el = focus_el || $('blog_post_comment');
	}	
	// If there is an error
	if ( msg != '' ) {
		// Send the errors to the screen in the errors wrapper
		$('validate').innerHTML = "<p class=\"error\">" + msg + "</p>"
		// Focus on the first element with an error
		if ( focus_el.focus ) {
			focus_el.focus();
		}
		// Stop the default action
		return false;
	}
	else {
		$('validate').innerHTML = '';
		// If there are no errors then we post the information to the database using ajax
		setCookie('daryll_cullinan' , $F('blog_post_author')+'|'+$F('blog_post_email')+'|'+$F('blog_post_url')+'|'+$F('country') , 10000 );
		deactivateTinyMce( "blog_post_comment" );
		doAjaxCallBack('Posting your comment..', true, 'POST' , '/blog.comments.ajax.php?menu=save&submenu='+id,
		'blog_post_author='+escape($F('blog_post_author'))+'&blog_post_email='+escape($F('blog_post_email'))+'&blog_post_url='+escape($F('blog_post_url'))+'&country='+$F('country')+'&blog_post_comment='+escape($F('blog_post_comment'))+'&blog_post_subscribed='+escape($F('blog_post_subscribed')),id);
		return false;
	}
}
/** 
* Set the validation namespace "validation" and we can then define all other functions within this namespace.
*/
var 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.
	* @usage validation.empty(field)
	* @param (field) which field needs to be checked
	* @version 0.1
	* @returns String
	*/
	empty: function ( field ) {
		var re = /^\s*$/;
		return re.test( field.value );
	},
	/*
	* Function to checks than an email address entered is valid @ & .
	* @usage validation.email()
	* @param (field) which field needs to be checked
	* @version 0.3
	* @returns Boolean
	*/
	email: function ( field ) {
		var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/
		return re.test( field.value );
	},
	/*
	* Function to check for valid domain name
	* Allows only a to z no spaces nothing else
	* @usage validation.domain_string()
	* @param (field) which field needs to be checked
	* @version 0.3
	* @returns Boolean
	*/
	domain_string : function ( field ) { 
		var re = /^[A-z0-9-]+$/
		return re.test( field.value );
	}
}
/*
* Function prototyped to be able to trime white space from the beggining and end of a string
* @usage validation.friendly_date( string )
* @param (string) which field needs to be converted
* @version 0.1
* @returns String
*/
String.prototype.trim = function() {
	return this.replace(/^\s*|\s*$/g, '');
}
// ]]>
