/*
 * $Author: wayne $
 * $LastChangedBy: wayne $
 * $Revision: 4148 $
 * $Date: 2011-08-05 14:17:31 +0200 (Fri, 05 Aug 2011) $
 */

var playFairJsLibRevision = "$Revision: 4148 $";

var _dashCodeVersion=9;
var previousJsonCommand;
var dataIsland = new Array();
var currentSelectedOID;
var currentCategoryID;
var jqueryPanelHeight = 500;
var jqueryPanelWidth = 700;
var jqueryPanelExists=false;
var jqueryAlertDialogExists=false;
// --------------------DATA STRUCTURES AND PROTOTYPE CLASSES

var compEntryCheck = getUrlVars()["entry"];
if(compEntryCheck == 'complete'){
	alert('You have been entered into the competition, Good Luck!');
}
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, 
		function(m,key,value) {
	        vars[key] = value;
	    }
    );
	return vars;
}

function genericCollection() {
	this.add = function(fName, fValue) {
		this[fName] = fValue;
	};
}

function jsonCommand(cName,debugMode) {
	this.commandName = cName;
	if (debugMode == true)
	{
			var now = new Date().getTime() / 1000;  
			var s = parseInt(now);
			var r=Math.floor(Math.random()*99999);
			var dC = s+'-'+r; 
			this.debug = dC;
	}
	this.parameters = new genericCollection();
	
	if (_dashCodeVersion == undefined)
	{
		this.parameters.add ('_dashCodeVersion',0);
	}
	else
	{
		this.parameters.add ('_dashCodeVersion',_dashCodeVersion);
	}
	
}

function jsonQueryArguments(qName) {
	this.queryName = qName;
	this.limit = 0;
	this.offset = 0;
	this.whereFields = new genericCollection();
	this.orderFields = new genericCollection();
}

// ------------------------------------------------------------------

// --------------------J-----------JSON DATA RETRIEVAL FOR SQL2JSON
// --------------------J----------------------------------------------------
function jsonQuery(jsonParams, jsonRenderDelegate, debugMode) {
	if (debugMode == true)
	{
//		var pString = URLEncode(YAHOO.lang.JSON.stringify(jsonParams));
//		var dataURI = "/jsonCommand/?cb_rnd=" + cacheBust() + "&c=" + pString;
//		var win = window.open(dataURI + "&debug=1");
	}
	jqueryJsonQuery(jsonParams, jsonRenderDelegate,debugMode);
}



function jqueryJsonQuery(jsonParams, jsonRenderDelegate,debugMode) {
	$.ajax({
		  mode:'queue',
		  type: 'POST',
		  url: '/jsonCommand/',
		  data: jsonParams,
		  success: function(data, textStatus, XMLHttpRequest){
	     		eval(jsonRenderDelegate+"(data);");
	   			},
		  dataType: 'json'
		});
	
	if (jsonParams.debug)
	{
		var win = window.open('/jsonCommand/debug.php?id='+jsonParams.debug);
	}
		
}

function yuiJsonQuery(jsonParams) {
	var callbacks = {
		success : function(o) {
			var messages = [];
			try {
				messages = YAHOO.lang.JSON.parse(o.responseText);
			} catch (x) {
				alert("JSON Parse failed!");
				return;
			}
			eval(jsonRenderDelegate + "(messages)");
		},

		failure : function(o) {
			if (!YAHOO.util.Connect.isCallInProgress(o)) {
				alert("An error occured while trying to retrieve some of the requested data.\nPlease reload this page.  \n\n We're sorry for the inconvenience :-(");
			}
		},
		timeout : 5000
	}

	var pString = URLEncode(YAHOO.lang.JSON.stringify(jsonParams));

	// Make the call to the server for JSON data
	if (transportMode != 'POST') {
		var dataURI = "/jsonCommand/?cb_rnd=" + cacheBust() + "&c=" + pString;
		YAHOO.util.Connect.asyncRequest('GET', dataURI, callbacks);

		if (debugMode == true)
			var win = window.open(dataURI + "&debug=1");

	} else {
		var postData = "c=" + pString;
		var dataURI = "/jsonCommand/?cb_rnd=" + cacheBust();
		// YAHOO.util.Connect.asyncRequest('POST', dataURI, callbacks,postData
		// );
		var request = YAHOO.util.Connect.asyncRequest('POST', dataURI,
				callbacks, postData);

		if (debugMode != null)
			var win = window.open(dataURI + "&c=" + pString + "&debug=1");

	}
}
// ===START: BUILT-IN GENERIC RENDER
// DELEGATES======================================

// This one drops ms.data (as HTML) into innerHTML of HTML entity with id of
// ms.targetContainer
function _renderGenericHTML(ms) {
	unsetBusy();
	
	if(ms.status=='LOGOUT')
	{
		doAdminLogout();
		return;
	}
	if (ms.data != null && ms.targetContainer != null) 
	{
		var target = document.getElementById(ms.targetContainer);
		if (target != null && target != undefined)
		{
			target.innerHTML = ms.data;
		}
		else
		{
			var target = document.getElementById('dashBodyContent');
			target.innerHTML = ms.data;
		}
	}
	
	if (ms.execJS != null)
	{
		eval(ms.execJS);
	}
	
	
	if (ms.chainRender != null) {
		var tmpCommand = ms.chainRender;
		var cmd='';
		if (tmpCommand.indexOf('(')>-1)
		{
			cmd = ms.chainRender;
		}
		else
		{
			cmd = ms.chainRender + "(ms);";
		}
		eval(cmd);
	}
}

 
function _renderInPanel(ms)
{
	if(ms.status=='LOGOUT')
	{
		doAdminLogout();
		return;
	}

	if (ms.panelWidth != undefined && ms.panelHeight!= undefined)
	{
		panelSetSize(ms.panelWidth,ms.panelHeight);
	}
	
	var displayTitle = 'Feedback';
	
	if (ms.panelTitle != undefined)
	{
		displayTitle=ms.panelTitle;
	}
	else
	{
		if (ms.status != undefined)
		{
			displayTitle =ms.status; 
		}
	}
	
	if (ms.status == 'ERROR')
	{
		showAlert(displayTitle,ms.data);
	}
	else
	{
		panelShow(displayTitle,ms.data);
	}
	unsetBusy();	
	
	if (ms.chainRender != null) {
		var cmd = ms.chainRender + "(ms);";
		eval(cmd);
	}
}


function _renderNull(ms) {
	if(ms.status=='LOGOUT')
	{
		doAdminLogout();
		return;
	}

	unsetBusy();
}

function _renderFeedback(ms) {
	unsetBusy();

	if(ms.status=='LOGOUT')
	{
		doAdminLogout();
		return;
	}

	switch (ms.status) {
	case 'OK':
		showAlert("SUCCESS",ms.data);
		break;
	case 'ERROR':
		showAlert("ERROR" , ms.data);
		break;
	default:
		showAlert(ms.status,ms.data);
		break;
	}

	if (ms.closePanel != undefined) {
		panelHide();
	}

	if (ms.chainRender != null && ms.chainRender != '_renderFeedback') {
		var cmd = ms.chainRender + "(ms);";
		eval(cmd);
	}
}
function _renderPageRefresh(ms) {
	unsetBusy();
	if (ms != undefined)
	{
		if(ms.status=='LOGOUT')
		{
			doAdminLogout();
			return;
		}
	}
	window.location.reload();
}

function _renderRemoteHelp(ms) {
	if(ms.status=='LOGOUT')
	{
		doAdminLogout();
		return;
	}

	unsetBusy();
	if (ms.helpFound) {
		YAHOO.INXCOM.IMS.panelHelp.cfg.setProperty('context', null);
		YAHOO.INXCOM.IMS.panelHelp.cfg.setProperty('width', '450px');
		panelShow('Help', ms.helpText, '&nbsp;', true);
	}
	
	if (ms.chainRender != null) {
		var cmd = ms.chainRender + "(ms);";
		eval(cmd);
	}

	
}

// ===END: BUILT-IN GENERIC RENDER
// DELEGATES======================================

// ===========================================================================================================================
function toggleAllCheckbox(elBaseName) {
	var inputs = document.getElementsByTagName("input");
	for ( var i = 0; i < inputs.length; i++) {
		if (inputs[i].name.indexOf(elBaseName) == 0) {
			inputs[i].checked = !inputs[i].checked;
		}
	}
}

function cacheBust() {
	var milli = new Date();
	var retVal = milli.getTime() + "_" + Math.random();
	return retVal;
}

function hashToPath(inHash) {
	var retVal = inHash.substr(0, 3) + '/' + inHash.substr(3, 3) + '/'
			+ inHash.substr(6, 3) + '/' + inHash.substr(9, 3) + '/'
			+ inHash.substr(12, 20);

	return retVal;
}

function padInteger(n, totalDigits) {
	n = n.toString();
	var pd = '';
	if (totalDigits > n.length) {
		for (i = 0; i < (totalDigits - n.length); i++) {
			pd += '0';
		}
	}
	return pd + n.toString();
}


function URLEncode(clearString) {
	var returnString = clearString.replace("?", "%3F");
	returnString = returnString.replace("&", "%26");
	returnString = returnString.replace("/", "%2F");
	return (returnString);
}

function URLDecode(clearString) {
	var returnString = clearString.replace("%3F","?");
	returnString = returnString.replace("%26","&");
	returnString = returnString.replace( "%2F","/");
	return (returnString);
}

var Url = {
		 
		// public method for url encoding
		encode : function (string) {
			return escape(this._utf8_encode(string));
		},
	 
		// public method for url decoding
		decode : function (string) {
			return this._utf8_decode(unescape(string));
		},
	 
		// private method for UTF-8 encoding
		_utf8_encode : function (string) {
			string = string.replace(/\r\n/g,"\n");
			var utftext = "";
	 
			for (var n = 0; n < string.length; n++) {
	 
				var c = string.charCodeAt(n);
	 
				if (c < 128) {
					utftext += String.fromCharCode(c);
				}
				else if((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				}
				else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}
	 
			}
	 
			return utftext;
		},
	 
		// private method for UTF-8 decoding
		_utf8_decode : function (utftext) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
	 
			while ( i < utftext.length ) {
	 
				c = utftext.charCodeAt(i);
	 
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				}
				else if((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i+1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				}
				else {
					c2 = utftext.charCodeAt(i+1);
					c3 = utftext.charCodeAt(i+2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
	 
			}
	 
			return string;
		}
	 
	};




// =========================================================================
function tool_newsletterSubscription_Subscribe() {
	var inp = document
			.getElementById('tool_newsletterSubscriptionForm_firstName');
	var firstName = inp.value;

	inp = document.getElementById('tool_newsletterSubscriptionForm_lastName');
	var lastName = inp.value;

	inp = document
			.getElementById('tool_newsletterSubscriptionForm_emailAddress');
	var emailAddress = inp.value;

	inp = document
			.getElementById('tool_newsletterSubscriptionForm_newsletterID');
	var newsletterID = inp.options[inp.selectedIndex].value;

	var myCommand = new jsonCommand("pfl_SubscribeToNewsletter");
	myCommand.parameters.add('firstName', firstName);
	myCommand.parameters.add('lastName', lastName);
	myCommand.parameters.add('emailAddress', emailAddress);
	myCommand.parameters.add('newsletterID', newsletterID);

	jsonQuery(myCommand, "_renderFeedback");
}

function panelHide(panelTag,clearContents)
{
	//yuiPanelHide(panelTag,clearContents);
	jqueryPanelHide(panelTag);
}

function jqueryPanelHide(targetPanelID)
{
	if (targetPanelID != undefined)
	{
		$("#"+targetPanelID).dialog('close');
	}
	else
	{
			$("#jqueryDialog").dialog('close');
	}
}

function yuiPanelHide(panelTag,clearContents) {
	if (panelTag == undefined)
	{
		panelTag='';
	}
	clearContents = (clearContents==null)?true:clearContents;
	switch (panelTag)
	{
		case null:
			if (clearContents)
			{
				var panelTitle = document.getElementById('panelTitle');
				panelTitle.innerHTML = '';
				var panelBody = document.getElementById('panelBody');
				panelBody.innerHTML = '';
				var panelStatus = document.getElementById('panelStatus');
				panelStatus.innerHTML = '';
			}
			YAHOO.INXCOM.IMS.panel.hide();
			break;
		default:
			var cmd = "var thisYuiPanel = YAHOO.INXCOM.IMS.panel" + panelTag +";";
			eval(cmd);

			if (clearContents)
			{
				var panelTitle = document.getElementById('panel'+panelTag+'Title');
				if (panelTitle != null)
					panelTitle.innerHTML = '';
				var panelBody = document.getElementById('panel'+panelTag+'Body');
				if (panelBody  != null)
					panelBody.innerHTML = '';
				var panelStatus = document.getElementById('panel'+panelTag+'Status');
				if (panelStatus!=null) 
					panelStatus.innerHTML = '';
			}
			thisYuiPanel.hide();
			break;
	}

}

function showAlert(myTitle,myMessage,alertWidth,alertHeight)
{
//	if (jqueryAlertDialogExists)
//	{
//		$("#alertDialog").dialog('destroy');
//		jqueryAlertDialogExists=false;
//	}
	
	jqueryAlertDialogExists=true;
	var divTarget=document.getElementById('alertDialog');
	if (divTarget == undefined)
	{
		$('body').append('<div id="alertDialog">&nbsp;</div>');
	}
	var divTarget=document.getElementById('alertDialog');
	divTarget.title=myTitle;
	divTarget.innerHTML='<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>'+myMessage+'</p>';
	
	if (alertWidth == undefined)
	{
		alertWidth = 300;
	}
	if (alertHeight== undefined)
	{
		alertHeight = 200;
	}
	
	return $("#alertDialog").dialog({
		title:myTitle,
		bgiframe: true,
		resizable: false,
		height:alertHeight,
		width:alertWidth,
		modal: true,
		dialogClass: 'alert',
		closeOnEscape: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			Close: function() {
				$(this).dialog('close');
			}
		}
	});
}

function panelShowExisting(dlgID,myTitle, myContent,width,height,showModal)
{
	$('#'+dlgID).dialog('destroy');
	var target = document.getElementById(dlgID);
	target.innerHTML=myContent;
	target.title=myTitle;
	$("#"+dlgID).dialog({ autoOpen: false, width: width, height: height ,modal:showModal });
	$("#"+dlgID).dialog('open');
}

function panelShowNew(myTitle, myContent, width,height,showModal,allowResize)
{
	if (allowResize == undefined)
	{
		allowResize=true;
	}
	//Any panels available for re-use?
	var panels = $('.jqPanel');
	for(var i=0; i<panels.length; i++)
	{
		var thisPanel = panels[i];
		if ($('#'+thisPanel.id).dialog('isOpen') == false)
		{
			$('#'+thisPanel.id).dialog('destroy');
			var target = document.getElementById(thisPanel.id);
			target.innerHTML=myContent;
			target.title=myTitle;
			$("#"+thisPanel.id).dialog({ width: width, height: height ,modal:showModal, resizable:allowResize });
			return thisPanel.id;
		}
	}
	var panelID = uniqid();
	$('body').append('<div title="'+myTitle+'" id="'+panelID+'" class="jqPanel">'+myContent+'</div>');
	$("#"+panelID).dialog({ autoOpen: false, width: width, height: height ,modal:showModal,closeOnEscape: false, bgiframe:true,resizable:allowResize });
	$("#"+panelID).dialog('open');
	return panelID;
}

function panelResizeAnimated(panelID, width,height,top,left)
{
	var dlg = $('#'+panelID).parents(".ui-dialog:first");
	if (top != undefined && left != undefined)
		dlg.animate({ width: width, height: height, top: top, left: left});
	else
		dlg.animate({ width: width, height: height}); 
}

function panelShow(myTitle, myContent, showModal)
{
	showModal=false;
	jqueryPanelShow(myTitle, myContent,showModal );
}

function jqueryPanelShow(myTitle, myContent, showModal) {
	var test =document.getElementById('jqueryDialog');
	if (test == undefined)
	{
		$('body').append('<div id="jqueryDialog">&nbsp;</div>');
	}
	
	$("#jqueryDialog").dialog('destroy');
	var target = document.getElementById('jqueryDialog');
	target.innerHTML=myContent;
	target.title=myTitle;
	$("#jqueryDialog").dialog({ autoOpen: false, width: jqueryPanelWidth, height: jqueryPanelHeight,modal:showModal,closeOnEscape: false,bgiframe:true });
	$("#jqueryDialog").dialog('open');
}



function yuiPanelShow(myTitle, myContent, myStatus, useHelpPanel, contextID) {
	var helpTag = '';
	
	switch (useHelpPanel)
	{
		case null:
			useHelpPanel = false;
			var thisYuiPanel = YAHOO.INXCOM.IMS.panel;
			alert(YAHOO.INXCOM.IMS.panel);
			break;
		case true:
			helpTag = 'Help';
			var thisYuiPanel = YAHOO.INXCOM.IMS.panelHelp;
			break;
		case 'Uploader':
			helpTag="Uploader";
			var thisYuiPanel = YAHOO.INXCOM.IMS.panelUploader;
			break;
	}
	
	
/*	if (useHelpPanel == null) {
		useHelpPanel = false;
		var thisYuiPanel = YAHOO.INXCOM.IMS.panel;
	} else {
		if (useHelpPanel) {
			helpTag = 'Help';
			var thisYuiPanel = YAHOO.INXCOM.IMS.panelHelp;
		} else {
			var thisYuiPanel = YAHOO.INXCOM.IMS.panel;
		}
	}
	*/

	if (myTitle != '') {
		var panelTitle = document.getElementById('panel' + helpTag + 'Title');
		panelTitle.innerHTML = myTitle;
	}

	if (myContent != '') {
		var panelBody = document.getElementById('panel' + helpTag + 'Body');
		panelBody.innerHTML = myContent;
	}

	if (myStatus != '') {
		var panelStatus = document.getElementById('panel' + helpTag + 'Status');
		panelStatus.innerHTML = myStatus;
	}

	var modal = false;
	if (modal == true) {
		thisYuiPanel.cfg.setProperty('modal', true);
	} else {
		thisYuiPanel.cfg.setProperty('modal', false);
	}

	//alert(contextID);
	if (contextID != null) {
		thisYuiPanel.cfg.setProperty('context', [ contextID, 'br', 'tr' ]);
	}

	thisYuiPanel.show();
}

function panelSetSize(width, height) {
	jqueryPanelHeight = height;
	jqueryPanelWidth = width;
}

function panelBody() {
	return document.getElementById('panelBody');
}
function panelClearChildren() {

	var panelBody = document.getElementById('panelBody');
	while (panelBody.hasChildNodes()) {
		panelBody.removeChild(panelBody.lastChild);
	}
}

function panelAppendChild(newNode) {
	var panelBody = document.getElementById('panelBody');
	panelBody.appendChild(newNode);
}


function goURL(newURI)
{
	jsNav(newURI);
}
function jsNav(newURI) {
	window.location.href = newURI;
}

function launchPopup(targetURI)
{
	  var win_iafricaPopup=window.open(targetURI,"_blank","toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,width=500,height=350,resizable");
}

function unsetBusy()
{
	var busy = document.getElementById("ajxBusy");
	if (busy!=null)
		busy.style.visibility="hidden";
}
function setBusy()
{
	var busy = document.getElementById("ajxBusy");
	if (busy!=null)
		busy.style.visibility="visible";
}

function toggleRollup(targetID)
{
	var target = document.getElementById(targetID);
	if (target.style.height =='20px')
	{
		target.style.height ='auto';
	}
	else
	{
		target.style.height ='20px';
	}
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function adLoader()
{
	var arSurrogates = YAHOO.util.Dom.getElementsByClassName('adSurrogate');
	for (var i=0; i<arSurrogates.length; i++)
	{
		var thisSurrogate = arSurrogates[i];
		var surrogateID = thisSurrogate.id;
		var parts = surrogateID.split('_');
		var targetID =  'webAd_'+parts[1];
		var targetDiv = document.getElementById(targetID);
		var code = thisSurrogate.innerHTML;
		targetDiv.innerHTML = code;
	}
}


function setRegistryValue(regSection, keyName, regValue, saveMode) {
	if (saveMode == null) {
		saveMode = 'silent';
	}

	var myCommand = new jsonCommand('modules/registry/save');
	myCommand.parameters.add('mode', saveMode);
	myCommand.parameters.add('Section', regSection);
	myCommand.parameters.add('Name', keyName);
	myCommand.parameters.add('Value', regValue);
	jsonQuery(myCommand, "_renderNull");
}

function dynoFields(theTarget,searchText,setBack){
	//alert(theTarget);
	var checkItem = document.getElementById(theTarget).value;
	if(checkItem == searchText){
		document.getElementById(theTarget).value = "";
	}
	if(setBack == "setBack"){
		if(checkItem == "" || checkItem == " "){
			document.getElementById(theTarget).value = searchText;
		}
	}
}


function MM_jumpMenuGo(objId,targ,restore){ //v9.0
	  var selObj = null;  with (document) { 
	  if (getElementById) selObj = getElementById(objId);
	  if (selObj) eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	  if (restore) selObj.selectedIndex=0; }
	}

function ajaxLoadPage(uri,targetContainerID)
{
	$.get(uri, function(data) {
		  $('#'+targetContainerID).html(data);
		});
}

function uniqid()
{
	var newDate = new Date;
	return newDate.getTime();
}

function hideThis(id){
    if(document.getElementById(id)){
        var it = document.getElementById(id);
    }
    if(it.style.visibility != 'hidden'){
        it.style.display = 'none';
        it.style.visibility = 'hidden';
    }
}


//-----------------------------------------------------------------------------------------
//---------------------ARB FUNCTIONS FROM IAF------------------------------------
//-----------------------------------------------------------------------------------------

/*
* ============================================================================
* nnjsValidateForm.js - Universal HTML Form Validator JScript
*
* Copyright (C) 2002 by N-Networks. All Rights Reserved.
* http://www.dpsp-yes.com
*
* Modification history:
*
* Feb 21, 2002  v1.0.0   V.Bulatov     - initially created
* Mar 05, 2002  v1.0.1   V.Zakharychev - cleaned up some names and texts
* Aug 26, 2002  v1.1.0   V.Bulatov     - IsDate attribute added
*
*
* Sample usage: 
* <form .... OnSubmit="return nnjsValidateForm( this );">
*   or 
* <form .... OnSubmit="return nnjsValidateForm( this ) && SomeUsersFunction(....);">
* ....
* <input type=text IsRegex="^[abc]$"  .... IsRegexTxt="bla bla" >
* <input type=text IsNotEmpty IsDigit .... IsNotEmptyTxt="bla1" IsDigitTxt="bla2">
* <input type=text IsNotEmpty IsEmail .... CommonTxt="bla bla">
* ....
* </form>
*
* See nnjsValidateForm.html for more details
* ============================================================================
*
* *** IMPORTANT! THIS SCRIPT IS SHAREWARE ***
* If you find this script useful, please register at http://www.dpsp-yes.com
* to use it legally. This script can not be used for any purpose except
* evaluation without registration. Registered users are entitled to free email
* support and updates. They will also benefit from clean conscience and good
* karma.
*
* Any modifications to the script are expressly prohibited. Please do not
* change or remove any copyright notices and other text and/or functionality.
* If you miss some functionality, please email us and we will gladly implement
* it in the script (provided that you are registered user, that is).
* ============================================================================
*/

// you are free to change the values below to fit your style

var nnjsCommonTxt     = "Entered value is not valid";   // Generic error message
var nnjsIsNotEmptyTxt = "The field cannot be empty";    // Field is empty
var nnjsIsDigitTxt    = "Numeric value expected";       // Field is not numeric
var nnjsIsDateTxt     = "Valid date value expected";    // Field is not a valid date
var nnjsIsEmailTxt    = "Valid email address expected"; // Field is not a valid email address
var nnjsIsRegexTxt    = "Entered value did not match given restrictions"; // Field didn't match regexp

var nnjsIsDateFmt     = "MM/DD/YYYY"; // Default format for date value

// DO NOT CHANGE ANYTHING PAST THIS LINE!

function nnjsValidateFocus( item ){
// bring focus to the form item if it can have focus
  if( item.type == "text" ||
      item.type == "password" || 
      item.type == "checkbox" || 
      item.type == "select-one" ||
      item.type == "select-multiple" ||
      item.type == "button" ||
      item.type == "textarea"
    ){
    item.focus();
    return true;
    }
  else{
    return false;
    }
  }

function nnjsValidateAlert( msg1, msg2, msg3, msg4 ){
// alert user using appropriate message
  if( msg1 ){ alert( msg1 ); }
  else{
    if( msg2 ){ alert( msg2 ); }
    else{
      if( msg3 ){ alert( msg3 ); }
      else{
        if( msg4 ){ alert( msg4 ); }
        }
      }
    }
  return true;
  }

function nnjsValidateDate( year, month, day ){
// validate date
// the full year, for example, 1976 (and not 76 for 1976)
// the month as an integer between 0 and 11 (January to December)
// the date as an integer between 1 and 31

  if( day < 1 || day > 31 || month < 0 || month > 11 || year < 0 )
    return false;
  if( day == 31 && ( month == 3 || month == 5 || month == 8 || month == 10 ))
    return false;
  if( day > 29 && month == 1 )
    return false;
  if( day == 29 && month == 1 && (( year % 4 != 0 ) || ( year % 100 == 0 && year % 400 != 0 )))
    return false;

  return true;
  }

function nnjsValidateForm( fm ){
// main validation routine
  for( i = 0; i < fm.elements.length; i++ ){
    var item = fm.elements.item(i);
    if( item && !item.disabled ){

      // check for NotEmpty
      if( item.getAttribute('IsNotEmpty') != null ){
        // check if item is filled/selected
        if(( item.value == "" ) ||
           ( item.type == "checkbox" && !item.checked )
          ){
          nnjsValidateFocus( item );
          nnjsValidateAlert(
            item.IsNotEmptyTxt,
            item.CommonTxt,
            nnjsIsNotEmptyTxt,
            nnjsCommonTxt
            );
          return false;
          }
        }

      // check if item is numeric
      if( item.getAttribute('IsDigit') != null ){
        var rex = /^-?\d+(\.\d+)?$/;
        if( item.IsDigit != "" ){
          if( item.IsDigit.search( /^-?([=z]?\d)|(z?\*)(\.([=z]?\d)|(z?\*))$/ ) == 0 ){
            //replacing rex with appropriate regexp
            }
          }
        if( item.value != "" && item.value.search( rex ) == -1 ){
          nnjsValidateFocus( item );
          nnjsValidateAlert(
            item.IsDigitTxt,
            item.CommonTxt,
            nnjsIsDigitTxt,
            nnjsCommonTxt
            );
          return false;
          }
        }

      // check if item is date
      if( item.getAttribute('IsDate') != null ){
        var fmt = item.getAttribute('IsDate');
        if( fmt == "" ) fmt = nnjsIsDateFmt;

        // determine order of date fields
        var mpos = fmt.search( /MM/ );
        var dpos = fmt.search( /DD/ );
        var ypos = fmt.search( /YYYY/ );
        var midx = 1, didx = 1, yidx = 1;
        if( mpos > dpos ) midx++;
        if( mpos > ypos ) midx++;
        if( dpos > mpos ) didx++;
        if( dpos > ypos ) didx++;
        if( ypos > mpos ) yidx++;
        if( ypos > dpos ) yidx++;

        // build regular expression according to date format
        fmt = fmt.replace( /\\/g, "\\\\" );
        fmt = fmt.replace( /MM/g, "(\\d{1,2})" );
        fmt = fmt.replace( /DD/g, "(\\d{1,2})" );
        fmt = fmt.replace( /YYYY/g, "(\\d{4})" );
        var rex = new RegExp( '^' + fmt + '$' );
        var sep = item.value.match( rex );

        if( item.value != "" &&
          ( sep == null || !nnjsValidateDate( sep[yidx], sep[midx]-1, sep[didx] ))){
          nnjsValidateFocus( item );
          nnjsValidateAlert(
            item.IsDateTxt,
            item.CommonTxt,
            nnjsIsDateTxt,
            nnjsCommonTxt
            );
          return false;
          }
        }

      // check if item is valid email address
      if( item.getAttribute('IsEmail') != null ){
        if( item.value != "" && item.value.search( /^[\w\.-_]+@[\w-_]+\.[\w\.-_]+$/ ) == -1 ){
          nnjsValidateFocus( item );
          nnjsValidateAlert(
            item.IsEmailTxt,
            item.CommonTxt,
            nnjsIsEmailTxt,
            nnjsCommonTxt
            );
          return false;
          }
        }

      // check if item matches the regular expression
      if( item.getAttribute('IsRegex') != null ){
        var rex = new RegExp( item.IsRegex );
        if( item.value != "" && item.value.search( rex ) == -1 ){
          nnjsValidateFocus( item );
          nnjsValidateAlert(
            item.IsRegexTxt,
            item.CommonTxt,
            nnjsIsRegexTxt,
            nnjsCommonTxt
            );
          return false;
          }
        }

      } // if
    } // for

  // all checks passed - form data is ok.
  return true;
} // nnjsValidateForm


function componentRemoteLoad(componentID,chainRender,extraArguments)
{
	var myCommand = new jsonCommand("pfl_playFairObjectProxy");
	myCommand.parameters.add('componentHtmlID',componentID);

	if(chainRender != undefined && chainRender != null)
	{
		myCommand.parameters.add('chainRender',chainRender);
	}
	
	if (extraArguments != undefined)
	{
		myCommand.parameters.add('extraArguments',extraArguments);
	}
	
	jsonQuery(myCommand, "_componentReload");
}

function _componentReload(ms)
{
	$('#'+ms.targetContainer).replaceWith(ms.data);
	if (ms.chainRender != null) {
		var cmd = ms.chainRender + "(ms);";
		eval(cmd);
	}

}

function doAdminLogout()
{
	window.location.href="/_admin/auth/editLogout.php";
}
function humanReadableBytes(value, startScaleIdx) {
	if (startScaleIdx == undefined) {
		startScaleIdx = 0;
	}
	var scaleUnit = Array("B", "Kb", "Mb", "Gb", "Tb", "Pb");
	var unitIdx = startScaleIdx;
	while (value >= 1024) {
		value = value / 1024;
		unitIdx++;
	}
	retVal = (Math.round(value * 100) / 100).toFixed(2) + scaleUnit[unitIdx];
	return retVal;
}


function sendFriend(articleID,articleUrl) {
	sURL2 = '/apps/sendToAFriend/?content_id=' + articleID + '&url=' + articleUrl;
	spawn_window(sURL2,'myWin','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,width=450,height=350,resizable=yes');
}		
function spawn_window(content,spawn,sizing){
	window.open(content,spawn,sizing);
}


var hexcase=0;function hex_md5(a){return rstr2hex(rstr_md5(str2rstr_utf8(a)))}function hex_hmac_md5(a,b){return rstr2hex(rstr_hmac_md5(str2rstr_utf8(a),str2rstr_utf8(b)))}function md5_vm_test(){return hex_md5("abc").toLowerCase()=="900150983cd24fb0d6963f7d28e17f72"}function rstr_md5(a){return binl2rstr(binl_md5(rstr2binl(a),a.length*8))}function rstr_hmac_md5(c,f){var e=rstr2binl(c);if(e.length>16){e=binl_md5(e,c.length*8)}var a=Array(16),d=Array(16);for(var b=0;b<16;b++){a[b]=e[b]^909522486;d[b]=e[b]^1549556828}var g=binl_md5(a.concat(rstr2binl(f)),512+f.length*8);return binl2rstr(binl_md5(d.concat(g),512+128))}function rstr2hex(c){try{hexcase}catch(g){hexcase=0}var f=hexcase?"0123456789ABCDEF":"0123456789abcdef";var b="";var a;for(var d=0;d<c.length;d++){a=c.charCodeAt(d);b+=f.charAt((a>>>4)&15)+f.charAt(a&15)}return b}function str2rstr_utf8(c){var b="";var d=-1;var a,e;while(++d<c.length){a=c.charCodeAt(d);e=d+1<c.length?c.charCodeAt(d+1):0;if(55296<=a&&a<=56319&&56320<=e&&e<=57343){a=65536+((a&1023)<<10)+(e&1023);d++}if(a<=127){b+=String.fromCharCode(a)}else{if(a<=2047){b+=String.fromCharCode(192|((a>>>6)&31),128|(a&63))}else{if(a<=65535){b+=String.fromCharCode(224|((a>>>12)&15),128|((a>>>6)&63),128|(a&63))}else{if(a<=2097151){b+=String.fromCharCode(240|((a>>>18)&7),128|((a>>>12)&63),128|((a>>>6)&63),128|(a&63))}}}}}return b}function rstr2binl(b){var a=Array(b.length>>2);for(var c=0;c<a.length;c++){a[c]=0}for(var c=0;c<b.length*8;c+=8){a[c>>5]|=(b.charCodeAt(c/8)&255)<<(c%32)}return a}function binl2rstr(b){var a="";for(var c=0;c<b.length*32;c+=8){a+=String.fromCharCode((b[c>>5]>>>(c%32))&255)}return a}function binl_md5(p,k){p[k>>5]|=128<<((k)%32);p[(((k+64)>>>9)<<4)+14]=k;var o=1732584193;var n=-271733879;var m=-1732584194;var l=271733878;for(var g=0;g<p.length;g+=16){var j=o;var h=n;var f=m;var e=l;o=md5_ff(o,n,m,l,p[g+0],7,-680876936);l=md5_ff(l,o,n,m,p[g+1],12,-389564586);m=md5_ff(m,l,o,n,p[g+2],17,606105819);n=md5_ff(n,m,l,o,p[g+3],22,-1044525330);o=md5_ff(o,n,m,l,p[g+4],7,-176418897);l=md5_ff(l,o,n,m,p[g+5],12,1200080426);m=md5_ff(m,l,o,n,p[g+6],17,-1473231341);n=md5_ff(n,m,l,o,p[g+7],22,-45705983);o=md5_ff(o,n,m,l,p[g+8],7,1770035416);l=md5_ff(l,o,n,m,p[g+9],12,-1958414417);m=md5_ff(m,l,o,n,p[g+10],17,-42063);n=md5_ff(n,m,l,o,p[g+11],22,-1990404162);o=md5_ff(o,n,m,l,p[g+12],7,1804603682);l=md5_ff(l,o,n,m,p[g+13],12,-40341101);m=md5_ff(m,l,o,n,p[g+14],17,-1502002290);n=md5_ff(n,m,l,o,p[g+15],22,1236535329);o=md5_gg(o,n,m,l,p[g+1],5,-165796510);l=md5_gg(l,o,n,m,p[g+6],9,-1069501632);m=md5_gg(m,l,o,n,p[g+11],14,643717713);n=md5_gg(n,m,l,o,p[g+0],20,-373897302);o=md5_gg(o,n,m,l,p[g+5],5,-701558691);l=md5_gg(l,o,n,m,p[g+10],9,38016083);m=md5_gg(m,l,o,n,p[g+15],14,-660478335);n=md5_gg(n,m,l,o,p[g+4],20,-405537848);o=md5_gg(o,n,m,l,p[g+9],5,568446438);l=md5_gg(l,o,n,m,p[g+14],9,-1019803690);m=md5_gg(m,l,o,n,p[g+3],14,-187363961);n=md5_gg(n,m,l,o,p[g+8],20,1163531501);o=md5_gg(o,n,m,l,p[g+13],5,-1444681467);l=md5_gg(l,o,n,m,p[g+2],9,-51403784);m=md5_gg(m,l,o,n,p[g+7],14,1735328473);n=md5_gg(n,m,l,o,p[g+12],20,-1926607734);o=md5_hh(o,n,m,l,p[g+5],4,-378558);l=md5_hh(l,o,n,m,p[g+8],11,-2022574463);m=md5_hh(m,l,o,n,p[g+11],16,1839030562);n=md5_hh(n,m,l,o,p[g+14],23,-35309556);o=md5_hh(o,n,m,l,p[g+1],4,-1530992060);l=md5_hh(l,o,n,m,p[g+4],11,1272893353);m=md5_hh(m,l,o,n,p[g+7],16,-155497632);n=md5_hh(n,m,l,o,p[g+10],23,-1094730640);o=md5_hh(o,n,m,l,p[g+13],4,681279174);l=md5_hh(l,o,n,m,p[g+0],11,-358537222);m=md5_hh(m,l,o,n,p[g+3],16,-722521979);n=md5_hh(n,m,l,o,p[g+6],23,76029189);o=md5_hh(o,n,m,l,p[g+9],4,-640364487);l=md5_hh(l,o,n,m,p[g+12],11,-421815835);m=md5_hh(m,l,o,n,p[g+15],16,530742520);n=md5_hh(n,m,l,o,p[g+2],23,-995338651);o=md5_ii(o,n,m,l,p[g+0],6,-198630844);l=md5_ii(l,o,n,m,p[g+7],10,1126891415);m=md5_ii(m,l,o,n,p[g+14],15,-1416354905);n=md5_ii(n,m,l,o,p[g+5],21,-57434055);o=md5_ii(o,n,m,l,p[g+12],6,1700485571);l=md5_ii(l,o,n,m,p[g+3],10,-1894986606);m=md5_ii(m,l,o,n,p[g+10],15,-1051523);n=md5_ii(n,m,l,o,p[g+1],21,-2054922799);o=md5_ii(o,n,m,l,p[g+8],6,1873313359);l=md5_ii(l,o,n,m,p[g+15],10,-30611744);m=md5_ii(m,l,o,n,p[g+6],15,-1560198380);n=md5_ii(n,m,l,o,p[g+13],21,1309151649);o=md5_ii(o,n,m,l,p[g+4],6,-145523070);l=md5_ii(l,o,n,m,p[g+11],10,-1120210379);m=md5_ii(m,l,o,n,p[g+2],15,718787259);n=md5_ii(n,m,l,o,p[g+9],21,-343485551);o=safe_add(o,j);n=safe_add(n,h);m=safe_add(m,f);l=safe_add(l,e)}return Array(o,n,m,l)}function md5_cmn(h,e,d,c,g,f){return safe_add(bit_rol(safe_add(safe_add(e,h),safe_add(c,f)),g),d)}function md5_ff(g,f,k,j,e,i,h){return md5_cmn((f&k)|((~f)&j),g,f,e,i,h)}function md5_gg(g,f,k,j,e,i,h){return md5_cmn((f&j)|(k&(~j)),g,f,e,i,h)}function md5_hh(g,f,k,j,e,i,h){return md5_cmn(f^k^j,g,f,e,i,h)}function md5_ii(g,f,k,j,e,i,h){return md5_cmn(k^(f|(~j)),g,f,e,i,h)}function safe_add(a,d){var c=(a&65535)+(d&65535);var b=(a>>16)+(d>>16)+(c>>16);return(b<<16)|(c&65535)}function bit_rol(a,b){return(a<<b)|(a>>>(32-b))};
