﻿/*
- - ( 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;
	},
	setCookie : function(c_name,value,expiredays,path)
	{
		var exdate=new Date()
		exdate.setDate(exdate.getDate()+expiredays)
		document.cookie=c_name+ "=" +escape(value)+
		((expiredays==null) ? "" : ";expires="+exdate.toGMTString())+
		((path) ? "; path=" + path : "");
	},
	getCookie : function(c_name)
	{
		if (document.cookie.length>0)
		{
			c_start=document.cookie.indexOf(c_name + "=")
			if (c_start!=-1)
			{ 
				c_start=c_start + c_name.length+1 
				c_end=document.cookie.indexOf(";",c_start)
				if (c_end==-1) c_end=document.cookie.length
				return unescape(document.cookie.substring(c_start,c_end))
			} 
		}
		return ""
	},
	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);
}


function copy(text2copy) {
  if (window.clipboardData) {
	window.clipboardData.setData("Text",text2copy);
  } else {
	var flashcopier = 'flashcopier';
	if(!document.getElementById(flashcopier)) {
	  var divholder = document.createElement('div');
	  divholder.id = flashcopier;
	  document.body.appendChild(divholder);
	}
	document.getElementById(flashcopier).innerHTML = '';
	var divinfo = '<embed src="/assets/flash/_clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
	document.getElementById(flashcopier).innerHTML = divinfo;
  }
}


/* --------------------------------------------------
   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) {
		$('form').each(function(){
			$(this).submit(function(evt){
				var ok = true;
				$(this).find('.required').each(function(){
					var val = this.value;
					if($(this).hasClass("markItUpEditor"))
						var pdiv = $(this).parents('div').get(2);
					else
						var pdiv = $(this).parents('div').get(0);
					
					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!');
					evt.preventDefault();
				}
				else
				{
				    $(this).find('input[type="submit"]').each(function(){
						$(this).attr('value', 'Please wait...').addClass("disabled").click(function(){
							evt.preventDefault();
						});
					});
				};
			});
		});
	}
}

/* --------------------------------------------------
   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]).observe("focus", function(){
			        var pdiv = Element.getParentByTagName(['div'], this);
			        var pfs = Element.getParentByTagName(['fieldset'], this);
			        if(pdiv && ((!$(pdiv).hasClassName("buttons")) && (!$(pfs).hasClassName("simple"))))
			        {
			            $(pdiv).addClassName('focus');
			            $(pfs).addClassName('focus');
			        }
			    });
			    $(flds[k]).observe("blur", function(){
			        var pdiv = Element.getParentByTagName(['div'], this);
			        var pfs = Element.getParentByTagName(['fieldset'], this);
			        if(pdiv && ((!$(pdiv).hasClassName("buttons")) && (!$(pfs).hasClassName("simple"))))
			        {
			            $(pdiv).removeClassName('focus');
			            $(pfs).removeClassName('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) {
		$(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).parents('div').get(0);
				$(parentDiv).addClass('field-error');
				if(cmtAr[i] != "")
					$(parentDiv).append('<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() {
		setTimeout(function(){
			$('#system_message').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").html(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();
	$("a.thumbtip").cluetip({width: 152, topOffset: -15, leftOffset: 0, showTitle: false, positionBy: 'auto', arrows: true, dropShadow: false});
}
//Event.observe(window, 'load', g_LoadEvents);
$(document).ready(g_LoadEvents);
