/*
- - ( FILE INFO ) - - - - - - - - - - - - - - - - - - - - - - - - 
 Name:           general.js
 Title:          General scripts run on all pages
 Author:         Colin Mc Mahon [Protomatter Web Solutions]
                 www.protomatter.co.uk
 Version:        1.0
 Updated:        08/03/2007
- - - - - - - -  - - - - - - - - - - - - - - - - - - - - - - - - - 
*/
var Utilities = {
	goUrl : function(url)
	{
		if (url == 'back') {
			history.go(-1);
		} else {
			document.location = url;
		}
	},
	ConfirmSubmit : function()
	{
		var str = "Are you sure you wish to continue?";
		if (arguments[1] != null) str = arguments[1] + "\n" + str;
		var agree = window.confirm(str);
		if (agree) {
			if (arguments[0] != null) {
				this.goUrl(arguments[0]);
			} else {
				return true;
			}
		} else {
			return false;
		}
	},
	OpenImage : function(in_img)
	{
		Utilities.OpenWindow('/assets/images/images.asp?img=' + in_img, "ImgWindow", 200, 200, 0);
		return false;
	},
	OpenWindow : function(in_url, in_win_id, in_width, in_height, in_scroll_bars)
	{
		if (in_width =="" || in_width == null) in_width = 486;
		if (in_height == "" || in_height == null) in_height = 500;
		var features ='directories=0,location=0,menubar=0,scrollbars=' + in_scroll_bars + ',status=0,toolbar=0,resizable=1,width=' + in_width + ',height=' + in_height + ',screenX=15,screenY=15,top=15,left=15';
		in_url = in_url.replace(/\s/,'%20');
		var wind=window.open (in_url, in_win_id, features);
		wind.focus();
		return wind;
	},
	GetCoords : function (e)
	{
		var posx = 0;
		var posy = 0;
		if (!e) var e = window.event;
		if (e.pageX || e.pageY) 	{
			posx = e.pageX;
			posy = e.pageY;
		}
		else if (e.clientX || e.clientY) 	{
			posx = e.clientX + document.body.scrollLeft
				+ document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop
				+ document.documentElement.scrollTop;
		}
		return [posx, posy];
	},
	GetPath : function()
	{
		var loc = window.location;
		return {
			protocol: loc.protocol,
			server: loc.hostname,
			path: loc.pathname,
			query: loc.search,
			hash: loc.hash,
			fullurl: loc.protocol + "//" + loc.hostname + loc.pathname + loc.search + loc.hash
		};
	}
};

function getElementsByTagNameMultiple( tag_names, parent_node ) {
	if( parent_node == undefined ) {
		parent_node = document;
	}
	var out = new Array();
	for( var i = 0; i < tag_names.length; i++ ) {
		elementsFound =
		parent_node.getElementsByTagName(tag_names[i]);
		for (var j = 0; j < elementsFound.length; j++)
			out.push( elementsFound.item(j) );
		}
	return out;
}

function getAllFormElements( parent_node )
{
    return getElementsByTagNameMultiple(['input', 'textarea', 'select', 'button'], parent_node);
}


/* --------------------------------------------------
   Script checks for required class form elements and
   blocks form submission if blank
   Copyright (C) Colin Mc Mahon, Protomatter Web
   Solutions 2007
   -------------------------------------------------- */
var Checkform = {
	init : function(in_text) {
		var aForms = document.getElementsByTagName('form');
		for (var i=0; i<aForms.length; i++) {
			$(aForms[i]).addEvent('submit', function(evt){
				var aRequired = $(this).elmsByClass('required');
				var ok = true;
				for (var k=0; k<aRequired.length; k++) {
					var val = aRequired[k].value;
					var pdiv = $(aRequired[k]).getParentByTagName('div');					
					if(val == '' || val == in_text || val == '-1') {
						ok = false;
						$(pdiv).addClass('field-error');
					} else {
						$(pdiv).removeClass('field-error');
					}
				}
				if(ok==false)
				{
					alert('Please complete all required fields!');
					DOMAssistant.preventDefault(evt);
				}
				else
				{
				    var submits = $(this).elmsByAttribute("type", "submit", "input");
				    if(submits)
				    {
				        for (var x=0; x<submits.length; x++)
				        {
							var thisSubmit = $(submits[x]);
				            thisSubmit.setAttributes({value : "Please wait..."});
				            thisSubmit.addClass("disabled");
				            thisSubmit.addEvent("click", function(e){DOMAssistant.preventDefault(e);});
				        }
				    }
				    //DOMAssistant.preventDefault(evt);
				};
			});
		}
	}
}

/* --------------------------------------------------
   Script highlights form rows and fieldsets on
   focus of a form element
   Copyright (C) Colin Mc Mahon, Protomatter Web
   Solutions 2007
   -------------------------------------------------- */
var FocusFields = {
	init : function() {
		var aForms = document.getElementsByTagName('form');
		for (var i=0; i<aForms.length; i++)
		{
			var flds = getAllFormElements(aForms[i]);
			for (var k=0; k<flds.length; k++)
			{
				$(flds[k]).addEvent("focus", function(){
			        var pdiv = $(this).getParentByTagName('div');
			        var pfs = $(this).getParentByTagName('fieldset');
			        if(pdiv && ((!$(pdiv).hasClass("buttons")) && (!$(pfs).hasClass("simple"))))
			        {
			            $(pdiv).addClass('focus');
			            $(pfs).addClass('focus');
			        }
			    });
			    $(flds[k]).addEvent("blur", function(){
			        var pdiv = $(this).getParentByTagName('div');
			        var pfs = $(this).getParentByTagName('fieldset');
			        if(pdiv && ((!$(pdiv).hasClass("buttons")) && (!$(pfs).hasClass("simple"))))
			        {
			            $(pdiv).removeClass('focus');
			            $(pfs).removeClass('focus');
			        }
			    });
			}
		}
	}
}


/* --------------------------------------------------
   Script highlights form errors post form submission
   given a list of field ids
   Copyright (C) Colin Mc Mahon, Protomatter Web
   Solutions 2007
   -------------------------------------------------- */
var HighlightFields = {
	init : function (in_fields, in_cmts) {
		DOMAssistant.DOMReady(function(){
			var fldAr = in_fields;
			var cmtAr = in_cmts;
			var parentDiv;
			for (var i=0; i<fldAr.length; i++) {
				var tmpElem = fldAr[i];
				if (tmpElem.indexOf('file_')!=-1 || tmpElem.indexOf('img_')!=-1) {
					tmpElem = tmpElem.split("__");
					tmpElem = tmpElem[1];
				}
				parentDiv = $(tmpElem).getParentByTagName('div');
				$(parentDiv).addClass('field-error');
				$(parentDiv).addContent('<p class="field-error-detail">' + cmtAr[i] + '</p>');
			}
		});
	}
};

var HighlightRow = {
	init : function() {
		DOMAssistant.DOMReady(function(){
			var tbls = document.getElementsByTagName('table');
			if(tbls)
			{
				for (var i=0; i<tbls.length; i++)
				{
					var tbodys = tbls[i].getElementsByTagName('tbody');
					if(tbodys)
					{
						for (var j=0; j<tbodys.length; j++)
						{
							var rows = tbodys[j].getElementsByTagName('tr');
							for (var k=0; k<rows.length; k++)
							{
								$(rows[k]).addEvent("mouseover", function(){
									$(this).addClass("hover");
								});
								$(rows[k]).addEvent("mouseout", function(){
									$(this).removeClass("hover");
								});
							}
						}
					}
				}
			}
		});
	}
}


var ClearFeedback = {
	init : function() {
		var fback = $('system_message');
		if(fback) {
			setTimeout(function(){
				fback.remove();
			}, 5000);
		}
	}
}

/* --------------------------------------------------
   Script shows a countdown on the page
   Copyright (C) Colin Mc Mahon, Protomatter Web
   Solutions 2007
   -------------------------------------------------- */
var countdown = {
	init : function(in_minutes)
	{
		var now = new Date();
		var now = now.getTime();
		this.timeout = now + ((in_minutes * 60) * 1000)
		this.DisplayCountDown();
	},
	DisplayCountDown : function()
	{
		var me = this;
		var now = new Date();
		var now = now.getTime();
		var timeremaining = this.timeout - now;
		
		$("session-timer-text").replaceContent(this.FormatSeconds(timeremaining));
		
		setTimeout(function(){
			me.DisplayCountDown()
		}, 1000);
	},
	FormatSeconds : function(millisecs)
	{
		var countdn = Math.floor(millisecs/1000);
		if (countdn <= 1)
		{
			document.location.href = "/admin/login/logout.asp?action=loggedout";
		}
		else
		{
			if(countdn <= 60)
			{
				$("session-timer-text").addClass("warning");
			}
			if(countdn <= 30)
			{
				$("session-timer-text").addClass("expiring");
			}
			var secs = countdn % 60;
			if (secs < 10) secs = '0'+secs;
			var countdn1 = (countdn - secs) / 60;
			var mins = countdn1 % 60;
			if (mins < 10) mins = '0'+mins;countdn1 = (countdn1 - mins) / 60;
			var hours = (countdn1 % 24);
			var days = (countdn1 - hours) / 24;
			
			var outhtml = new String("%hours% hrs %mins% mins %secs% secs");
			outhtml = outhtml.replace(/%days%/,days);
			outhtml = outhtml.replace(/%hours%/,hours);
			outhtml = outhtml.replace(/%mins%/,mins);
			outhtml = outhtml.replace(/%secs%/,secs);
			return outhtml;
		}
	}
}

/* --------------------------------------------------
   General page initialisation
   -------------------------------------------------- */
g_LoadEvents = function() {
	Checkform.init();
	ClearFeedback.init();
	FocusFields.init();
	HighlightRow.init();
}

DOMAssistant.DOMReady(g_LoadEvents);