/**
 * @fileoverview This is the administrator admin utilities
 * for admin pages
 */

/**
 * @class csAdminUtils
 */
function csUtils() {
	
	this.empty = function(v) { return (v==null||v==''?true:false); }
	
	this.trim = function(v) {
		v = ""+v.toString();
		return(v.replace(/^\s+/,'').replace(/\s+$/,''));
	}
	/**
	 * Identifies if the parameter is an object
	 * @param {Object} obj The variant to test
	 * @return {Boolean} Returns true if an object, otherwise false.
	 */
	this.isObject = function(obj) { return (typeof(obj) == "object"?true:false); }
	/**
	 * Identifies if the parameter is a date object
	 * @param {Date} obj The variant to test
	 * @return {Boolean} Returns true if a date object, otherwise false.
	 */
	this.isDate = function(obj) {
		try {
			if ( typeof(obj) == "date" ) { return true; }
			if ( typeof(obj) != "object" ) { return false; }
			// do a test on a date method and catch the error if fails
			var m = obj.getMonth();
			return true;
		} catch(e) {}
		return false;
	}
	/**
	 * Identifies if the parameter is an array object
	 * @param {Array} obj The variant to test
	 * @return {Boolean} Returns true if a date object, otherwise false.
	 */
	this.isArray = function(obj) {
		try {
			if ( typeof(obj) != "object" ) { return false; }
			// do a test on an array method and catch the error if fails
			var m = obj.join(',');
			return true;
		} catch(e) {}
		return false;
	}
	/**
	 * Identifies if the param:obj is undefined
	 * @param {Variant} obj The variant to test
	 * @return {Boolean} Returns true if param:obj is undefined, otherwise false.
	 */
	this.isUndefined = function(obj) { return (typeof(obj) == "undefined"?true:false); }
	/**
	 * Identifies if the param:obj is a number
	 * @param {Variant} obj The variant to test
	 * @return {Boolean} Returns true if param:obj is a number, otherwise false.
	 */
	this.isNumber = function(obj) { return (typeof(obj) == "number"?true:false); }
	/**
	 * Identifies if the param:obj is a boolean
	 * @param {Variant} obj Variant The variant to test
	 * @return {Boolean} Returns true if param:obj is a boolean, otherwise false.
	 */
	this.isBoolean = function(obj) { return (typeof(obj) == "boolean"?true:false); }
	/**
	 * Identifies if the param:obj is a string
	 * @param {Variant} obj The variant to test
	 * @return {Boolean} Returns true if param:obj is a string, otherwise false.
	 */
	this.isString = function(obj) { return (typeof(obj) == "string"?true:false); }
	/**
	 * Returns true or false if the number is numeric or not. This looks deep
	 * into the value as a string, number, or object to determine
	 * @param {Variant} val The value to test
	 * @return {Boolean} Returns true if Numeric, otherwise false
	 */
	this.isNumeric = function(val) {
		if ( val == null ) { return false; }
	  try {
	    var sType = typeof(val);
	    switch ( sType.toLowerCase() ) {
	      case 'number'	: return true;
	      case 'string'	:
			    if ( isNaN(Number(val)) ) { return false; }
			    return true;
			  default	:
			  	return false;
	    }
	  } catch(err) {
	    return false;
	  }
	}
	/**
	 * Validates the email address.
	 * @param {String} v The email address to test
	 * @return {Boolean}
	 */
	this.validateEmail = function(_this) {
		var v = _this.value;
		if ( this.empty(v) ) { return true; }
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if( reg.test(v) === false ) {
			alert('Email address is not valid!');
			return false;
		}
		return true;
	}
	/**
	 * Validates phone number characters.
	 * @param {String} phone The phone number value to test against
	 * @param {Boolean} [allowExt] <i>optional</i> Identifies if the characters
	 * 'ext' or 'x-' should be allowed at the end of the phone number.
	 * This is set to FALSE by default.
	 * @return {Boolean} Returns true if the phone number meets the validation
	 * test, otherwise returns false.
	 */
	this.validatePhone = function(_this) {
		// get other parameters
		var phone = _this.value;
		if ( this.empty(phone) ) { return true; }
		var _args = this.validatePhone.arguments;
		// set defaults
		var _minLen = 7;
		var _isReqd = true;
		var _allowExt = (_args.length>1&&_args[1]===true?true:false);
	  // test if the phone number has valid allowed characters
	  var _rgx = /^\+?[\d\(\)\.\-\ ]+([ ]+[xX][\d]+)?$/;
  	if ( _rgx.test(phone) === false ) {
			alert('Phone number contains improper characters.');
			return false;
  	}
  	// check length of total numbers
		var numOnly = phone.replace(/[^\d]/g, ''); // strip out everything but numbers
 		if ( numOnly.length < _minLen ) {
			alert('Phone number is too short! Must be longer than '+_minLen+' characters.');
			return false;
	  }
		return true;
	}
	
	this.validateNumber = function(v) {
		var isNum = (this.empty(v)?true:this.isNumeric(v));
		if ( !isNum ) {
			alert('Must be a number!');
			return false;
		}
		return true;
	}
	
}	// end class csAdminUtils

/*
 * The APIs
 */
/**
 * Returns a field value
 * @param {String} field_id The id of the field
 * @param {Mixed} [default] Default value if the field does not exist. If
 * not set, null is returned.
 * @return {Mixed} Returns the value
 */
function csapiGetFieldValue(field_id) {
	var _args = csapiGetFieldValue.arguments;
	var dflt = (_args.length>1?_args[1]:null);
	if ( field_id == null || field_id == '' ) { return dflt; }
	try {
		var dom = document.getElementById(field_id);
		if ( dom ) { return  dom.value; }
	} catch(e) {}
	return dflt;
}
/**
 * Sets a field value
 * @param {String} field_id The id of the field
 * @param {Mixed} val Value to set
 * @return {Boolean} Returns true if field set properly, otherwise false
 */
function csapiSetFieldValue(field_id,val) {
	if ( field_id == null || field_id == '' ) { return false; }
	try {
		var dom = document.getElementById(field_id);
		if ( dom ) { dom.value = val; return true; }
	} catch(e) {}
	return false;
}
/**
 * Check if the field is a date
 * @param {Date} d The date object
 * @return {Boolean}
 */
function csapiIsDate(d) { return new csUtils().isDate(d); }
/**
 * Validates an email address
 * @param {String} email_addr The email address to test
 * @return {Boolean}
 */
function csapiValidateEmail(_this) {
	if ( !new csUtils().validateEmail(_this) ) { _this.focus(); }
}
/**
 * Validates a phone number
 * @param {String} phone The phone number to test
 * @return {Boolean}
 */
function csapiValidatePhone(_this) {
	if ( !new csUtils().validatePhone(_this) ) { _this.focus(); }
}
/**
 * Returns the sublist row number from the ID
 * @param {String} id The id to derive the row number from
 * @return {Integer} Returns the row number or false if can not be derived.
 */
function csapiSublistRowNumber(id) {
	try {
		var sp = id.split('_');
		var rn = sp.pop();
		return (isNaN(parseInt(rn))?false:parseInt(rn));
	} catch(e) {}
	return false;
}

function csapiFormSubmit() {
	var _args = csapiFormSubmit.arguments;
	if ( _args.length == 0 ) { return true; }
	var ok = false;
	for(var i=_args.length-1; i>=0; i--) {
		ok = false;
		try {
			eval("ok="+_args[i]+";");
		} catch(e) {
			alert('Error validating form:'+"\n"+e.message);
			return false;
		}
		if ( !ok ) { return false; }
	}
	return true;
}

function csapiFormValidateCaptcha() {
	var doc = document.getElementById('af_form_captcha');
	if ( !doc ) { return true; }
	if ( doc.value == null || doc.value == '' ) {
		alert('Please enter the value of the image text into the text box before submitting!');
		doc.focus();
		return false;
	}
	return true;
}

// global variable associated with csapiOpenPopup
var csapiOpenPopupWin = '';

function csapiClosePopup(doc,field_id,callback) {
alert('closing field id '+field_id);
	if ( !csapiOpenPopupWin.closed ) {
		alert('Cancel = '+doc.getElementById('cancel_id').value);
		csapiOpenPopupWin = '';
		if ( doc.getElementById('cancel_id').value == 'false' ) {
			alert('process callback');
		}
	}
}
/**
 * Opens a new window with the desired information (url
 * or html
 * @param {String} name The name of this window.
 * @param {String} [url] {optional} The URL to open (or null if passing in HTML)
 * @param {Integer} [width] {optional} The width of the screen. If null
 * then 600 is used
 * @param {Integer} [height] {optional} The height of the screen. If null
 * then 400 is used
 * @param {Boolean} [use_scroll] {optional} If true, will apply scroll bars, the
 * default is true
 * @param {Boolean} [use_menus] {optional} If true, will apply toolbars, menus and
 * address bar in window.
 * @param {Boolean} [modal] {optional} Identifies if modal (can't exit until close).
 * Default is false.
 * @param {Boolean} [resizeable] {optional} Identifies if the window can be resized.
 * Default is true.
 * @param {String} [html] {optional} Passes in HTML to display in new window. If url
 * is empty, this is required. If url is not empty, this is ignored.
 * @return {void}
 */
function csapiOpenPopup(name) {
	var url = null;
	var width = 600;
	var height = 400;
	var use_scroll = true;
	var use_menus = true;
	var modal = false;
	var resize = true;
	var html = null;
	switch(csapiOpenPopup.arguments.length) {
		case 9	: html = csapiOpenPopup.arguments[8];
		case 8	: resize = (csapiOpenPopup.arguments[7]===false?false:true);
		case 7	: modal = (csapiOpenPopup.arguments[6]===true?true:false);
		case 6	: use_menus = (csapiOpenPopup.arguments[5]===false?false:true);
		case 5	: use_scroll = (csapiOpenPopup.arguments[4]===false?false:true);
		case 4	: height = csapiOpenPopup.arguments[3];
		case 3	: width = csapiOpenPopup.arguments[2];
		case 2	: url = csapiOpenPopup.arguments[1];
	}
	if ( (html == null || html == '') && (url == null || url == '') ) { return; }
	var use_html = false;
	if ( html != '' && (url == null || url == '') ) {
		use_html = true;
		url = '';
	} else {
		url = csapiEncodeUrl(url);
	}
	// Remove special characters from name
	name = name.replace(/\/|\-|\./gi, "");
	// Remove whitespaces from name
	var whitespace = new RegExp("\\s","g");
	name = name.replace(whitespace,"");
	// Set attributes
	var attrs = new Array();
	attrs.push('location='+(use_menus?'yes':'no'));
	attrs.push('toolbar='+(use_menus?'yes':'no'));
	attrs.push('menubar='+(use_menus?'yes':'no'));
	attrs.push('scrollbars='+(use_scroll?'yes':'no'));
	attrs.push('resizeable='+(resize?'yes':'no'));
	attrs.push('width='+width);
	attrs.push('height='+height);
	// Check to be sure it is closed
	if ( !csapiOpenPopupWin.closed && csapiOpenPopupWin.location ) {
		// update the location with the new URL
		csapiOpenPopupWin.location.href = url;
	} else {
		// open the window
		csapiOpenPopupWin = '';
		csapiOpenPopupWin = window.open(url,name,attrs.join(','));
		if ( use_html ) { csapiOpenPopupWin.document.write(html); }
		if ( !csapiOpenPopupWin.opener ) {
			csapiOpenPopupWin.opener = self;
		}
	}
  // Stop focus from leaving popup (modal)
  if ( modal && window.focus ) { csapiOpenPopupWin.focus(); }

}
/**
 * Enodes a URL
 * @param {String} url The URL to encode
 * @return {String}
 */
function csapiEncodeUrl(url) {
	if ( url == null || url == '' ) { return url; }
	if ( url.indexOf("?") > 0 ) {
		var encodedParams = new Array();
		var parts = url.split("?");
		var params = parts[1].split("&");
		for(var i=0; i<params.length; i++) {
			if ( params[i].indexOf("=") > 0 ) {
				p = params[i].split("=");
				encodedParams.push(p[0]+"="+escape(encodeURI(p[1])));
			} else {
				encodedParams.push(params[i]);
			}
		}
		url = parts[0]+(encodedParams.length>0?'?'+encodedParams.join('&'):'');
	}
	return url;
}
/**
 * Standard compact routine that removes spaces and other
 * punctuations.
 * @param {String} value The value to compact
 * @param {Array} [allow] Array of characters to allow. If not
 * specified, only A-Z, a-z, 0-9 and underscore are allowed.
 * @return {String} Returns compacted string.
 */
function csapiCompactString(val) {
	val = csapiTrim(val);
	if ( val == '' ) { return val; }
	var o = '';
	var a = 0;
	for(var i=0; i<val.length; i++) {
		a = val.charCodeAt(i);
		switch(a) {
			case 32	:
			case 45	:
			case 95	:
				o += '_';
				break;
			default	:
				if ( (a >= 48 && a <= 57) || (a >= 65 && a <= 90) || (a >= 97 && a <= 122) ) {
					o += val.charAt(i).toLowerCase();
				} else if ( a == 32 ) {
					o += '_';
				}
				break;
		}
	}
	return o;
}
/**
 * Trims a string
 * @param {String} val Value to trim
 * @return {String}
 */
function csapiTrim(val) {
	val = ""+val;
	return val.replace(/^\s+/,'').replace(/\s+$/,'');
}
/* end APIs */