/* 
-------------------------------------------------------------

Title :		mesvision.com Javascript common functions
Author : 	Josh Orum, Loud Dog Corp.
URL : 		http://www.louddog.com

Created : 	19 Dec 2006
Modified : 	
Version : 	0.01

Comments:	This should be included in every page.
-------------------------------------------------------------
*/

function empty(obj) {
	if (obj == null) return true;
	
	switch (typeof(obj)) {
		case "boolean" : return !obj;
		case "number" : return obj == 0;
		case "string" : return obj == '';
		case "object" : return obj.length == 0;
		case "undefined" : return true;
	}
	
	return false;
}

// The null is to push January to months[1]
var months = [null,"January","February","March","April","May","June","July","August","September","October","November","December"];

// String functions

String.prototype.firstCap = function() {
    return this.toLowerCase().replace(/\w+[\w'"-_]*/g, function(s) {
        return s.charAt(0).toUpperCase() + s.substr(1);
    });
}

String.prototype.trim = function() {
	return this.replace(/^\s+/, '').replace(/\s+$/, '');
}

String.prototype.reverse = function() {
	return this.split('').reverse().join('');
}

String.prototype.formatCurrency = function() {
	var sections = this.replace(/[^\d\.]/g, '').split('.');

	dollars = sections[0] == '' ? '0' : sections[0];
	dollars = '$' + dollars.reverse().replace(/(\d{3})/g, '$1,').reverse().replace(/^,/, '');
	if (this.indexOf('-') != -1) dollars = '-' + dollars;

	var cents = sections.length > 1 ? sections[1] : '0';
	cents = Math.round(parseInt(cents, 10)/Math.pow(10, (cents.length-2)));
	if (cents < 10) cents = '0' + cents;
	
	return (dollars + '.' + cents);
}

var monthNames = [null, 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

String.prototype.date = function() {
	if (this.match(/^\d{8}$/)) {
		var year = parseInt(this.substr(0, 4), 10);
		var month = parseInt(this.substr(4, 2), 10);
		var day = parseInt(this.substr(6, 4), 10);
	} else {
		var sections = this.split('/');

		var month = sections.length > 0 ? parseInt(sections[0], 10) : false;
		var day = sections.length > 1 ? parseInt(sections[1], 10) : false;
		var year = sections.length > 2 ? parseInt(sections[2], 10) : false;
	}
	
	if (month > 12 || month < 1) month = false;
	if (day > 31 || day < 1) month = false;
	if (year < 100) year = year + (year < 76 ? 2000 : 1900);
	if (year < 1000) year = false;
	
	if (month && !day && year) return monthNames[month] + ' ' + year;
	if (month && day && year) return monthNames[month] + ' ' + day + ', ' + year;

	return this;
}

// Utility functions

// Day of for each last day of each month
var monthLastDays = new Array(31, 59, 90, 120, 151, 181, 212, 243, 273, 302, 334, 365);

// Returns the month given the day of the year (1-366) and the current year (to check for leap years), Jan = 1
function dayOfYearToMonth(day, year) {
	for (var i = 0; i < monthLastDays.length; i++) {
		if (i == 1 && year % 4 == 0) day--; // Leap year
		if (day <= monthLastDays[i]) return i + 1;
	}
}

function today() {
	var now = new Date();
	return months[now.getMonth() + 1] + " " + now.getDate() + ", " + now.getFullYear();
}

function addressToString(address, city, state, zip) {
	var addressString = '';
	
	if (address && address != '') addressString += address + ", ";
	if (city && city != '') addressString += city + ", ";
	if (state && state != '') addressString += state + " ";
	if (zip && zip != '') addressString += zip;
	
	return addressString;
}

function viewMapUrl(address, city, state, zip) {
	var url = "http://maps.yahoo.com/maps_result?" +
		"addr=" + address + 
		"&amp;csz=" + city + "%2C" + state + "%20" + zip;
		
	return url.replace('#', '%23');
}

function getDirectionsUrl(fromAddress, fromCity, fromState, fromZip, toAddress, toCity, toState, toZip) {
	var url = "http://maps.yahoo.com/dd_result?" + 
		"newaddr=" + fromAddress + 
		"&csz=" + fromCity + "%20" + fromState + "%20" + fromZip +
		"&amp;taddr=" + toAddress + 
		"&amp;tcsz=" + toCity + "%20" + toState + "%20" + toZip;
		
	return url.replace('#', '%23');
}

function hsmArray(hsmBlock) {
	if (hsmBlock == '[end]') hsmBlock = '';
	var items = hsmBlock.split('[end]');
	items.pop();
	return items;
}

function hsmObject(hsmBlock) {
	if (hsmBlock == '=[end]') hsmBlock = '';
	var items = hsmArray(hsmBlock);
	var item;
	var length = items.length;
	var object = {};
	for (var i = 0; i < length; i++) {
		item = items[i].split('='); 
		object[item[0]] = item[1];
	}
	
	return object;
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

// Cookie functions

function setCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + days*24*60*60*1000);
		var expires = "; expires="+date.toGMTString();
	} else var expires = "";
	
	document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
	var cookies = document.cookie.split(';');
	for (var i = 0; i < cookies.length; i++) {
		var cookie = cookies[i];
		while (cookie.charAt(0) == ' ') cookie = cookie.substring(1);
		if (cookie.indexOf(name+'=') == 0)		
			return cookie.substring(name.length+1);
	}
	return null;
}

function deleteCookie(name) {
	setCookie(name, '', -1);
}

/* *********************************************************** 
 *	FUNCTION:	checkPre()
 *	PURPOSE:	
 * 	If the site is test, / is returned, otherwise https is retuned
 * ********************************************************* */

function checkPre() {
	return(pXHg==532)?"/":"https://www.mesvision.com/";
}

// Hover and rollover functions

function addHover(element) {
	element.onmouseover = function() { Element.addClassName(this, 'hover'); }
	element.onmouseout = function() { Element.removeClassName(this, 'hover'); }
}

function addHoverToChildren(targetID, childTag) {
	if  (navigator.appName == "Microsoft Internet Explorer") {
		if ($(targetID)) {
			for (i = 0; element = $(targetID).down(childTag, i); i++) {
				addHover(element);
			}
		}
	}
}

function addHoverToParent(targetClass, parentTag) {
	document.getElementsByClassName(targetClass).each(function(element) {
		addHover(element.up(parentTag));
	});
}

function addClassToParentOnFocus(targetClass, parentTag, className) {
	document.getElementsByClassName(targetClass).each(function(element) {
		element.onfocus = function() { Element.addClassName($(this).up(parentTag), className); }
		element.onblur = function() { Element.removeClassName($(this).up(parentTag), className); }
	});
}

function addClassToParentsOnFocusWithRelative(targetClass, relativeClass, parentTag, className) {
	document.getElementsByClassName(targetClass).each(function(element) {
		element.onfocus = function() {
			var i = 0;
			while (element = $(this).up(parentTag, i++)) {
				if (element.down('.'+relativeClass)) {
					Element.addClassName(element, className);
					break;
				}
			}
		}
		element.onblur = function() {
			var i = 0;
			while (element = $(this).up(parentTag, i++)) {
				if (element.down('.'+relativeClass)) {
					Element.removeClassName(element, className);
					break;
				}
			}
		}
	});
}

// Utility functions

function addHintArrows() {
	document.getElementsByClassName('formHint').each(function(hint) {
		new Insertion.Top(hint, "<div class='hintArrow'></div>");
	});
}

function openWin(url, width, height, name, location, scrollbars) {
  if (width    == null) width=685;
  if (height   == null) height=450;
  if (location == null) location="no";
  if (name     == null) {
    name="ldwin";
  } else {
    // Strip out spaces
    name = name.replace(/\s+/g, '');
  }
  
  menubar = "no";
  toolbar = "no";
  if (scrollbars == null) scrollbars = "yes";
  resizeable = "yes";
  
  var opts="menubar=" + menubar + ",toolbar=" + toolbar + ",scrollbars="
		   + scrollbars + ",resizable=" + resizeable + ",fullsize=no,width="
           + width + ",height=" + height + ",location=" + location;

  winref=window.open(url,name,opts);
  winref.focus();
}

function closeWin() {
	window.close();
}

function printPage() {
	window.print();
}

function redactSubnum(num) {
	num = "*****" + num.substring(5,9);
	document.write(num);
}

function quoteMonthSelectBoxOptions() {
	var startDate = new Date();
	startDate.setDate(startDate.getDate() + 5);
	var month = startDate.getMonth() + 1; // Jan == 0
	var year = startDate.getFullYear() - 2000;
	
	for (var i = 0; i < 18; i++) {
		if (month < 0) {
			month = 12;
			year--;
		}
		if (month > 12) {
			month = 1;
			year++;
		}
		
		var dateStr = (month < 10 ? '0' : '') + month + '-01-' + (year < 10 ? '0' : '') + year; 
		document.write('<option value="' + dateStr + '">' + dateStr + '</option>');
		
		month++;
	} 
}

/* *********************************************************** 
 *	FUNCTION:  enableFormLinks()
 *	PURPOSE: 
 *  Finds links in forms with a certain class, then assigns 
 *  them onclick actions accordingly.  Links are not followed.
 *  'submitButton' - Submits its parent form using its own
 *     href attribute.
 *  'cancelButton' - Resets its parent form.
 *  'printButton' - Prints the window
 * ********************************************************* */
function enableFormLinks() {
	enableAction('submitButton', function(link, form) {
		form.action = link.href;
		form.submit();
	});
	
	enableAction('cancelButton', function(link, form) {
		form.reset();
	});
	
	enableAction('printButton', function(link, form) {
		window.print();
	});
}

function enableAction(targetClass, func) {
	document.getElementsByClassName(targetClass).each(function(element) {
		for (var i = 0; i < document.forms.length; i++) {
			if (element.descendantOf(document.forms[i])) {
				element.onclick = function() {
					element.up().addClassName('disabled');
					func(element, document.forms[i]);
					return false;
				}
				break;
			}
		}
	});
}

/* *********************************************************** 
 *	FUNCTION:  toggleDetails(details, link [, showText, hideText])
 *	PURPOSE: 
 *	Show and hide a details section when a user clicks a link.
 *  You may optionally specify the two versions of text the link
 *  will show.
 * ********************************************************* */
function toggleDetails(details, link, showText, hideText) {
	$(details).toggle();
	if (showText && hideText) {
		link.innerHTML = $(details).visible() ? hideText : showText;
	} else link.innerHTML = $(details).visible() ? 'hide details' : 'show details';
	return false;
}


/* *********************************************************** 
 *	FUNCTION:  selectAll(targetClass, link, onText, offText)
 *	PURPOSE: Toggles all checkboxes in a group on and off.
 *	targetClass: The class applied to all checkboxes in the group.
 *  link: A 'this' reference to the link doing the toggling.
 *  onText: Text to show the user to select all.
 *  offText: Text to show the user to select none.
 * ********************************************************* */
var selectAllOn = new Object();
function selectAll(targetClass, link, onText, offText) {
	if (typeof selectAllOn[targetClass] == 'undefined')
		selectAllOn[targetClass] = true;
	else selectAllOn[targetClass] = !selectAllOn[targetClass];
	
	document.getElementsByClassName(targetClass).each(function(box) {
		box.checked = selectAllOn[targetClass];
	});
	
	link.innerHTML = selectAllOn[targetClass] ? offText : onText;
	
	return false;
}

// Form utility functions

var FormUtils = {
	debug: false,
	
	value: function(field) {
		switch (this.fieldType(field)) {
			case 'radio' :
				for (var ndx = 0; ndx < field.length; ndx++)
					if (field[ndx].checked) return field[ndx].value;
				return false;
			case 'checkbox': return field.checked;
			case 'select-one':
				if (field.selectedIndex == -1) return false;
				return field[field.selectedIndex].value;
			default: return field.value;			
		}
	},

	fieldType: function(element) {
		if (element[0] && element[0].type == 'radio') return 'radio';
		else if (element.type == 'checkbox') return 'checkbox';
		else if (element.type) return element.type;
		else return false;
	},
	
	set: function(element, value) {
		if (element == undefined) {
			if (this.debug) alert('ERROR[FormUtils.set]: Undefined element (value = '+value+')');
			return;
		}
		
		switch (this.fieldType(element)) {
			case 'radio': this.setRadio(element, value); break;
			case 'checkbox': element.checked = value == true; break;
			case 'select-one': this.setSelect(element, value); break;
			default: element.value = value;
		}
	},
	
	setRadio: function(element, value) {
		var length = element.length;
		for (var i = 0; i < length; i++) {
			if (element[i].value == value) {
				element[i].checked = true;
				break;
			}
		}
	},
	
	setSelect: function(element, value) {
		var length = element.options.length;
		for (var i = 0; i < length; i++) {
			if (element.options[i].value == value) {
				element.selectedIndex = i;
				break;
			}
		}
	},

	labelFor: function(element) {
		if (!$(element) || !element.id) return false;
		var result = false;
		$A(document.getElementsByTagName('label')).each(function(label) {
			if (Element.readAttribute(label, 'for') == element.id) result = label;
		});
		return result;
	},

	fixFormLabels: function() {
		// enable label clicks for IE and Safari
		if( document.all || navigator.userAgent.indexOf("Safari") > 0){ 
			var labels = document.getElementsByTagName("label");
			$A(labels).each ( function(label){
				Event.observe(label, "click", function(){
					var target = $(this.getAttribute('for'));
					if(target.type == 'checkbox' || target.type == 'radio')
						target.checked = target.checked == false ? true : false;
					else target.focus();
				});
			});
		}
	},
	
	formatPhone: function(field) {
		var phone = field.value.replace(/\D/g,'');
		var p1 = phone.slice(0,3);
		var p2 = phone.slice(3,6);
		var p3 = phone.slice(6,10);
		
		if (p1 != '') field.value = "(" + p1 + ") " + p2 + "-" + p3;
		
		return true;
	},
	
	numberSelectOptions: function(min, max) {
		for (var i = min; i <= max; i++) {
			document.write('<option value="' + i + '">' + i + '</option>');
		}
	}
}