/*
$Id: js_functions.inc.js 2500 2007-06-21 23:26:49Z fesh $
*/
function popup_image(image_url, title) {
	var winl = (screen.width - 200)/2;
	var wint = (screen.height - 300)/2;
	var settings ='top='+wint+',';
	settings +='left='+winl+',';
	settings +='width=200, ';
	settings +='height=300, ';
	settings +='scrollbars=no,';
	settings +='resizable=yes';

	title = title.replace(/\s/g, '%20');

	win=window.open('/image_popup.php?image_url='+image_url+'&title='+title, 'image',settings);

	if(parseInt(navigator.appVersion) >= 4) {
		win.window.focus();
	}
}

function popup_gallery_image(g, i, w, h) {
	var winl = (screen.width - 800)/2;
	var wint = (screen.height - 800)/2;
	var settings ='top='+wint+',';
			settings +='left='+winl+',';
			settings +='width=800, ';
			settings +='height=800, ';
			settings +='scrollbars=no,';
			settings +='resizable=yes';

	win=window.open('/popup.php?comp_gallery_id='+g+'&comp_gallery_image_id='+i+'&w='+w+'&h='+h, 'image',settings);

	if(parseInt(navigator.appVersion) >= 4) {
	   win.window.focus();
	}
}

function popup_gallery(g, i, w, h) {
	var winl = (screen.width - 700)/2;
	var wint = (screen.height - 500)/2;
	var settings ='top='+wint+',';
		settings +='left='+winl+',';
		settings +='width=700, ';
		settings +='height=500, ';
		settings +='scrollbars=no,';
		settings +='resizable=yes';

	win=window.open('/gallery_popup.php?g='+g+'&i='+i+'&w='+w+'&h='+h, 'image',settings);

	if(parseInt(navigator.appVersion) >= 4) {
	   win.window.focus();
	}
}

var href = location.href;
function refreshPage(page) {
	if (typeof page == "undefined") page = href;
	window.location.replace(page);
}
var win=null;
function PopupPage(w, h, page, resize, name) {
	if (typeof resize == "undefined") resize = 0;
	if (typeof name == "undefined") name = 'editor_popup';

	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	var settings  ='height='+h+',';
		settings +='width='+w+',';
		settings +='top='+wint+',';
		settings +='left='+winl+',';
		settings +='resizable='+resize+',';
		settings +='scrollbars=0';

	win = window.open(page, name, settings);
	win.window.focus();

	return false;
}

/* preload images */
if (document.images) {
	var spacerOn = new Image();
	spacerOn.src = "/images/spacer.gif";
}


// Shorter way of typing document.getElementById() - also good for returning many elements
var $ = function() {
	var elements = new Array();
	for (var i=0; i < arguments.length; i++) {
		var element = arguments[i];

		if (typeof(element) === 'string') {
			element = document.getElementById(element);
		}

		if (arguments.length == 1) {
			return element;
		}

		elements.push(element);
	}

	return elements;
};


// Return all elements by specifying a class name
var getElementsByClass = function(searchClass, node, tag) {
	var classElements = new Array();

	if (node == null) {
		node = document;
	}

	if (tag == null) {
		tag = '*';
	}

	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');

	for (var i=0, j=0; i < elsLen; i++) {
		if (pattern.test(els[i].className)) {
			classElements[j] = els[i];
			j++;
		}
	}

	return classElements;
};


var toggle = function(elm) {
	var elm_id = $(elm);

	if (elm_id.style.display == 'block') {
		elm_id.style.display = 'none';
	}
	else {
		elm_id.style.display = 'block';
	}
}


var validDate = function(dateStr) {
	var regex = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}\ \d{1,2}\:\d{1,2}$/

	if (regex.test(dateStr) == false) {
		return false;
	}
	else {
		return true;
	}
};


var reformatDecimal = function(fld) {
	var num = fld.value;
	var fldObj = $(fld.id);

	if ((parseFloat(num)).toFixed(2) == 'NaN') {
		fld.value = '';

		var a = document.createElement('span');
		a.style.color = '#FF0000';
		a.style.fontWeight = 'bold';
		a.innerHTML = 'invalid';
		fldObj.parentNode.appendChild(a);
	}
	else {
		fld.value = (parseFloat(num)).toFixed(2);

		if (fldObj.parentNode.lastChild.tagName == 'SPAN') {
			fldObj.parentNode.removeChild(fldObj.parentNode.lastChild);
		}
	}
};


var reformatPhone = function(fld) {
	var val = stripCharsNotInBag(fld.value, digits);

	if (val.length == 7) {
		// xxx xxxx
		fld.value = reformat(val, "+64 6 ", 3, " ", 4);
		return true;
	}
	if (val.length == 9) {
		if ((val.substr(0, 3) == '021') || (val.substr(0, 3) == '025') || (val.substr(0, 3) == '027') || (val.substr(0, 3) == '029')) {
			// 0xx xxx xxx
			val = val.substr(1, (val.length - 1));
			fld.value = reformat(val, "+64 ", 2, " ", 3, " ", 3);

			return true;
		}
		else if (val.substr(0, 1) == '0') {
			// 0x xxx xxxx
			val = val.substr(1, (val.length - 1));
			fld.value = reformat(val, "+64 ", 1, " ", 3, " ", 4);

			return true;
		}
		else {
			// xx xxx xxxx
			elmnt.value = reformat (val, "", 2," ", 3, " ", 4);
			return true;
		}
	}
	if (val.length == 10) {
		if ((val.substr(0, 4) == '0800') || (val.substr(0, 4) == '0508')) {
			// 0xxx xxxxxx
			fld.value = reformat(val, "", 4, " ", 6);

			return true;
		}
		else if ((val.substr(0, 3) == '021') || (val.substr(0, 3) == '025') || (val.substr(0, 3) == '027') || (val.substr(0, 3) == '029')) {
			// 0xx xxx xxxx
			val = val.substr(1, (val.length - 1));
			fld.value = reformat(val, "+64 ", 2, " ", 3, " ", 4);

			return true;
		}
		else {
			// xx x xxx xxxx
			fld.value = reformat(val, "+", 2," ", 1, " ", 3, " ", 4);
			return true;
		}
	}
	if (val.length == 11) {
		if ((val.substr(0, 4) == '0800') || (val.substr(0, 4) == '0508')) {
			// 0xxx xxxxxxx
			fld.value = reformat(val, "", 4, " ", 7);

			return true;
		}
		else if ((val.substr(0, 3) == '021') || (val.substr(0, 3) == '025') || (val.substr(0, 3) == '027') || (val.substr(0, 3) == '029')) {
			// 0xx xxxx xxxx
			val = val.substr(1, (val.length - 1));
			fld.value = reformat(val, "+64 ", 2, " ", 4, " ", 4);

			return true;
		}
	}
	if (val.length > 11) {
		if ((val.substr(0, 4) == '0800') || (val.substr(0, 4) == '0508')) {
			// 0xxx xxxxxxx...
			fld.value = reformat(val, "", 4, " ", (val.length - 4));

			return true;
		}
	}

	return false;
};


var focusText = function(obj) {
	if (obj.value == obj.defaultValue) {
		obj.value = '';
	}
	else if (obj.value == '') {
		obj.value = obj.defaultValue;
	}
};


// Add an event
var addEvent = function(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);

		return r;
	}
	else {
		elm['on' + evType] = fn;
	}

	return true;
};


// Append a script/stylesheet to the <head> of a document
var appendToHead = function(type, url) {
	var a;

	switch(type) {
		case 'javascript':
		case 'script':
			a = document.createElement('script');
			a.setAttribute('type', 'text/javascript');
			a.setAttribute('src', url);
			a.setAttribute('defer', true);
			break;

		case 'css':
		case 'style':
			a = document.createElement('link');
			a.setAttribute('href', url);
			a.setAttribute('rel', 'Stylesheet');
			a.setAttribute('type', 'text/css');
			break;
	}

	try {
		document.getElementsByTagName('head')[0].appendChild(a);

		a = null;	// Prevent memory issues
	}
	catch(e) {
		setTimeout(function() {
			appendToHead(type, url);
		}, 100);
	}
};


function checkFiletype(obj) {
	var elms = arguments;
	var frmOk = false;

	var start = elms[0].value.lastIndexOf('.');

	if (start !== -1) {
		var ext = elms[0].value.substring(start, elms[0].value.length);

		for (var i=1; i < elms.length; i++) {
			if ('.' + elms[i] == ext) {
				frmOk = true;
			}

			if (frmOk) {
				return true;
			}
		}

		if (!frmOk) {
			alert('This filetype is not allowed.\nPlease try again and select a JPEG Image.');

			return false;
		}
	}

	return true;
}


// Usage = 'var blah = new createRequestObject();' and then to connect 'blah.connect(arg1, arg2, arg3, arg4);'
var createRequestObject = function() {
	var xmlhttp;
	var completeRequest = false;

	if (window.XMLHttpRequest) {	// Non-IE Browser
		try {
			xmlhttp = new XMLHttpRequest();
		}
		catch(error) {
			alert(error.message);
		}
	}
	else if (window.ActiveXObject) {	// Internet Explorer
		try {
			xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch(error) {
			try {
				xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch(error) {
				alert(error.message);
			}
		}
	}

	if (!xmlhttp) {
		return null;
	}

	/**
	  *  Function to create AJAX connection and process
	  *
	  * Args:
	  * @ sURL - URL for AJAX to connection
	  * @ sMethod - The request method to be used for the connection - POST or GET
	  * @ sVars - Request options (i.e. a=1&b=2)
	  * @ fnDone - Function to execute on successful AJAX return
	  *
	  * example:
	  * var xmlRequest = new xmlHttpRequestObject();
	  *       xmlRequest.connect('a.php', 'post', 'name=test&age=22', test);
	  *
	  **/
	this.connect = function(sURL, sMethod, sVars, fnDone) {
		if (!xmlhttp) {
			return false;
		}

		completeRequest = false;
		sMethod = sMethod.toUpperCase();

		try {
			if (sMethod == 'GET') {
				xmlhttp.open(sMethod, sURL + '?' + sVars, true);
				sVars = '';
			}
			else {
				xmlhttp.open(sMethod, sURL, true);
				xmlhttp.setRequestHeader('Method', 'POST ' + sURL + ' HTTP/1.1');
				xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			}

			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState == 4 && !completeRequest) {
					bComplete = true;

					if (fnDone) {
						fnDone(xmlhttp);
					}
				}
			};

			xmlhttp.send(sVars);
		}
		catch(z) {
			return false;
		}

		return true;
	};

	return this;
};


// Style form elements for IE and setup default fields
var formOnload = function() {
	// add handlers for default fields
	var default_fields = getElementsByClass('default');

	for (var i=0; i < default_fields.length; i++) {
		if (default_fields[i].htmlFor && $(default_fields[i].htmlFor)) {
			var field = $(default_fields[i].htmlFor);

			if (field.defaultValue && field.defaultValue != '') {
				field.onfocus = function() { focusText(this); };
				field.onblur = function() { focusText(this); };
			}
		}
	}

	// add hover styles to form elements for IE 6
	if (navigator.userAgent.indexOf('MSIE') != -1) {
		var temp = navigator.appVersion.split('MSIE');
		var version = parseFloat(temp[1]);

		if (version < 7) {
			var elmInput = document.getElementsByTagName('input');

			for (var i=0; i < elmInput.length; i++) {
				if (elmInput[i].className.indexOf('field') != -1 && elmInput[i].className.indexOf('_field') == -1) {
					elmInput[i].onmouseover = function() { this.className = 'field_hover'; };
					elmInput[i].onmouseout = function() { this.className = 'field'; };
				}
				else if (elmInput[i].className.indexOf('contact_field') != -1) {
					elmInput[i].onmouseover = function() { this.className = 'contact_field_hover'; };
					elmInput[i].onmouseout = function() { this.className = 'contact_field'; };
				}
				else if (elmInput[i].className.indexOf('currency_field') != -1) {
					elmInput[i].onmouseover = function() { this.className = 'currency_field_hover'; };
					elmInput[i].onmouseout = function() { this.className = 'currency_field'; };
				}
				else if (elmInput[i].className.indexOf('tarea') != -1) {
					elmInput[i].onmouseover = function() { this.className = 'tarea_hover'; };
					elmInput[i].onmouseout = function() { this.className = 'tarea'; };
				}
				else if (elmInput[i].className.indexOf('comments') != -1) {
					elmInput[i].onmouseover = function() { this.className = 'comments_hover'; };
					elmInput[i].onmouseout = function() { this.className = 'comments'; };
				}
				else if (elmInput[i].className.indexOf('tarea') != -1) {
					elmInput[i].onmouseover = function() { this.className = 'tarea_hover'; };
					elmInput[i].onmouseout = function() { this.className = 'tarea'; };
				}
				else if (elmInput[i].className.indexOf('contact_btn') != -1) {
					elmInput[i].onmouseover = function() { this.className = 'contact_btn_hover'; };
					elmInput[i].onmouseout = function() { this.className = 'contact_btn'; };
				}
				else if (elmInput[i].className.indexOf('inline_field') != -1) {
					elmInput[i].onmouseover = function() { this.className = 'inline_field_hover'; };
					elmInput[i].onmouseout = function() { this.className = 'inline_field'; };
				}
				else if (elmInput[i].className.indexOf('inline_select') != -1) {
					elmInput[i].onmouseover = function() { this.className = 'inline_select_hover'; };
					elmInput[i].onmouseout = function() { this.className = 'inline_select'; };
				}
				else if (elmInput[i].className.indexOf('date_field') != -1) {
					elmInput[i].onmouseover = function() { this.className = 'date_field_hover'; };
					elmInput[i].onmouseout = function() { this.className = 'date_field'; };
				}
			}
		}
	}
};


// return current value of form element
function getValue(obj) {
	if (obj.type == 'select-one') {
		return obj.options[obj.selectedIndex].value;
	}
	else {
		return obj.value;
	}
}


// kill off any default fields in form
var removeDefaultFields = function() {
	var default_fields = getElementsByClass('default');

	for (var i=0; i < default_fields.length; i++) {
		if (default_fields[i].htmlFor && $(default_fields[i].htmlFor)) {
			var field = $(default_fields[i].htmlFor);

			if (field.defaultValue && field.defaultValue != '' && field.defaultValue == field.value) {
				field.value = '';
			}
		}
	}
}


// readd any default fields in form
var addDefaultFields = function() {
	var default_fields = getElementsByClass('default');

	for (var i=0; i < default_fields.length; i++) {
		if (default_fields[i].htmlFor && $(default_fields[i].htmlFor)) {
			var field = $(default_fields[i].htmlFor);

			if (field.defaultValue && field.defaultValue != '' && field.value == '') {
				field.value = field.defaultValue;
			}
		}
	}
}


// Validate form
var validateGenericForm = function() {
	removeDefaultFields();

	var required_fields = getElementsByClass('required');

	for (var i=0; i < required_fields.length; i++) {
		if (required_fields[i].htmlFor && $(required_fields[i].htmlFor)) {
			var field = $(required_fields[i].htmlFor);

			if (required_fields[i].innerHTML.indexOf(': *') != -1) {
				label = required_fields[i].innerHTML.substring(0, required_fields[i].innerHTML.length - 3);
			}
			else if (required_fields[i].innerHTML.indexOf(': &nbsp;&nbsp;') != -1) {
				label = required_fields[i].innerHTML.substring(0, required_fields[i].innerHTML.length - 14);
			}
			else if (required_fields[i].innerHTML.indexOf(': ') != -1) {
				label = required_fields[i].innerHTML.substring(0, required_fields[i].innerHTML.length - 2);
			}
			else {
				label = required_fields[i].innerHTML;
			}

			if (getValue(field) == '') {
				addDefaultFields();

				alert('You must enter a value for ' + label);

				field.focus();

				return false;
			}
		}
	}

	return true;
};


// window onload to style forms for IE
window.onload = function() {
	formOnload();
};











function add_onload(element, new_function) {
	var old_onload = element.onload;

	if (typeof old_onload != 'function') {
		old_onload = function(){};
	}

	element.onload = function (){
		old_onload();
		new_function();
	}
}

function add_onunload(element, new_function) {
	var old_onunload = element.onunload;

	if (typeof old_onunload != 'function') {
		old_onunload = function(){};
	}

	element.onunload = function (){
		old_onunload();
		new_function();
	}
}

function add_onfocus(element, new_function) {
	var old_onfocus = element.onfocus;

	if (typeof old_onfocus != 'function') {
		old_onfocus = function(){};
	}

	element.onfocus = function (){
		old_onfocus();
		new_function();
	}
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}



function limitTextarea(elm,limit,display_id,limit_id) {
  $(limit_id).value = limit - (elm.value.length);
  if ($(limit_id).value > 1) {
  	$(display_id).innerHTML = limit - elm.value.length+' characters remaining.';
  }
  if ($(limit_id).value == 1) {
  	$(display_id).innerHTML = '1 character remaining.';
 	}
  if ($(limit_id).value == 0) {
  	$(display_id).innerHTML = '0 characters remaining.';
 	}
 	if ($(limit_id).value < 0) {
 		$(display_id).innerHTML = limit - elm.value.length+' characters remaining, excess characters will be truncated.';
 	}
}