var isIE, isFF, isOP, cmsTop, cmsFrame, cmsLeft, clone, isDebug;
var xmlHttp, aPanelTab, EMPTY, curTab, curKey, curAction, curLineNum, aUAC, clipKey, clipId;
var ID, WINVALUE, DELI, LF, P;
var login, iUid, dExpired, bIsStatus, sFirstName, sLastName, sEmail;
var h, cH, idS, keyS;

var TOKEN_ADMIN, TOKEN_UPLOAD;


h              = {};
cH             = {};

xmlHttp        = null
EMPTY          = "";

cmsTop         = getParentDOM("cmsTop");
cmsFrame       = getParentDOM("cmsFrame");
cmsLeft        = getParentDOM("cmsLeft");
clone          = getDOM("clone");

curTab         = -1;
curKey         = EMPTY;
curAction      = EMPTY;
clipKey        = EMPTY;
clipId         = EMPTY;

login          = EMPTY;
iUid           = EMPTY;
dExpired       = EMPTY;
bIsStatus      = 5;
sFirstName     = EMPTY;
sLastName      = EMPTY;
sEmail         = EMPTY;
curId          = EMPTY;
curLineNum     = -1;

TOKEN_ADMIN    = "000100";
TOKEN_UPLOAD   = "000100-000100";
ID             = "id.";
AMP            = "&";
DOT            = ".";
COMMA          = ",";
SP             = " ";
DELI           = "||";
LF             = "\r\n";
BR             = "<br>";
ERR            = "<p>ERROR<p>";


tagC           = '_C';
tagG           = '_G';
imgOpen        = 'img/open.ico';
imgClose       = 'img/close.ico';
moveImg        = " <img src='img/move.gif' width=12 height=12 style='vertical-align:bottom'> ";

URL            = "CMS.aspx?q=";
CHECKEDICO     = "img/checked.ico";
PERSONICO      = "<img src='img/person.ico' width=16 height=16> ";
WINVALUE       = "top=100, left=100, height=500px, width=800px, status=no, menubar=no, resizable=yes, toolbar=no, location=no, directories=no";

isIE           = false;
isFF           = false;
isOP           = false;

initMain();

function initMain() {

   if(document.all  && document.getElementById && !window.opera) isIE = true;
   if(!document.all && document.getElementById && !window.opera) isFF = true;
   if(document.all  && document.getElementById && window.opera)  isOP = true;

   isDebug        = AJAX(URL + "getDebug" + getRan()) == "T";

}

function getXmlHttpObject() {

   try {                                          // Firefox, Opera 8.0+, Safari
      xmlHttp = new XMLHttpRequest();
   } catch (e) {                                            // Internet Explorer
      try {
         xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
   }
   return xmlHttp;
}

function AJAX(aUrl) {

   if (document.body != null) document.body.style.cursor = 'wait';
   xmlHttp = getXmlHttpObject();
   if (xmlHttp == null) { alert ("Error:AJAX");  return;  }
   var t = EMPTY;

   xmlHttp.open("GET", aUrl, isFF);
   xmlHttp.onreadystatechange = function showRPT() {
     if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
        t = xmlHttp.responseText;
   }
   //xmlHttp.open("GET", aUrl, false);
   xmlHttp.send(null);
   if (document.body != null) document.body.style.cursor = 'default';


   return t;
}

function doSubmit(submitStr, actionName) {

   var aWin, r, aUrl, ret;

   aWin = window.open('blank.htm','aWin',WINVALUE);
   aWin.document.write(submitStr);

   r    = Math.random();
   aUrl = URL + "setStatus&r=" + r + "&rr=" + Math.random();
   ret  = AJAX(aUrl);

   aUrl = URL + actionName + AMP + "r=" + r;

   aWin.document.cmsForm.action = aUrl;
   aWin.document.cmsForm.submit();

   for (var i = 0; i < 5; i++) {
      sleep(1);
      aUrl = URL + "getStatus&r=" + r + "&rr=" + Math.random();;
      ret = AJAX(aUrl);
      //alert("i=" + i + " ret=" + ret);
      if (ret == "Done") break;
   }
   aWin.close();

}
function sleep() { }

sleep.prototype.setTimer = function(sec) {
   var sleep = this;
   function timerRelay() { sleep.handleTimer(sec); }
   setTimeout(timerRelay, sec*1000);
}
sleep.prototype.handleTimer = function(sec) {
   //getDOM("ret").innerHTML =ajaxValue;
}


function checkCode(ext, place) {

   var a, b, c;
   b = getDOM("inp");
   c = getDOM(place);
   a = AJAX("http://www.cpco.on.ca/report/VerificationCode.aspx?q=" + b.value + "&ext=" + ext);
   if (a == "NOK") c.innerHTML += "<span style='color:red;'><b>Error </b></span>";
   else {
      getDOM("mail" + ext).innerHTML = a;
      c.innerHTML = EMPTY;
   }
}


function showVCode(ext) {

   var b, place;

   place = "mail" + ext + "Div";
   b     = getDOM(place);

   if (b.innerHTML == EMPTY) {

      b.innerHTML =
      "<p><b>Please enter the verification code. (Not Case Sensitive)</b><br>" +
      "<img src='http://www.cpco.on.ca/report/VerificationCode.aspx?q=CR" + getRan() + "'>&nbsp;&nbsp;&nbsp;" +
      "<input id='inp' type=text size=8 style='font-size:120%' onKeyDown='if(event.keyCode==13) checkCode(\"" + ext + "\",\"" + place + "\")'>&nbsp;&nbsp;&nbsp;" +
      "<span id='subId' onclick='checkCode(\"" + ext + "\",\"" + place + "\")' style='color:blue; text-align:center;width:50px;' onMouseOver=\"style.cursor='hand'; style.color='red'\" onMouseOut=\"style.cursor='default'; style.color='blue'\"> <u>Submit</u> </span>";
      getDOM("inp").focus();

   } else b.innerHTML = EMPTY;

}

function doSetLineBkg(aLineNum) {

   var b;
   b = getDOM("idTR." + curLineNum);

   if(aLineNum == null || aLineNum == 'undefined') return;
   var selectedBkg = "#F9966B";

   if (curLineNum == aLineNum) { b.style.background = selectedBkg; return; }

   if (curLineNum != -1) b.style.background = (curLineNum % 2 == 1 ? "#DDDDFF" : "white");

   curLineNum = aLineNum;
   b = getDOM("idTR." + curLineNum);
   if (b != null) b.style.background = selectedBkg;

}

function addCSS(aUid, aName, isCashOff) {

   var a, b, aId;
   a   = document.getElementsByTagName('head');
   aId = "'" + ID + aName + "'";

   if (a[0]){

      b      = getDOM(aId);
      if (b != null) b.parentNode.removeChild(b);
      b      = a[0].appendChild(document.createElement('link'));
      b.id   = aId;
      b.rel  = "stylesheet";
      b.href = "/css/" + aUid + "_" + aName + ".css" + (isCashOff ? "?" + getRan() : EMPTY);
      b.type = "text/css";

   }
}




function saveTreeStatus(aTab, isBoth) {

   var i, a, aId, list, here;

   here = "cmsCommon.js saveTreeStatus(aTab=" + aTab + ", isBoth=" + isBoth + ")=";

   list = EMPTY;
   if (idS == null) return here + "EMPTY";

   for (i = 0; i < idS.length - 1; i++) {

      aId = keyS[i] + DOT + idS[i];
      a   = getDOM("id" + aId + "_C");

      if (a!= null) {
         if (a.style.display != "none") list += aId + COMMA;
      }

   }
   if (list != EMPTY)  {
      if (isEnabledCookie()) setCookie("cms2M_TreeStatus" + aTab, list);
      if (isBoth) AJAX(URL + "saveTreeStatus&tab=" + aTab + "&list=" + list + getRan());
   }

   return here + list;

}




function goToPage(aTab, aId) {

   if (iTree == null || iTree == "undefined") return;

   if (aTab != curTab) { iTree.clickedTab(aTab); return; }

   var ndx, p, aKey, an;

   ndx = aId.indexOf("#");

   if (ndx >= 0) { an = aId.substring(ndx); aId = aId.substring(0, ndx);}

   a = getDOM(aId);
   if (a == null) return;
   p = a.parentNode;

   while (p != null && p != "undefined") {

      if (p.id) {
         if (p.id.indexOf("id") == 0) {
            if (p.style.display == "none") p.style.display = "block";
         }

      }
      p = p.parentNode;
   }
   if (a != null) iTree.clickedTreeNode(a, an);

}

function showPage(aUrl, aClass, aBanner, aTarget) {

   var ndx, t, tS;
   window.open(aUrl, aTarget == null ? "cmsFrame" : aTarget);
   t            = window.top.cmsTop.document.location.href;
   ndx          = t.indexOf("?"); if (ndx < 0) return;
   t            = t.substring(ndx + 1);
   tS = t.split(",");
   if (tS.length > 1) window.top.cmsTop.document.location.href = "cmsTop.htm?" + tS[0] + "," + tS[1] + "," + aBanner;
}


function clickedCalendar(a)  {

   var aObj, ret;
   aObj       = new Object();
   aObj.close = true;
   aObj.title = "Exipry Date";
   aObj.value = a.innerHTML;

   ret = window.showModalDialog("Calendar.htm", aObj, "dialogWidth:160px; dialogHeight:200px;");
   if (ret == 'undefined' || ret == null) return;
   a.innerHTML = ret;

}

function setUAC(aUac)    {

   var aUacS = aUac.split(DELI);
   if (aUacS.length > 10) {
      iUid           = aUacS[2];
      bIsStatus      = 5;
      sFirstName     = aUacS[4];
      sLastName      = aUacS[5];
      sEmail         = aUacS[11];
   } else {
      iUid           = aUacS[0];
      dExpired       = aUacS[1];
      bIsStatus      = parseInt(aUacS[2]);
      sFirstName     = aUacS[3];
      sLastName      = aUacS[4];
      sEmail         = aUacS[5];
   }

}



function clickedTreeImg(a, isToggle) {

   //checkReindex();
   var aId, b, g ;

   aId = getIdFromImg(a.id);
   b   = getDOM(aId + tagC);
   g   = getDOM(aId + tagG);

   if (b.style.display == 'none') {                               b.style.display = 'block'; g.src = imgOpen; }
   else                           { if (isToggle != null) return; b.style.display = 'none';  g.src = imgClose; }

}

function isEnabledCookie() {

   var cookieEnabled = navigator.cookieEnabled;

   if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
      document.cookie = "testCookie";
      cookieEnabled   = document.cookie.indexOf("testCookie") < 0;
   }
   return cookieEnabled;
}

function setCookie(name, v)   {

   var locPath, path, expDate, expires, c, cS, len, i, t, ndx;
   locPath = location.pathname;
   path    = locPath.substring(0,locPath.lastIndexOf('/')) + '/';
   expDate = new Date();
   expDate.setTime(expDate.getTime() + (1 * 365 * 24 * 3600 * 1000));
   expires = expDate.toGMTString();
   c       = name + "=" + escape(v) + "; expires=" + expires + "; path=" + path;
   cS      = c.split("; ");
   len     = cS.length;
   cH.length = len;
   for (i = 0; i < len; i++) {
      t = cS[i];
      ndx = t.indexOf("=");
      if (ndx > 0) cH[t.substring(0, ndx)] = t.substring(ndx + 1);
   }
   document.cookie = c;
}

function reloadTree()         { saveTreeStatus(curTab); window.open("cms2M.aspx?" + curTab + "," + curAction + "," + curKey + "," + getRan(), "cmsLeft"); }
function getCookie(name)      { return cH[name] == null || cH[name] == "undefined" ? EMPTY : unescape(cH[name]); }
function getMonthNum(a)       { var MONTHS = {"":"00", "Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", "Jun":"06", "Jul":"07", "Aug":"08", "Sep":"09", "Oct":"10", "Nov":"11", "Dec":"12"}; return MONTHS[a];}
function doSave()             { editor.doSave(); }
function cvtSql(a)            { return a.indexOf("'") >= 0 ? a.replace(new RegExp("'", "g"), "''") : a;}
function getRan()             { return "&r=" + Math.random(); }
function getDOM(a)            { return document.getElementById(a); }
function getParentDOM(a)      { return parent.document.getElementById(a); }

function trim(s)              { return (s ? '' + s : '').replace(/^\s*|\s*$/g, ''); }
function lTrim(str)           { var re = /^\s */; return str.replace(re, ''); }
function rTrim(str)           { var re = /\s *$/; return str.replace(re, ''); }

function mv(a)                { a.style.cursor='hand';     }
function mt(a)                { a.style.cursor='default';  }

function copyClip(str)        { holdArea.value = str; holdArea.createTextRange().execCommand("Copy");}
function checkReindex()       { var aReindex = AJAX(URL + "isReindexed&tab=" + curTab + getRan()); if (aReindex == "Y") reloadTree(); }
function getIdFromImg(aId)    { return aId.lastIndexOf('_') < 0 ? aId : aId.substring(0, aId.lastIndexOf('_')); }

function getStrTypeDate(a)    { var MONTHS = new Array ("", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); var calS = a.split("/"); return MONTHS[parseInt(calS[0])] + DOT + (calS[1].length < 2 ? "0" : "") + calS[1] + DOT + calS[2]; }
function getNumTypeDate(a)    { var calS = a.split(DOT); return getMonthNum(calS[0]) + "/" + calS[1] + "/" + calS[2]; }
function getIntTypeDate(a)    { var calS = a.split("/"); return parseInt(calS[2]) * 10000 + parseInt(calS[0]) * 100 + parseInt(calS[1]); }

function addDebug(a, b, c, d) { if (isDebug || a) AJAX(URL + "addDebug&src=" + b +"&method=" + c + "&msg=" + d + getRan()); }
function dump(a)              { var aWin = window.open('blank.htm','aDump',WINVALUE); aWin.document.write( "<p>" + a + "<p>" + "<textarea id='dumpArea' name='dumpArea' style='font-size:12px;    font-family:courier-new;width:1000px; height:400px;'>" + a + "</textarea>" ); }

