var BACKEND = document.location.href.match('^https?://[^/?]+/edit/')?true:false;

var im_popped = 0;

// Simple popup box for images. Only one at a time.
function image_popup(name, url, width, height) {
	//if (im_popped) image_popup_window.close();
	//im_popped = 1;
	image_popup_window = window.open('./display_image.php?display_image='+url+'&title='+name, 1, 'toolbar=no,width='+width+',height='+height+',nominimize,nomaximize,norestore,scrollbars=no');
	image_popup_window.focus();
}

var current_colour_field = null;
var colour_picker = 0;
function load_colour_picker(field) {
	current_colour_field = field;
	if (colour_picker != 0 && !colour_picker.closed) colour_picker.close();
	colour_picker = window.open('colour_picker.php?colour=' + field.value, 1, 'toolbar=no,width=330,height=40,titlebar=false,scrollbars=no');
}

function update_colour(colour) {
	current_colour_field.value = colour;
}

var nonhexdigits  = new RegExp('[^0-9a-fA-F]');
var nonhexletters = new RegExp('[g-zG-Z]');

function check_colour(value) {
	//if (value.match(nonhexdigits)) return '000000';
	var c;
	for (i=0;i<value.length;i++) {
		c = value.substring(i,i+1);
		if (c.match(nonhexdigits)) {
			if (c.match(nonhexletters)) {
				value = value.substring(0,i) + 'f' + value.substring(i+1,value.length);
			} else {
				value = value.substring(0,i-1) + '0' + value.substring(i+1,value.length);
			}
		}
	}
	var extra = 6 - value.length;
	for (i=0;i<extra;i++) value += '0';
	return value.toLowerCase();
}


<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- V1.1.3: Sandeep V. Tamhankar (stamhankar@hotmail.com) -->
<!-- Original:  Sandeep V. Tamhankar (stamhankar@hotmail.com) -->
<!-- Changes:
/* 1.1.4: Fixed a bug where upper ASCII characters (i.e. accented letters
international characters) were allowed.

1.1.3: Added the restriction to only accept addresses ending in two
letters (interpreted to be a country code) or one of the known
TLDs (com, net, org, edu, int, mil, gov, arpa), including the
new ones (biz, aero, name, coop, info, pro, museum).  One can
easily update the list (if ICANN adds even more TLDs in the
future) by updating the knownDomsPat variable near the
top of the function.  Also, I added a variable at the top
of the function that determines whether or not TLDs should be
checked at all.  This is good if you are using this function
internally (i.e. intranet site) where hostnames don't have to 
conform to W3C standards and thus internal organization e-mail
addresses don't have to either.
Changed some of the logic so that the function will work properly
with Netscape 6.

1.1.2: Fixed a bug where trailing . in e-mail address was passing
(the bug is actually in the weak regexp engine of the browser; I
simplified the regexps to make it work).

1.1.1: Removed restriction that countries must be preceded by a domain,
so abc@host.uk is now legal.  However, there's still the 
restriction that an address must end in a two or three letter
word.

1.1: Rewrote most of the function to conform more closely to RFC 822.

1.0: Original  */
// -->

<!-- Begin
function isEmailValid (emailStr) {

	/* The following variable tells the rest of the function whether or not
	to verify that the address ends in a two-letter country or well-known
	TLD.  1 means check it, 0 means don't. */

	var checkTLD=1;

	/* The following is the list of known TLDs that an e-mail address must end with. */

	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */

	var emailPat=/^(.+)@(.+)$/;

	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address. 
	These characters include ( ) < > @ , ; : \ " . [ ] */

	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

	/* The following string represents the range of characters allowed in a 
	username or domainname.  It really states which chars aren't allowed.*/

	var validChars="\[^\\s" + specialChars + "\]";

	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */

	var quotedUser="(\"[^\"]*\")";

	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */

	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

	/* The following string represents an atom (basically a series of non-special characters.) */

	var atom=validChars + '+';

	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */

	var word="(" + atom + "|" + quotedUser + ")";

	// The following pattern describes the structure of the user

	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */

	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

	/* Finally, let's start trying to figure out if the supplied address is valid. */

	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */

	var matchArray=emailStr.match(emailPat);

	if (matchArray==null) {

		/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */

		alert("Email address seems incorrect (check @ and .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

	// Start by checking that only basic ASCII characters are in the strings (0-127).

	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("Ths username contains invalid characters.");
			return false;
		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("Ths domain name contains invalid characters.");
			return false;
		}
	}

	// See if "user" is valid 

	if (user.match(userPat)==null) {

		// user is not valid

		alert("The username doesn't seem to be valid. Please also ensure there are no spaces before the email.");
		return false;
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {

		// this is an IP address

		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Destination IP address is invalid!");
				return false;
			}
		}
		return true;
	}

	// Domain is symbolic name.  Check if it's valid.
	 
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			alert("The domain name does not seem to be valid. Please also ensure there are no spaces after the email.");
			return false;
		}
	}

	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding 
	the domain or country. */

	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
	}

	// Make sure there's a host name preceding the domain.

	if (len<2) {
		alert("This address is missing a hostname!");
		return false;
	}

	// If we've gotten this far, everything's valid!
	return true;
}

//  End -->


// POP UP HELP OR TOOLS WINDOW 
<!--
var i=1 
function buchel(arg, w, h)
{
myWindow=window.open("" + arg, i, "toolbar=no,scrollbars=yes,width="+(w+5)+",height="+(h+5)+",status=yes,resizable=yes");
i++;
}
// -->

function openwindowlink(link, width, height) {
	newwin = window.open(link,"windowname","height="+height+",width="+width+",scrollbars=yes,resizable=yes");
	newwin.focus();
}

//var popup_count = 0;
function Popup_Window (name, width, height, replace_win, xpos, ypos, scrollbars, resizable, status, toolbar, menubar) {
	if(!replace_win) {
		//popup_count++;
		//var popup_name = 'win'+popup_count;
		var popup_name = '';
	} else {
		var popup_name = 'win';
	}
	if(!width) width=400;
	if(!height) height=250;
	if(height > (screen.height - 20)) height = (screen.height - 20);
	if(!xpos) xpos = (screen.width - width) / 2;
	if(!ypos) ypos = (screen.height - 20 - height) / 2;
	if(!scrollbars) scrollbars = 'yes';
	if(!resizable) resizable = 'yes';
	if(!status) status = 'yes';
	if(!toolbar) toolbar = 'no';
	if(!menubar) menubar = 'no';
	popup_window = window.open(name, popup_name, 'width='+width+',height='+height+',screenx='+xpos+',screeny='+ypos+',left='+xpos+',top='+ypos+',scrollbars='+scrollbars+',resizable='+resizable+',status='+status+',toolbar='+toolbar+',menubar='+menubar);
	if (popup_window.opener == null) popup_window.opener = self;
	popup_window.focus();
}

function moveOptions(from,to,deleteSelection,defaultText,defaultValue) {

  // Move them over

  if(to){
	  for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected && o.value.match('^[0-9]+$')) {
		  to.options[to.options.length] = new Option( ((defaultText=='')?o.text:defaultText), ((defaultValue=='')?o.value:defaultValue), false, false);
		}
	  }
  }
  
  if(deleteSelection){
	  // Delete them from original
	  for (var i=(from.options.length-1); i>=0; i--) {
		var o = from.options[i];
		if (o.selected) {
		  from.options[i] = null;
		}
	  }
	  from.selectedIndex = -1;
	  to.selectedIndex = -1;
  }
}

function selectAllOptions(select_box) {
	if(select_box) {
		for(var i=0; i<select_box.options.length; i++) {
			select_box.options[i].selected = true;
		}
	}
}

// Given a select box reference, returns the current value
function getSelectValue(selectBox) {
	return eval ('document.' + selectBox + '.options[document.' + selectBox + '.selectedIndex].value');
}

function check_field_date(form, date_name) {

	date_string = '';

	if(isNumeric(document.forms[form].elements[date_name+'_year'].value)) {
		year = eval(document.forms[form].elements[date_name+'_year'].value);
	} else {
		year = '0';
	}

	if(isNumeric(document.forms[form].elements[date_name+'_month'].value)) {
		month = eval(date_string + document.forms[form].elements[date_name+'_month'].value);
	} else {
		month = '0';
	}

	if(isNumeric(document.forms[form].elements[date_name+'_day'].value)) {
		day = eval(date_string + document.forms[form].elements[date_name+'_day'].value);
	} else {
		day = '0';
	}

	date_string = year + '-' + month + '-' + day;

	document.forms[form].elements[date_name].value = date_string;

	return true;
}

function check_date(form, date_name) {
	day     = getSelectValue(form + '.day_' + date_name);
	month   = getSelectValue(form + '.month_' + date_name);
	year    = getSelectValue(form + '.year_' + date_name);
	if (month == 2) {
		if (day == 29) {
			// if not leap year
			if (((year % 4) != 0) || ( ((year % 100) == 0) && ((year % 400) != 0))) {
				alert (year + " is not a leap year, there is no " + day + "th of Feburary (for "+date_name+").");
				eval('document.' + form + '.day_' + date_name + '.focus()');
				return 0;
			}
		}
		else if (day > 29) {
			alert ("There is no " + day + "th of Feburary (for "+date_name+").");
			eval('document.' + form + '.day_' + date_name + '.focus()');
			return 0;
		}
	}
	if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) {
		alert ("There is no " + day + "st of " + getSelectText(form + '.month_' + date_name) + " (for" +date_name+").");
		eval('document.' + form + '.day_' + date_name + '.focus()');
		return 0;
	}
	if(day<=0 || month<=0 || year<=0) {

		if(!(day==0 && month==0 && year==0)) {
			alert("This is not a valid date. Please select all dashes(-) if you wish to set a blank date.");
			if(day!=0) {
				eval('document.' + form + '.day_' + date_name + '.focus()');
			}
			else if(month!=0) {
				eval('document.' + form + '.month_' + date_name + '.focus()');
			}
			else {
				eval('document.' + form + '.year_' + date_name + '.focus()');
			}
			return 0;
		}
	}
	date_string = year + '-' + month + '-' + day;
	eval('document.' + form + '.' + date_name + '.value = date_string');
	return 1;
}

/* This script is Copyright (c) Paul McFedries and 
Logophilia Limited (http://www.mcfedries.com/).
Permission is granted to use this script as long as 
this Copyright notice remains in place.*/

function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros(result3, decimals)
}

function pad_with_zeros(rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of dec imal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

function isNumeric(sText)
{
	var regExp = /^-?[0-9]+(\.[0-9]+)?$/;
	return regExp.test(sText);
}

// TRIMMING functions

// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	return LTrim(RTrim(value));
	
}

function commaDisplay(obj) {

	if(obj.value.indexOf(',') != -1) {

		full_names = obj.innerHTML.split(',');
		newHTML = new String();
		for(i=0;i < full_names.length; i++) {
			if(full_names[i] != '') {
				if(i>0) {
					newHTML += ',\n';
				}
				newHTML += trim(full_names[i].replace('\n','')) 
			}
		}
		
		obj.value = newHTML;
	}

}

function popup_form(myform)
{
	//A better way to popup a form is to put the target in the <form> tag
	//target="new_window"
	//And then in a button put the following in its onclick.
	//if(verify_form(prefix)){ window.open('','new_window','resizable=1,scrollbars=1,width=717,height=400'); document.form1.submit(); }

	if (! window.focus){
		return true;
	}
	var d = new Date();

	windowname = d.getTime();
	window.open('', windowname, 'top=100,left=100,height=600,width=800,location=no,resizable=yes,scrollbars=yes,status=no,toolbar=yes');
	myform.target=windowname;
	return true;
}

//openWindowWithPost
function openWindowPost(url,params) {
	var re = new RegExp(/(^https?:\/\/[^\/]+)/);
	var domain = url.match(re);
	var newWindow = window.open(domain[1]+'/simple.html'); 
	if (!newWindow) return false;
	var html = "";
	html += '<html><body><form id="formid" method="post" action="' + url + '">';
	if (params) {
		for (var key in params) {
			html += '<input type="hidden" name="' + key + '" value="' + params[key] + '"/>';
		}
	}
	html += '</form><script type="text/javascript">document.getElementById("formid").submit()</script></body></html>';
	newWindow.document.write(html);
	return newWindow;
}


function get_radio_value(form,name)
{
	for (var i=0; i < form.elements[name].length; i++) {
	   if (form.elements[name][i].checked) {
			return form.elements[name][i].value;
	   }
	}
	return "";
}

//http://www.stellapower.net/content/javascript-support-and-arrayindexof-ie
if(!Array.indexOf){
	Array.prototype.indexOf = function(obj, start) {
		for(var i = (start || 0),j=this.length; i < j; i++) {
			if(this[i] == obj) return i;
		}
		return -1;
	}
}

//http://objectmix.com/javascript/351435-json-object-empty.html
function isEmpty(object) {
	for(var i in object) { return true; }
	return false;
}

$(function () {
	$('body').mousemove(function(e){
		window.mouseXPos = e.pageX;
		window.mouseYPos = e.pageY;
	}); 
	if($.browser.msie && $.browser.version <= 7) {
		$('.center').center({vertical:false});
		$('.vcenter').center({horizontal:false});
	}

	$("input[type=button], input[type=submit]").hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	);

	if($.fn.tooltip) {
		var sel;
		$("a.help").each(function () {
			sel = $(this).nextAll('div.tooltip');
			if(!sel.length) sel = $(this).closest('tr').find('div.tooltip');
			if(!sel.length) sel = $(this).closest('div').find('div.tooltip');
			if(sel.length) {
				$(this).tooltip({ 
					relative:true,
					position: "bottom right", 
					offset: [10, 10], 
					effect: "fade", 
					opacity: 1.0,
					tip: sel.get(0)
				});	
			}
		}).dynamic();

		if(!BACKEND) {
			$(":input").nextAll(".tooltip").prevAll(':input').tooltip({
				relative:true,
				position: "center right", 
				offset: [-2, 10], 
				effect: "fade", 
				opacity: 0.8,
				tip: '.tooltip',
				lazy: false
			}).dynamic();
		}

		$(':input[title]').tooltip({ 
			relative:true,
			position: "center right", 
			offset: [-2, 10], 
			effect: "fade", 
			opacity: 0.8,
			tip: '#tooltip' 
		}).dynamic();
	}
});