/************************************************************************************
  A-Team Systems Source Code
  
  Copyright (c) 2001-2011, All Rights Reserved

  FULL SUPPORT IS AVAILABLE
  Email:  assistance@ateamsystems.com         USA Phone:   1.877.883.1394
    Web:  http://www.ateamsystems.com/       Intl Phone:  +1.603.244.3974
      
  You are hereby granted non-transferable rights to use this code in applications,
  software and scripts developed for you by A-Team Productions, LLC.
  
  Do not modify, resell, transfer or otherwise copy this code except for backup or
  migration purposes.
************************************************************************************/

/* Common tools for AJAX/JSON processing */

/* Global options & var */
var TZOffset = new Date().getTimezoneOffset() / 60 * (-1);
var UpdateDivColorOrig;
var CurFormDisableOnSubmit = 'Yes';
var CurMouseX;
var CurMouseY;

function UpdateDiv( DivName, URL, Message )
	{
	UpdateDivColorOrig = document.getElementById(DivName).style.color;
	document.getElementById(DivName).style.color="#AEAEAE";

	new Ajax.Updater(DivName, URL, { method: 'get', evalScripts: true });
	}

function PeriodicUpdateDiv( DivName, URL, Freq, Decay )
	{
	//alert('yo');
	new Ajax.PeriodicalUpdater(DivName, URL,
	  {
		 method: 'get',
		 //insertion: Insertion.Top,
		 frequency: Freq,
		 decay: Decay
	  });
	}

function FadeInDiv( DivName )
	{
	document.getElementById(DivName).style.color = UpdateDivColorOrig;
	}


var oldClassName = '';

function TableRollover ( object )
	{
	oldClassName = object.className;
	if ( oldClassName != 'TDD1' ) 
		{
		object.className='Rollover1TR';
		}
	else
		{
		object.className='Rollover2TR';
		//alert('Classname = [' + oldClassName + ']');
		}
	}
function TableRollout ( object )
	{
	//object.className='TDD1';
	object.className = oldClassName;
	}


/* Returns a nice text version of how old passed time is */
function getPageAge(birth)
	{
	var now = new Date();
	
	if ( ! birth )
		{
		return '<img src="/_tools/shared/cms/images/design/menubar/items/loading.gif" alt="loading" />';
		}
	
	aSecond = 1000;
	aMinute = aSecond * 60;
	aHour = aMinute * 60;
	aDay = aHour * 24;
	aWeek = aDay * 7;
	aMonth = aDay * 30;
	
	age = now - birth;

	// -- There are two modes to the display, one is if the page is a JSON data table (shows live status)
	//    The other is for 'regular pages' (less verbose)

	if ( PageType == 'JSON' )
		{
		if ( age < (aSecond * 10) )
			return "Live";
		}

	if ( age < (aSecond * 30) )
			return "Just Updated";
	
	if ( Math.round( (age / aMinute) ) == 1 )
		return "1 Min. Ago";

	if ( age < (aHour) )
		return Math.round( (age / aMinute) ) + " Min. Ago";

	if ( Math.round( (age / aHour) ) == 1 )
		return "1 Hour Ago";


	if ( age < (aHour*24) )
		return Math.round( (age / aHour) ) + " Hours Ago";
	else
		return "A Long Time Ago";
	}

// Heh
//
function ReturnFalse ()
	{
	return false;
	}


// Ajax.Request.abort
// extend the prototype.js Ajax.Request object so that it supports an abort method
//
Ajax.Request.prototype.abort = function() {
    // prevent and state change callbacks from being issued
    this.transport.onreadystatechange = Prototype.emptyFunction;
    // abort the XHR
    this.transport.abort();
    // update the request counter
    Ajax.activeRequestCount--;
};

// Loop through a form and re-enable it
//
function JSONFormEnable ( formID )
	{
	var elem = document.getElementById(formID).elements;
	for(var i = 0; i < elem.length; i++)
		{		
		// Enable it all
		document.forms[formID].elements[i].disabled = false;

		if (( elem[i].type == 'button' ) || ( elem[i].type == 'submit' ))
			{
			document.forms[formID].elements[i].setAttribute("class", "Button");
			//if ( elem[i].type == 'submit' )
			//	document.forms[formID].elements[i].value = 'Submit';
			}
		}
	}

// Loop through a form and clear its values
//
function JSONFormClear ( formID )
	{
	var elem = document.getElementById(formID).elements;
	for(var i = 0; i < elem.length; i++)
		{		
		if (( elem[i].type != 'button' ) && ( elem[i].type != 'submit' ) && ( elem[i].type != 'hidden' ) )
			{
			document.forms[formID].elements[i].value = '';
			}
		}
	}



// Loop through a form, disable it and return an array of its fields
//
function JSONFormCollect ( formID, FormDisableOnSubmit )
	{
	// Loop through form's objects and assemble list of variables and values
	var JSONFormFields = { };
	var elem = document.getElementById(formID).elements;
	for(var i = 0; i < elem.length; i++)
		{
		// If the element is a button, disable it
		//
		
		if ( FormDisableOnSubmit != 'No' )
			{
			// Disable it all
			document.forms[formID].elements[i].disabled = true;
	
			if (( elem[i].type == 'button' ) || ( elem[i].type == 'submit' ))
				{
				document.forms[formID].elements[i].setAttribute("class", "ButtonDisabled");
				//if ( elem[i].type == 'submit' )
				//	document.forms[formID].elements[i].value = 'Working ...';
				}
			}
		
		// Copy the form's values into an array for sending back to the server
		//
		if ( elem[i].name != '' )
			{
			if (( elem[i].type == 'select-multiple' ))
				{
				selected = new Array();
				for (var k = 0; k < elem[i].options.length; k++)
					{
					if (elem[i].options[k].selected)
						selected.push(elem[i].options[k].value);
					}

				JSONFormFields[elem[i].name] = selected;
				}
			else if ( elem[i].type == 'checkbox' )
				{
				if ( elem[i].checked == true )
					JSONFormFields[elem[i].name] = 'Yes';
				else
					JSONFormFields[elem[i].name] = 'No';
				}
			else
				JSONFormFields[elem[i].name] = elem[i].value;
			}
		}
	
	return JSONFormFields;
	}

// Get the domain portion from a URL
//
function getDomainFromURL ( url )
	{
	return url.match(/:\/\/(.[^/]+)/)[1];
	}

// Get mouse coordinatesrelative to a canvas or page if not specified
//
function getMouseXY(e)
	{
	if (IE) { // grab the x-y pos.s if browser is IE
	 CurMouseX = event.clientX + document.body.scrollLeft
	 CurMouseY = event.clientY + document.body.scrollTop
	} else {  // grab the x-y pos.s if browser is NS
	 CurMouseX = e.pageX
	 CurMouseY = e.pageY
	}  
	// catch possible negative values in NS4
	if (CurMouseX < 0){temCurMouseXpX = 0}
	if (CurMouseY < 0){CurMouseY = 0}  
	return true
	}

// Extend array classes to allow removing elements
//
Array.prototype.remove = function(from, to)
	{
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
	};

// Makes a string lowercase  
// 
function strtolower (str)
	{
	// version: 1103.1210
	// discuss at: http://phpjs.org/functions/strtolower    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Onno Marsman
	// *     example 1: strtolower('Kevin van Zonneveld');
	// *     returns 1: 'kevin van zonneveld'
	return (str + '').toLowerCase();
	}


/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};


function FormSubmitLock( formID )
	{
	var elem = document.getElementById(formID).elements;
	for(var i = 0; i < elem.length; i++)
		{
		// If the element is a button, disable it
		//		
		//document.forms[formID].elements[i].disabled = true;

		if (( elem[i].type == 'button' ) || ( elem[i].type == 'submit' ) )
			{
			document.forms[formID].elements[i].setAttribute("class", "ButtonDisabled");
			document.forms[formID].elements[i].disabled = true;
			//if ( elem[i].type == 'submit' )
			//	document.forms[formID].elements[i].value = 'Working ...';
			}
		}
	
	return true;
	}


function HoverButton ( buttonObj, type )
	{
	if ( buttonObj.enabled == false )
		return;

	if ( type == 'Primary' )
		{
		buttonObj.setAttribute("class", "PrimaryButtonHover");
		}
	}
function UnHoverButton ( buttonObj, type )
	{
	if ( buttonObj.enabled == false )
		return;
		
	if ( type == 'Primary' )
		{
		buttonObj.setAttribute("class", "PrimaryButton");
		}
	}

function ChangeInputFocus ( inputObj, action )
	{
	if ( inputObj.enabled == false )
		return;
	
	if (( inputObj.type == 'text' ) || ( inputObj.type == 'textarea' ) || ( inputObj.type == 'password' ))
		{
		if ( action == 'focus' )
			inputObj.addClassName('TextInputFocus');
		else
			inputObj.removeClassName('TextInputFocus');
		}
	
	if (( inputObj.type == 'select-one' ) || ( inputObj.type == 'select-multiple' ))
		{
		if ( action == 'focus' )
			inputObj.addClassName('SelectInputFocus');
		else
			inputObj.removeClassName('SelectInputFocus');
		}
	}


/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}
