var cs_LogState = 0;
var cs_DBLock = 1;
var cs_bSecurityEnabled = 2;
var bJustifyText = 3;
var cs_DateDefault = 12;
var PUBLIC_STATE_LENGTH = 50;
var PUBLIC_STATE_RESERVE = 20;
var ACCOUNT_NAME = 0;
var ACCOUNT_TYPE = 1;
var ACCOUNT_CATEGORY = 2;
var ACCOUNT_ROLE = 3;
var ACCOUNT_LOG_STATE = 4;
var BROWSER_CODENAME = 5;
var BROWSER_MINOR_VERSION = 6;
var BROWSER_NAME = 7;
var BROWSER_VERSION = 8;
var BROWSER_COOKIE_ENABLED = 9;
var BROWSER_CPUCLASS = 10;
var BROWSER_ONLINE = 11;
var BROWSER_PLATFORM = 12;
var BROWSER_USERAGENT = 13;
var BROWSER_LANGUAGE = 14;
var BROWSER_SYSTEM_LANGUAGE = 15;
var BROWSER_USER_LANGUAGE = 16;
var BROWSER_SCREEN_RESOLUTION = 17;
var SYSTEM_SCRIPT_EDITOR = 19;
var DEFAULT_PAGE_TYPE = 1;
var PERSONNEL_PAGE_TYPE = 7;
var SITE_PAGE = 0;
var CUSTOM_PAGE = 1;

// this function enables more than one onload event
var kbd_AddEvent = function (obj, evType, fn)
{ 
  if (obj.addEventListener)
  { 
    obj.addEventListener(evType, fn, false); 
    return true; 
  } else if (obj.attachEvent) { 
    var r = obj.attachEvent("on"+evType, fn); 
    return r; 
  } else { 
   return false; 
  } 
}

/*****************************************************/
/* begin onchange event handler for all documents
/*****************************************************/

// initialise the default document state
var bReadOnly = false;

// initialise the handle for the editor instance
var editorInstanceName = null;

// initialise the change content flag for the current document
var bContentChanged = false;

function onFormChange() 
{
  bContentChanged = true;
  // reset the session active handler
  resetSessionActiveTimeEvent();
}

function onBeforeBrowserUnload (e) 
{
  var e = e || window.event;
  if (window.FCKeditorAPI)
  {
    if (editorInstanceName) confirmEditorState();
    if (bContentChanged) 
    {
      if (e) e.returnValue = 'Changes have been made to this document.  Do you really wish to abandon these changes?';
   }		
 }		
}

// hack for IE (loosely emulates window.onchange event in moz)
var documentIEOnchangeEventHandler = function(obj) 
{
  if (document.attachEvent) 
  {
    var frm = obj.document.forms[0];
    var el = frm.elements;
    for ( i=0; i < el.length; i++ ) 
				{
      if ('text,textarea,select-one,select-multiple,radio,checkbox'.indexOf(el[i].type) != -1) 
						{
        if (el[i].id) 
								{
          switch (el[i].type) 
								  { 
            case "radio":
              obj.document.getElementById(el[i].id).attachEvent('onclick', onFormChange)
              break;
            case "checkbox":
              obj.document.getElementById(el[i].id).attachEvent('onclick', onFormChange)
              break;
            default: 
              obj.document.getElementById(el[i].id).attachEvent('onchange', onFormChange)
              break;
          }
        }
      }
    }
  }
}

var initialiseEditorState = function ()
{
  resetEditorState();
  bContentChanged = false;
}

// check for changes to the editor area
var confirmEditorState = function()
{
  if (editorInstanceName)
  {
    if (!bContentChanged)
    {
      var oEditor = FCKeditorAPI.GetInstance(editorInstanceName);
      if (oEditor.EditorDocument)
      {
        var bScriptOnly = eval(document.getElementById('bScriptOnly').value);
        if (!bScriptOnly) bContentChanged = oEditor.IsDirty();
      }
	}
  }
}

// reset changes to the editor area
var resetCount = 0;
var resetEditorState = function()
{
  if (editorInstanceName)
  {
    try 
    {
      FCKeditorAPI.GetInstance(editorInstanceName).ResetIsDirty();
    }
    catch (e) 
    {
      resetCount++;
      if (resetCount < 5)
      {
        window.setTimeout('resetEditorState()',200);
      } else {
        // state is lost, abandon all hope and reload the window
        window.top.location.reload();
      }
    }
  }
}

// the common prompt used to warn of changes before navigating away from a page
var saveDocumentPrompt = function(iType)
{
  var iHeight = 120;
  var iWidth = 420;
  var bScrollable = false;
  var bResizable = true;
  var bChrome = false;
  var bModal = true;
  var nvPopName = 'saveDocumentPrompt';
  var nvURL = '/admin/tp_SaveDocumentDialog.asp?iActionType='+iType;
  if (bModal && window.showModalDialog) 
  {
    window.top.document.body.style.opacity = 0.5;
    var nvParams = window.showModalDialog(nvURL, nvPopName, 'dialogHeight:'+parseInt(iHeight+35)+'px;dialogWidth:'+parseInt(iWidth+25)+'px;resizable:yes;status:no;center:yes}'); 
    window.top.document.body.style.opacity = 1;
    if (nvParams) 
    {
      var ar = nvParams.split('|');
      var iAction = ar[0];
      var iType = ar[1];
      return confirmSaveDocumentAction(iAction, iType);
    }
  } else {
    popWindow(nvURL,iHeight,iWidth,bScrollable,bResizable,nvPopName,bChrome,bModal);
  }
  return false;
}

/*****************************************************/
/* begin kaboodle session timeout scripts
/*****************************************************/

// Note:  We detect key and mouse movement and reset the active session variable.
//        Periodically, based on a site constant defined by the user, we look to 
//        see whether the time passed is greater than the last mouse or key event,
//        If there has been no action and the timeout period has been exceeded we
//        logoff and return to the site home page

var getTimeInMinutes = function() 
{
  var d = new Date();
  return parseFloat(Math.round(d.getTime() / 60000));
}

function activeSessionHandler () 
{
  var accountActive = window.top.accountActiveState(); 
  if (accountActive) window.top.expiredSessionHandler(accountActive);
}

var expiredSessionHandler = function(accountActive) 
{
  if (accountActive) 
  {
    if (window.top.kbdTimeoutPeriodExpired()) window.top.kbdLogout();  
    setTimeout('window.top.expiredSessionHandler(' + accountActive + ')', 60000);   
  }
}

var kbdTimeoutPeriodExpired = function()
{
  var timeoutCheckpoint = window.top.lastSessionActiveTime + window.top.kbdTimeoutPeriod();
  if (timeoutCheckpoint <= window.top.getTimeInMinutes()) return true;
  return false;
}

var kbdTimeoutPeriod = function() 
{
  var timeoutPeriod = 0;
  var el = document.getElementsByTagName("meta");
  for (var i=0; i<el.length; i++) 
  {
    if (el.item(i).name == 'cms-timeout') 
	{
	  return parseInt(el.item(i).content);
    }
  }
  return parseInt(timeoutPeriod);
}

var accountActiveState = function() 
{
  var bSessionState = (window.top.getState(cs_LogState) === 1) ? true : false;
  return bSessionState;
}

var kbdLogout = function() 
{
  if (window.top.accountActiveState()) 
  {
    sessionActiveTimeReset = true;
    location.href = '/admin/tp_LogoutForm.asp';
  }
}

function resetSessionActiveTimeEvent()
{
  lastSessionActiveTime = window.top.getTimeInMinutes();
}

// capture any activity in the FCKEditor window
function FCKeditor_OnComplete(editorInstance)
{
  window.top.editorInstanceName = editorInstance.Name;
  editorInstance.Events.AttachEvent( 'OnSelectionChange', window.top.resetSessionActiveTimeEvent );
  FCKeditorAPI.GetInstance(editorInstance.Name).ResetIsDirty();
  if (bReadOnly) editorInstance.EditorDocument.body.contentEditable = false;
  if (window.forceExpandEditor) forceExpandEditor(editorInstance.Name);
}

// set and monitor the lastSessionActiveTime
var lastSessionActiveTime = window.top.getTimeInMinutes();
var sessionActiveTimeReset = false;

// initialise the activeSessionHandler
if (window.top.kbdTimeoutPeriod() != 0)
{
  // W3C DOM
  if (document.addEventListener) 
  {
    kbd_AddEvent (window, 'load', window.top.activeSessionHandler);
    kbd_AddEvent (window, 'mouseup', window.top.resetSessionActiveTimeEvent);
  } 
  // NOTE:  ie 7.0 still doesnt support the DOM correctly.  Since the activeSessionHandler applies 
  // to administrators and kaboodle admin requires W3C compliance we ignore these routines in ie.
}

/*****************************************************/
/* generic default scripts
/*****************************************************/

// proper case string prototype
String.prototype.toProperCase = function() 
{
  return this.toLowerCase().replace(/^(.)|\s(.)/g, 
  function($1) { return $1.toUpperCase(); });
}

// make a string upper camel case
String.prototype.toCamelCase = function() 
{
  var j = 0;

  // strip all html
  var t = unescape(this).replace(/\+/g,' ').replace(/\-/g,' ').replace(/(<([^>]+)>)/ig,' '); 

  // remove unwanted characters
  var s = '';
  for (var i=0; i<t.length; i++) 
  {
    j = t.charCodeAt(i);
    if ((j == 32) || (j >= 48 && j <= 57) || (j >= 65 && j <= 90) || (j >= 97 && j <= 122))  s += String.fromCharCode(j);
  }

  // make words proper case
  t = s.toProperCase();

  // concatenate words
  t = t.replace(/ /gi,'');

  return t;
}

/*****************************************************/
/* ISAPI Rewrite URL 
/*****************************************************/

// NOTE: typically iMenuProfileID is unknown when this function is called as it may not have been set or may not belong to any menu profile
var createISAPIRewriteURL = function(nvTitle,iSitePageID,iMenuProfileID,iPageTypeID,iCustomPage,transactionMode,errNum) {
  var ajaxFramework = (iPageTypeID == 100) ? true : false;
  var title = nvTitle.toCamelCase();
  var pt = (title) ?  title : 'n';
  var en = (errNum) ? errNum : '0';
  if (ajaxFramework) {
    var vsid = (iSitePageID) ?  iSitePageID : 'n';
    var aid = (iMenuProfileID) ?  iMenuProfileID : 'n';
    var fv = (iCustomPage) ?  iCustomPage : 'n';
    var tm = (transactionMode) ?  transactionMode : 'n';
    return "/ktm/" + pt + "/" + aid + "/" + vsid + "/" + fv + "/" + tm + "/"
  } else {
    var pid = (iSitePageID) ?  iSitePageID : 'n';
    var mpid = (iMenuProfileID) ?  iMenuProfileID : 'n';
    var ptid = (iPageTypeID) ?  iPageTypeID : DEFAULT_PAGE_TYPE;
    var cp = (iCustomPage) ?  iCustomPage : SITE_PAGE;
    if (cp == CUSTOM_PAGE) {
      if (ptid == PERSONNEL_PAGE_TYPE) {
        return "/kbv/" + pt + "_" + pid + ".html"
				  } else {
        return "/kcp/" + pt + "/" + pid + "/" + mpid + "/" + cp + "/"
				  }
    } else {
      return "/" + pt + "/" + pid + "/" + mpid + "/" + ptid + "/" + cp + "/" + en + "/"
		  }
  }
}

/*****************************************************/
/* FCKEditor scripts 
/*****************************************************/

var getEditorValue = function(instanceName) 
{  
  var oEditor = FCKeditorAPI.GetInstance( instanceName ) ;
  return oEditor.GetXHTML( true ) ;  // "true" means you want it formatted.
}  

var FCKSetPageCommand = function(instanceName) {
  var api = FCKeditorAPI.GetInstance(instanceName);  
  api.SetHTML('', true ) ;
}

// reverse current editor state
var toggleEditor = function() {
  var bEditorState = (getPublicState(SYSTEM_SCRIPT_EDITOR)=='true') ? false : true; 
  var nvText = (bEditorState) ? 'Script' : 'Rich Text';
//  var bChange = (document.content.iFCKContentChanged.value == 1) ? true : false;
  putPublicState(bEditorState,SYSTEM_SCRIPT_EDITOR,true);
  if (bContentChanged) {
    if (confirm('Abandon this editor and use the ' + nvText + ' Editor instead.\r\n\r\nPress OK to save changes or Cancel to abandon changes...')) {
      isValidData(0);
    } else {
      location.href = window.location.href;  
    }  
  } else {
    location.href = window.location.href;  
  }  
}

/*****************************************************/
/* old old scripts, some even written in the 20th 
/* century, they include numerious updates
/*****************************************************/

var documentImages = new Array()

var preloadImages = function () 
{
  for (var i=0; i < arguments.length; i++) 
  {
    documentImages[i] = new Image();
    documentImages[i].src = arguments[i]
  }
}

var cs_OnMouseover = function(param) {param.style.cursor='pointer'}
var cs_OnMouseup = function(param) {param.style.border='1px outset white'}
var cs_OnMouseout = function(param) {param.style.border='1px outset white'}
var cs_SetCursor = function(type) {document.content.style.cursor=type}
var isUndefined = function(a) {return typeof a=='undefined';} 

var cs_OnMousedown = function(param) {
  cs_OnMouseover(param);
  param.style.border='1px inset white';
}

String.prototype.trim = function() 
{
  return this.replace( /(^\s*)|(\s*$)/g,'');
}

var getLink = function() {
  var nvReturnValue = cs_PopLinkCaptureDialog();
  if (nvReturnValue) {
    document.content.iBrowserOpenMethodID.options[1].selected = true;
    document.content.nvLinkURL.value = nvReturnValue;
  }  
  return true;
}

var getURL = function(param) {
  fileName = 'tp_GetSitePage.asp?q='+param;
  return isTemplate() + fileName;
}

var cs_PopLinkCaptureDialog = function(ob) {
  var bMSIE = (navigator.appName.indexOf("Microsoft") != -1) ? true : false;
  var nvURL = 'tp_LinkCapture.asp?q='+ document.content.nvLinkURL.value; 
  var nvFeatures = null; 
  var nvLinkParams = null;
  if (bMSIE) {
    nvFeatures = 'dialogHeight:480px;dialogWidth:580px;status:no;resizable:yes;status:no;center:yes}'; 
    nvLinkParams = showModalDialog(nvURL,"",nvFeatures); 
    if (nvLinkParams) return nvLinkParams; 
  } else {
    nvFeatures = 'height=480,width=550,status=no,toolbar=no,menubar=no,location=no,scrollbars=no,resizable=yes';
    remote = window.open('','1002',nvFeatures);
    if (remote != null) {
      if (remote.opener == null) {
        remote.opener == self;
      }
      remote.location.href = nvURL;
    }
  }  
  return false
}

var getSitePageID = function(nvLinkProperies) {
  var ar = nvLinkProperies.split('-');
  return ar[1]
}

var isValidLink = function(ob) {
  var nvSubstr;
  var param = ob.value;
  if (!param) {
    alert('Please enter a fully qualified URL for this link...');
    ob.focus();
    return false;
  }
  if ((param.substr(0,11) != "javascript:") && (param.substr(0,7) != "http://")) {
    alert("Please enter a valid link for this page.\r\n\r\nFor example, you may use one of the following methods:\r\n\r\n - a fully qualified URL beginning with 'http://'\r\n - javascript:getSitePage([ID]);\r\n - javascript:getCustomPage([ID]);\r\n - javascript:'[function name]';");
    ob.focus();
    return false;
  }
  return true;
}

var getDateString = function(iType) {
  var d = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
  var m = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
  var today = new Date();
  var day = today.getDate();
  var year = today.getFullYear();
  if (year < 2000) year = year + 1900;
  var end = "th";
  if (day==1 || day==21 || day==31) end="st";
  if (day==2 || day==22) end="nd";
  if (day==3 || day==23) end="rd";
  switch(iType) {
    case "INT" : 
      day+=end;
      return d[today.getDay()]+", "+m[today.getMonth()]+" "+day+" "+year;
    case "US" : 
      return day+" "+m[today.getMonth()]+" "+year;
    default : 
      day+=end;
      return d[today.getDay()]+", "+m[today.getMonth()]+" "+day+" "+year;
  }
}  

var cs_IsMacBrowser = function() {	
  var nvUserAgent = navigator.userAgent.toLowerCase();
  if (nvUserAgent.indexOf("mac") != -1) return true;
  return false;
}  

var cs_BrowserType = function() {	
  var nvType, nvUserAgent = navigator.userAgent.toLowerCase();
  if (nvUserAgent.indexOf("msie") != -1) {
    nvType = "ie";
    if (nvUserAgent.indexOf("mac") != -1) nvType = "iemac";
  } else if (nvUserAgent.indexOf("mozilla") != -1) {
    nvType = "nn";
    if (nvUserAgent.indexOf("gecko") != -1) nvType = "nn6";
    if (nvUserAgent.indexOf("linux") != -1) nvType = "nnlinux";
    if (nvUserAgent.indexOf("mac") != -1) nvType = "nnmac"; 
  } else {
    nvType = "other";
  }
  return nvType;
}  

var getState = function(param,bString) {
  var cs_State = getCookie('cs_State');
  if (cs_State) {
    var ar = cs_State.split(',');
    var result = (bString) ? ar[param] : parseInt(ar[param]);
    return result;
  } else {
    location.href = "/"
  }  
}

var setState = function(value,el) {
  var cs_State = getCookie('cs_State');
  if (cs_State) {
  		var nvState = '';
    var ar = cs_State.split(',');
    for (var i=0; i<ar.length; i++) {
      nvState += (i === el) ? value + ',' : ar[i] + ',';
    } 
    setCookie('cs_State',nvState.substr(0,nvState.length-1));
  } 
}

var getPublicState = function(iPosition) {
  var nvState = getCookie('cs_PublicState');
  if (!isNaN(iPosition)) {
    var i = parseInt(iPosition);
    if (nvState) {
      var ar = nvState.split('|');
      if (ar.length > i) {
      var nvElement = ar[i];
      while (nvElement.indexOf('+') != -1) nvElement = nvElement.replace('+',' ');
      return nvElement;
      } else {
        return 'undefined';
    }
  }
  }
  return nvState
}

var putPublicState = function(nvValue,iPosition,bIgnore) {
  var nvCookie = '';
  var i = 0;  
  if (!isNaN(iPosition)) {
    var k = parseInt(iPosition);
    if ((!bIgnore) && (k <= PUBLIC_STATE_RESERVE)) {
      var iReserve = PUBLIC_STATE_RESERVE + 1;
      alert('Element out of bounds. The Public State cookie will only accept elements starting at position ' + iReserve + '.  Elements between 0 and ' + PUBLIC_STATE_RESERVE + ' are reserved.');
    } else {
      var nvCookie = getCookie('cs_PublicState');
      if (!nvCookie) {
        for (i=0; i<PUBLIC_STATE_LENGTH; i++) {
          nvCookie = nvCookie + "|"
        }
      }
      var nvState = '';
      var ar = nvCookie.split('|');
      var j = ar.length;
      if (k > j) {
        alert('Element out of bounds. You have exceeded the number of elements present in the Public State cookie.');
      } else {
        if (k <= j) ar[k] = nvValue;
        for (i=0; i<j; i++) {
          nvState += ar[i];
          if (i<j-1) nvState += '|';
        }
        setCookie('cs_PublicState',nvState);
      } 
    } 
  } 
}

var associativeClass = function() {
  for (var i=0;i<arguments.length;++i) {
    this[associativeClass.arguments[i]] = new associativeObj()
  }
}
var associativeObj = function() {}

var mnu = function(iMenuProfileID){setCookie('mnu',iMenuProfileID,null,'/');}
var getCookie = function(param) {var c = unescape(document.cookie), i=0; param += "="; while (i < c.length) {var j = i + param.length; if (c.substring(i,j) == param) {var k = c.indexOf(";", j);if (k == -1) k = c.length; return c.substring(j,k);}i = c.indexOf(" ", i) + 1;if (i == 0) break;}return null;}
var setCookie = function(name, value, expires, path, domain, secure){document.cookie = name + "=" + escape(value) + ((expires) ? ";expires=" + expires.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : "");}
  
var dbLocked = function() {
  if (getState(cs_DBLock)) {
    alert('The site is currently undergoing essential website\r\nand database maintenance. Access is restricted.\r\n\r\nPlease logon at a later time...');
    return true;
  }
  return false;
}  

var isSecure = function() {
  var thisParam = (getState(cs_bSecurityEnabled)==1) ? 'https://' : 'http://'
  return thisParam + location.hostname + '/admin/';
}

var isTemplate = function() {return 'http://' + location.hostname + '/templates/';}

var isHelp = function() {return 'http://' + location.hostname + '/help/';}

var getCustomPage = function(iCustomPageID,iMenuProfileID,bCustomPage) {
  if (!iMenuProfileID) iMenuProfileID = 0;
  if (!bCustomPage) bCustomPage = 1;
  fileName = 'tp_GetCustomPage.asp?q1=' + iCustomPageID + '&q2=' + iMenuProfileID + '&q3=' + bCustomPage;
  location.href = isTemplate() + fileName;
}

var getSitePage = function(iSitePageID,iMenuProfileID,bCustomPage) {
  if (!iMenuProfileID) iMenuProfileID = 0;
  if (!bCustomPage) bCustomPage = 0;
  fileName = 'tp_GetSitePage.asp?q1=' + iSitePageID + '&q2=' + iMenuProfileID + '&q3=' + bCustomPage;
  location.href = isTemplate() + fileName;
}

var submitForm = function(param,ignoreLock) {
  if (!ignoreLock) if (dbLocked()) return;  
  document.content.action = param;
  document.content.submit();
}

var cs_PrintThis = function()
{  
  if (window.print) {
    window.print() ;  
  } else {
    var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
    document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
    WebBrowser1.ExecWB(6, 1);//Use a 1 vs. a 2 for a prompting dialog box WebBrowser1.outerHTML = "";  
  }
}

var getSendPrintThis = function(param,nvSubject) {
  var nvMailtoSubject = (nvSubject) ? '?subject=' + nvSubject + '&body=' + escape(window.location.href) : '?body=' + escape(window.location.href);
  var strobj = '<a href="javascript:cs_PrintThis();" onmouseover="self.status=' +"''"+'; return true;" onmouseout="self.status='+"''"+';"><img border="0" height="16" width="16" SRC="/images/cs_Print.gif" alt="Print document icon" title="Print this document" /></a><a href="mailto:' + nvMailtoSubject + '" onmouseover="self.status=' +"''"+'; return true;" onmouseout="self.status='+"''"+';"><img hspace="10" border="0" height="16" width="16" src="/images/cs_Email.gif" alt="Forward this document" title="Send this document" /></a>';
  switch(param) {
    case 100 : strobj = '<a href="javascript:history.go(-1);" onmouseover="self.status=' +"''"+'; return true;" onmouseout="self.status='+"''"+';"><img border="0" height="16" width="16" hspace="10" SRC="/images/cs_MagnifyingGlass.gif" alt="Search icon" title="Search" /></a>' + strobj; break;
    case 12 : strobj = '<a href="javascript:location.href='+"'"+'/templates/tp_AccountSearch.asp?q1=show+all'+"'"+'" onmouseover="self.status=' +"''"+'; return true;" onmouseout="self.status='+"''"+';"><img border="0" height="16" width="16" hspace="10" SRC="/images/cs_MagnifyingGlass.gif" alt="Search icon" title="Search" /></a>' + strobj; break;
  }
  return strobj; 
}

var kbd_Print = function ()
{  
  if (window.print) {
    window.print() ;  
  } else {
    var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
    document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
    WebBrowser1.ExecWB(6, 1);//Use a 1 vs. a 2 for a prompting dialog box WebBrowser1.outerHTML = "";  
  }
}

var kbd_Search = function (str)
{  
  if (str)
  {
    if (str.toLowerCase() != 'search')
    {
      location.href = '/templates/tp_BDRFind.asp?q1=' + str;
    }
  }
}

var getUniqueID = function() {
  var d = new Date();
  return d.getTime()
}

var getHelp = function(param) {
  fileName = isHelp() + param
  location.href = fileName;
}

var popHelp = function(nvURL) {
  var iHeight = 720;
  var iWidth = 620;
  var bScroll = true;
  var bResize = true;
  var nvPopName = 'popHelp';
  popWindow(nvURL,iHeight,iWidth,bScroll,bResize,nvPopName)
}

var popLinkTest = function(nvSelectedIndex) {
  var ar = nvSelectedIndex.split('-');
  var iCustomPage = ar[0];
  var iPageID = ar[1];
  var iHeight = 500;
  var iWidth = 720;
  var bScroll = true;
  var bResize = true;
  var nvPopName = 'popLinkTest';
  var nvURL = '/templates/tp_GetLinkTest.asp?q1=' + iPageID + '&q2=' + iCustomPage;
  popWindow(nvURL,iHeight,iWidth,bScroll,bResize,nvPopName)
}

var popWindow = function(nvURL,iHeight,iWidth,bScroll,bResize,nvPopName,bChrome,bModal) 
{
  if (!iHeight) iHeight = 600;
  if (!iWidth) iWidth = 500;
  var nvWindowName = (nvPopName) ? nvPopName : getUniqueID();
  var nvScroll = (bScroll) ? 'yes' : 'no';
  var nvResize = (bResize) ? 'yes' : 'no';
  var nvState = (bChrome) ? 'yes' : 'no';
  var nvModal = (bModal) ? 'yes' : 'no'; 
  remote = window.open('',nvWindowName,'titlebar='+nvState+',height='+iHeight+',width='+iWidth+',status='+nvState+',toolbar='+nvState+',menubar='+nvState+',location='+nvState+',scrollbars='+nvScroll+',resizable='+nvResize+',modal='+nvModal+',dependent='+nvModal);
  if (remote != null) 
  {
    if (remote.opener == null) remote.opener == self;
    remote.location.href = nvURL;
  }  
}

// emulate radio button hehaviour with a checkbox set
var radioCheckbox = function (groupName, obj) 
{
  if (document.getElementById(obj.id).checked)
  {
    var el = document.getElementsByTagName("input"); 
    for (var i = 0; i < el.length; i++) 
    { 
      if (el[i].id.indexOf(groupName) != -1)
      {
        if (el[i].id != obj.id) document.getElementById(el[i].id).checked = false;
      }
    }
  }    
}

// Collect all properties associated with the HTML DOM Navigator Object 
var cs_ClientDOM = function() {	
  var nvText = '';
  var x = navigator;
  var re = new RegExp(';','g');
  nvText += x.appCodeName + '|';
  nvText += x.appMinorVersion + '|';
  nvText += x.appName + '|';
  nvText += x.appVersion + '|';
  nvText += x.cookieEnabled + '|';
  nvText += x.cpuClass + '|';
  nvText += x.onLine + '|';
  nvText += x.platform + '|';
  nvText += x.userAgent + '|';
  nvText += x.browserLanguage + '|';
  nvText += x.systemLanguage + '|';
  nvText += x.userLanguage + '|';
  nvText += screen.width + "x" + screen.height;
  return nvText.replace(re,",");
}

var getKaboodleHeader = function() 
{
  var nvTooltip = (document.all) ? 'Inzen - Powered by Kaboodle\&\#13End your session and logout' : 'End your session and logout';
  var nvLogOutSymbol = '</td><td bgcolor="#f6f5f0"><a href="/admin/tp_LogOutForm.asp" onmouseover="self.status=\'\'; return true;"><img border="0" style="margin-right:12px" align="right" height="40" width="40" src="/images/cs_InzenLoggedUserLogo.gif" alt="Image announcing a user is currently logged in, click to log out" title="' + nvTooltip + '" /></a>';
  var nvScript = '<table border="0" cellspacing="0" cellpadding="0" width="100%" border="0"><tr><td style="background-position: 10px 25px; font-weight: 900; background-image: url(/images/cs_KaboodleHeaderLogo.gif); color: #b5bbae; background-repeat: no-repeat; background-color: #f6f5f0" valign="top" nowrap height="46"><a onmouseover="self.status =\'Home Page\';return true;" style="padding-right: 340px" onmouseout="self.status=\'\';" href="/" target="_top"><img title="Return to the home page" height="46" alt="Click to return to the home page" src="/images/cs_tm.gif" width="216" border="0" /></a>';
  nvScript += getDateString(getState(cs_DateDefault,1));
  nvScript += nvLogOutSymbol + '</td></tr><tr><td valign="top" bgcolor="#000000" colspan="2"><img height="1" src="/images/cs_tm.gif" width="1" border="0" /></td></tr></table>';
  return nvScript;
}  

var kaboodleVersion = function() 
{
  var kbdVersion = 'v0.911b';
  var el = document.getElementsByTagName("meta");
  for (var i=0; i<el.length; i++) 
  {
    if (el.item(i).name == 'cms-version') return el.item(i).content;
  }
  return kbdVersion;
}

var getKaboodleFooter = function() 
{
  var kbd_Version = kaboodleVersion();
  var curdate = new Date()
  var curyear = curdate.getFullYear()
  var nvScript = '<table style="border-top:1px solid #8f867c" border="0" cellspacing="0" cellpadding="0" width="100%">';
      nvScript +=  '<tr>';
      nvScript +=    '<td style="border-top:1px solid #ffffff; background-color:#c1c1c1; font-weight:bold; padding-top:1px">';
      if (accountActiveState()) {
        nvScript +=     '<a title="End your session and logout" alt="Click to end your session and logout" style="color:#ffffff;margin-left:15px" onmouseover="self.status=\'\';return true;" href="/logout">Log Out</a>';
      } else {
        nvScript +=       '<a onmouseover="self.status=\'\'; return true;" style="color:#ffffff;margin-left:15px" href="/terms">Terms Of Use</a>';
        nvScript +=       '<a onmouseover="self.status=\'\'; return true;" style="color:#ffffff;margin-left:15px" href="/privacy">Privacy</a>';
      }
      nvScript +=    '</td>';
      nvScript +=    '<td style="border-top:1px solid #ffffff; background-color:#c1c1c1;padding-top:1px">';
      nvScript +=      '<a onmouseover="self.status=\'\';return true;" href="#top">';
      nvScript +=        '<img align="right" height="15" hspace="15" src="/images/cs_KaboodleDefaultReturnToTop.jpg" width="126" border="0" />';
      nvScript +=      '</a>';
      nvScript +=    '</td>';
      nvScript +=  '</tr>';
      nvScript +=  '<tr>';
      nvScript +=    '<td style="border-top:1px solid #000000" colspan="2">';
      nvScript +=      '<table style="margin-top:6px; margin-bottom:6px; margin-right:18px; color:#c1c1c1;font-weight:900;font-size:8pt" border="0" cellspacing="0" cellpadding="0" width="100%">';
      nvScript +=        '<tr>';
      nvScript +=          '<td style="padding-left:15px">&copy; 2004-' + curyear + ' Inzen Pty Ltd</td>';
      nvScript +=          '<td style="padding-left:25px">Support +61 2 9034 6000</td>';
      nvScript +=          '<td style="padding-right:15px;text-align:right;font-weight:600;color:#c1c1c1">';
      nvScript +=            '<a onmouseover="self.status=\'\'; return true;" target="_blank" title="Inzen - the home of Kaboodle (' + kbd_Version + ')" alt="Link to Inzen - the home of Kaboodle" href="http://www.inzen.com.au/"><img border="0" height="13" width="14" src="/images/kb_KaboodleKay.gif" /></a>';
      nvScript +=          '</td>';
      nvScript +=        '</tr>';
      nvScript +=      '</table>';
      nvScript +=    '</td>';
      nvScript +=  '</tr>';
      nvScript +='</table>';

  return nvScript;
}

var babelFish = function(olg,tlg) {
  babelFishURL = 'http://babelfish.altavista.com/babelfish/urlload?url=';
  kaboodleURL = escape(document.location.href);
  language = '&lp='+olg+'_'+tlg+'&tt=url';
  location.href = babelFishURL + kaboodleURL + language;
}

// reference the Ajax framework

var BINARY = 0
var MARKUP = 1
var FTPROOT = 2
var FTPROOT = 2
var OPEN_DOCUMENT = 25
var EMAIL_CGI = 26
var RAISE_ERROR = 99

var popBDRFile = function (iVersionSetID) 
{
  var id = (iVersionSetID) ? iVersionSetID : null;
  var action = '/templates/ajaxFramework_f.asp?aid='+OPEN_DOCUMENT+'&vsid='+id+'&fv='+BINARY;
  ajaxAction(action);
}

var popFDRFile = function (iVersionSetID) 
{
  var id = (iVersionSetID) ? iVersionSetID : null;
  var action = '/templates/ajaxFramework_f.asp?aid='+OPEN_DOCUMENT+'&vsid='+id+'&fv='+FTPROOT;
  ajaxAction(action);
}

var eCGI = function (et,ef,es,eb,eh) 
{
  var action = '/templates/ajaxFramework_f.asp?aid='+EMAIL_CGI+'&et='+et+'&ef='+ef+'&es='+es+'&eb='+eb+'&eh='+eh;
  ajaxAction(action);
}

var ajaxAction = function(action) 
{
  var ajax = document.getElementById('ajax').contentWindow;
  ajax.document.ajax.action = action;
  ajax.document.ajax.submit();
}

var raiseError = function (iVersionSetID) 
{
  var id = (iVersionSetID) ? iVersionSetID : null;
  var action = '/templates/ajaxFramework_f.asp?aid='+RAISE_ERROR+'&vsid='+id;
  ajaxAction(action);
}

// populate cart

// Matches all positive & negative integer numbers, to any magnitude.
var isInteger = function(i) 
{
  var re = /^-?[0-9]+[0-9]*$/
  if (re.test(i)) return true;
  return false;
}                      

var onCheckout = function() 
{
  cartProductOrder();
}	

var cartHandler = function(vid,gid,pid,pn,pq) 
{
  var cookie = getCookie('kbd_CartState');
  var uniqueID = null;
  this.cartCookie = (cookie) ? cookie : '';
  if (this.cartCookie)
  {
    var ar1 = this.cartCookie.split('__');
    var ar2 = ar1[0].split(',');
    if (ar2.length > 4) uniqueID = ar2[4];
  }
  this.iVersion_PKID = vid;
  this.iGalleryID = gid;
  this.iPageID = pid;
  this.iQuantity = (pq) ? pq : 1;
  this.iTrackingID = (uniqueID) ? uniqueID : getUniqueID();
  this.iOrderID = 'undefined';
  this.nvShippingID = 'undefined';
  this.mShipping = 'undefined';
  this.nvShippingDefinition = 'orderonly';
  this.nvProductName = pn;
  this.setCartCookie();
}		

cartHandler.prototype.setCartCookie = function() 
{

  var cookieString = '';
  if (this.cartCookie.indexOf(this.iVersion_PKID) == -1) 
  {
    if (this.cartCookie.length > 0) this.cartCookie += '__';
    this.cartCookie += this.iVersion_PKID + ',';
    this.cartCookie += this.iGalleryID + ',';
    this.cartCookie += this.iPageID + ',';
    this.cartCookie += this.iQuantity + ',';
    this.cartCookie += this.iTrackingID + ',';
    this.cartCookie += this.iOrderID + ',';
    this.cartCookie += this.nvShippingID + ',';
    this.cartCookie += this.mShipping + ',';
    this.cartCookie += this.nvShippingDefinition + ',';
    this.cartCookie += this.nvProductName;
    var ar = this.cartCookie.split('__');
    for (el in ar) 
    {
      cookieString += ar[el] + '__';
    }
  } else {
    var crumbs = '';
    var iQuantity = (document.getElementById('kbd_AddToCartQuantity')) ? isInteger(document.getElementById('kbd_AddToCartQuantity').value) ? parseInt(document.getElementById('kbd_AddToCartQuantity').value) : 1 : 1;
    var ar1 = this.cartCookie.split('__');
    var ar2 = new Array();
    for (var el in ar1) 
    {
      ar2 = ar1[el].split(',');
      if (ar2[0] == this.iVersion_PKID)
      {
        if ((parseInt(ar2[3]) + iQuantity) > 0)
        {
          crumbs += ar2[0] + ',';
          crumbs += ar2[1] + ',';
          crumbs += ar2[2] + ',';
          crumbs += parseInt(ar2[3]) + iQuantity + ',';
          crumbs += ar2[4] + ',';
          crumbs += ar2[5] + ',';
          crumbs += ar2[6] + ',';
          crumbs += ar2[7] + ',';
          crumbs += ar2[8] + ',';
          crumbs += ar2[9];
          cookieString += crumbs + '__';
        }
      } else {
        if (parseInt(ar2[3]) > 0) cookieString += ar1[el] + '__';
      }
    }		
  }			
  var finalCookie = (cookieString.length > 0) ? cookieString.substring(0,cookieString.length-2) : this.cartCookie;
  if (finalCookie) setCookie('kbd_CartState',finalCookie,null,'/');
}

var buildCheckout = function() 
{
  var kbd_CartState = getCookie('kbd_CartState');
  var cartCookie = (kbd_CartState === 'undefined') ? '' : kbd_CartState;
  if (cartCookie)
  {
    if (document.getElementById('kbd_Cart'))
    {
      document.getElementById('cartContent').innerHTML = cartContent();
      document.getElementById('kbd_Cart').style.display = 'block';
    }
  } else {
    if (document.getElementById('kbd_Cart')) document.getElementById('kbd_Cart').style.display = 'none';
  }
}

var cartContent = function() 
{
  var kbd_CartState = getCookie('kbd_CartState');
  var cartCookie = (kbd_CartState === 'undefined') ? '' : kbd_CartState;
  if (cartCookie)
  {
    var iVersion_PKID = null;
    var iGalleryID = null;
    var iPageID = null;
    var nvCartContent = '';
    var iQuantity = 0;
    var nvProductName = null;
    var ar1 = cartCookie.split('__');
    var ar2 = new Array();
    for (var el in ar1) 
    {
      ar2 = ar1[el].split(',');
      iVersion_PKID = ar2[0];
      iGalleryID = ar2[1];
      iPageID = ar2[2];
      iQuantity = ar2[3];
      nvProductName = ar2[9];
      if (parseInt(iQuantity) > 0) nvCartContent += '<a class="kbd_cartProductLink" onclick="this.blur();" href="http://' + location.hostname + '/kpv/ProductView/' + iVersion_PKID + '/' + iGalleryID + '/' + iPageID + '/">' + nvProductName + '<br /><span>Quantity: ' + iQuantity + '</span></a><br /><br />';
    }		
  }		
  return nvCartContent.substring(0, nvCartContent.length - 12);
}

var cartProductOrder = function() 
{
  location.href = 'http://' + location.host  + '/kpo/order/';
}

var cartSalesProductOrder = function() 
{
  location.href = 'http://' + location.host  + '/kps/sale/';
}

var cartCheckout = function() 
{
  location.href = 'http://' + location.host  + '/kpc/checkout/';
}

var initialiseCart = function()
{
  var kbd_CartState = getCookie('kbd_CartState');
  var cartCookie = (kbd_CartState === 'undefined') ? '' : kbd_CartState;
  if (cartCookie.length > 0) 
  { 
    cartCookie = '';
    setCookie('kbd_CartState',cartCookie,null,'/');
  }		
}

// populate cart address

var cartAddressHandler = function(on,oe,op,of,sdn,a1,a2,c,s,pc,cid,de,dp,df,di) 
{
  this.nvOrderByName = (on) ? on : '';
  this.nvOrderEmail = (oe) ? oe : '';
  this.nvOrderPhone = (op) ? op : '';
  this.nvOrderFax = (of) ? of : '';
  this.nvSaleDeliveryName = (sdn) ? sdn : '';
  this.nvAddress1 = (a1) ? a1 : '';
  this.nvAddress2 = (a2) ? a2 : '';
  this.nvCity = (c) ? c : '';
  this.nvState = (s) ? s : '';
  this.nvPostCode = (pc) ? pc : '';
  this.cCountry = (cid) ? cid : '';
  this.nvDeliverEmail = (de) ? de : '';
  this.nvDeliverPhone = (dp) ? dp : '';
  this.nvDeliverFax = (df) ? df : '';
  this.nvInstructions = (di) ? di : '';
  this.cartAddressCookie = '';
  this.setCartAddressCookie();
}		

cartAddressHandler.prototype.setCartAddressCookie = function() 
{
  if (this.cartAddressCookie.length > 0) this.cartAddressCookie += '__';
  this.cartAddressCookie += this.nvOrderByName + ',';
  this.cartAddressCookie += this.nvOrderEmail + ',';
  this.cartAddressCookie += this.nvOrderPhone + ',';
  this.cartAddressCookie += this.nvOrderFax + ',';
  this.cartAddressCookie += this.nvSaleDeliveryName + ',';
  this.cartAddressCookie += this.nvAddress1 + ',';
  this.cartAddressCookie += this.nvAddress2 + ',';
  this.cartAddressCookie += this.nvCity + ',';
  this.cartAddressCookie += this.nvState + ',';
  this.cartAddressCookie += this.nvPostCode + ',';
  this.cartAddressCookie += this.cCountry + ',';
  this.cartAddressCookie += this.nvDeliverEmail + ',';
  this.cartAddressCookie += this.nvDeliverPhone + ',';
  this.cartAddressCookie += this.nvDeliverFax + ',';
  this.cartAddressCookie += this.nvInstructions + ',';
  this.cartAddressCookie += 'undefined';
  var ar = this.cartAddressCookie.split('__');
  var cookieString = '';
  for (el in ar) 
  {
    cookieString += ar[el] + '__';
  }
  var finalCookie = (cookieString.length > 0) ? cookieString.substring(0,cookieString.length-2) : cookie;
  if (finalCookie) setCookie('kbd_CartAddressState',escape(finalCookie),null,'/');
}

/*  complete junk used by the Dundas file upload component in the importsrcipts folder */

var cs_ImportDialog = function(iURL,param) {
  var iHeight = 480;
  var iWidth = 520;
  var nvURL = null;
  switch (iURL) {
    case 1: n = nvURL = '/admin/importscripts/tp_CRMImportSource.asp'; break;
    case 2: n = nvURL = '/admin/importscripts/tp_CRMImportFormat.asp'; break;
    case 3: n = nvURL = '/admin/importscripts/tp_CRMImport.asp'; break;
    case 4: n = nvURL = '/admin/importscripts/tp_CRMImportSplash.asp'; break;
    case 5: n = nvURL = '/admin/importscripts/tp_ImportSource.asp'; break;
    case 6: n = nvURL = '/admin/importscripts/tp_ImportFormat.asp'; break;
    case 7: n = nvURL = '/admin/importscripts/tp_Import.asp'; break;
    default: n = nvURL = '/admin/importscripts/tp_ImportSplash.asp';
  }
  popWindow(nvURL,iHeight,iWidth,0,0,'Import')
}

