//Author: Christopher J. Andrews 2002, All copyleft rights reserved.

//Debug tool

var pageOutput = "";
/** Debugging tool that writes given text to the screen. */
function myDocWrite(text, indent){
    pageOutput += text;
    if (indent != null){
        for (ind = 0; ind < indent; ind++){
            text = '&nbsp;' + text;
        }
    }
    document.write(text + '<br>');
}

//CONSTANTS
var TAB = "&#x0009;";
var SPACE = "&nbsp;";
var AMPERSAND = "&amp;";

/**
    Browser detection routine

    Browser
        .version() <-- returns the code of the browser that is currently in use
            this will be 'ns6', 'ns', 'ms5', 'ms4', or 'too old'
*/

var theBrowser = new Browser();
theBrowser.version();

function Browser(){
    this.type = "";
    this.N6 = "N6";
    this.MS5 = "MS5";
    this.MS4 = "MS4";
    this.NS = "NS";
    this.OTHER = "OTHER";
    this.version = version;
    this.testCookies = testCookies;
    this.getBrowserSize = getBrowserSize;
}

function version() {
    if (this.type == ""){
        var agentInfo = window.navigator.userAgent;
        //DEBUG
        //alert(agentInfo);
        //DEBUG
        if ((agentInfo.indexOf("Netscape6") > -1) ||
            (agentInfo.indexOf("Netscape/7") > -1)){
            this.type = this.N6;
        } else if ((agentInfo.indexOf("MSIE 5.5") > -1) ||
            (agentInfo.indexOf("MSIE 6.0") > -1) ||
            (agentInfo.indexOf("MSIE 7.0") > -1)){
            this.type = this.MS5;
        } else if (agentInfo.indexOf("Opera/9") > -1){
            this.type = this.MS5;
        } else if (agentInfo.indexOf("Firefox") > -1){
            this.type = this.MS5;
        } else if ((window.navigator.appName.indexOf("Microsoft")==0) &
                (window.navigator.appVersion.substring(0,1)>="4")) {
            this.type = this.MS4;
        } else if ((window.navigator.appName.indexOf("Netscape")==0)
                & (window.navigator.appVersion.substring(0,1)>="4")){
            this.type = this.NS;
        } else {
            alert("Your browser type is too old or not recognized.\r\n" +
                "Some of the scripts on this page may not work.\r\n" +
                agentInfo);
            this.type = this.OTHER;
        }
        //DEBUG
        //alert(this.type);
        //DEBUG
    }
    return this.type;
}

function testCookies(showMessage){
    // Check whether cookies enabled
    document.cookie = "Enabled=true";
    var cookieValid = document.cookie;
    // if retrieving the VALUE we just set actually works
    // then we know cookies enabled
    if (cookieValid.indexOf("Enabled=true") != -1){
        cookiesEnabled = true;
    } else {
        cookiesEnabled = false;
    }

    if(showMessage && !cookiesEnabled){
        alert(
            'For the protection of your data, this site requires\n' +
            'the use of browser cookies, but we have detected that\n' +
            'cookies are not enabled.  Please verify that cookies\n' +
            'are enabled in your browser and try again.\n\n' +
            'We do not use cookies to track any personal or internet\n' +
            'address information.\n\n' +
            'Thank you.');
    }
    return cookiesEnabled;
}

/** Returns an array of the (width, height) of the browser window. */
function getBrowserSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return new Array(myWidth, myHeight);
}

function getCookie(c_name) {
    var c_start;
    var c_end;
    //alert('dc ' + document.cookie);
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";",c_start)
            if (c_end == -1){
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start,c_end));
        }
    }
    return null;
}

function setCookie(c_name,value,expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie = c_name + "=" + escape(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate);
}

// print the web browser page
function printpage(){
    window.print();
    return 0;
}

String.prototype.trim = function() {
    return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"");
}

String.prototype.fulltrim = function() {
    return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,"").replace(/\s+/g," ");
}



/*
    ArrayList
        .length
        .capacity
        .allowDuplicateKeys <-- note get()
            will only get the first duplicate if true
        .add()
        .getByKey()
        .getItemByIndex() -- zero-based
        .getKeyByIndex() -- zero-based

    Constructor function
        newArrayList(allowDupKeys)
*/

function ArrayList(){
    this.length = 0;
    this.capacity = 10;
    this.allowDuplicateKeys = false;
    this.keys = new Array(10);
    this.items = new Array(10);
}

function newArrayList(allowDupKeys){
    var arrayList = new ArrayList();
    this.allowDuplicateKeys = allowDupKeys;
    arrayList.add = add;
    arrayList.getByKey = getByKey;
    arrayList.get = getItemByIndex;
    // TODO: refactor this out
    arrayList.getItemByIndex = getItemByIndex;
    arrayList.getKeyByIndex = getKeyByIndex;
    arrayList.removeByKey = removeByKey;
    arrayList.removeByIndex = removeByIndex;
    return arrayList;
}

function add(key, item){
    var index = -1;

    if ((key != null) && !this.allowDuplicateKeys){
        for (i = 0; i < this.length; i++){
            if (key == this.keys[i]){
                index = i;
            }
        }
    }

    if (index == -1){
        if (this.length == this.capacity){
            index = this.capacity;
            this.capacity = this.capacity * 2;
            var tkeys = new Array(this.capacity);
            var titems = new Array(this.capacity);

            for (ii = 0; ii < this.capacity; ii++){
                tkeys[ii] = this.keys[ii];
                titems[ii] = this.items[ii];
            }

            this.keys = tkeys;
            this.items = titems;
        } else {
            index = this.length;

        }
        this.length++;
    }

    this.keys[index] = key;
    this.items[index] = item;

    return index;
}

function getByKey(key){
    var result = null;
    for (i = 0; i < this.length; i++){
        if (this.keys[i] == key){
            result = this.items[i];
        }
    }
    return result;
}

function getItemByIndex(index){
    var result = null;
    result = this.items[index];
    return result;
}

function getKeyByIndex(index){
    var result = null;
    result = this.keys[index];
    return result;
}

function removeByKey(key){
    alert("removeByKey not implemented");
    this.length--;
}

function removeByIndex(index){
    alert("removeByIndex not implemented");
    this.length--;
}

/*
    Functions:
        processQueryString
        tokenize
        formatDollarValue(number)
*/

function processQueryString(){
    var result = null;
    var data = new String(window.location);
    if (data.indexOf('?') > -1){
        result = newArrayList(true);
        data = data.substring(data.indexOf('?') + 1, data.length);

        var ampTokens = tokenize(data, "&");
        var equTokens = null;
        for (var ij = 0; ij < ampTokens.length; ij++){
            equTokens = tokenize(new String(ampTokens.getItemByIndex(ij)), "=");
            if (equTokens.length == 2){
                result.add(
                    equTokens.getItemByIndex(0),
                    equTokens.getItemByIndex(1));
            }
        }
        if (result.length == 0){
            result = null;
        }
    }
    return result;
}

function tokenize(data, token){
    var tokenSize = token.length;
    var tokens = newArrayList(true);
    var pos = data.indexOf(token);
    var index = 0;

    if (pos == -1){
        tokens.add(null, data);
    } else {
        while ((pos > -1)){
            var d1 = data.substring(0, pos);
            var d2 = data.substring(pos + tokenSize, data.length);
            data = d2;
            tokens.add(null, d1);
            index++;
            pos = data.indexOf(token);
            if (pos == -1){
                if ((d2 != null) && (d2 != '')){ //This does not allow trailing tokens to create a null list entry
                    tokens.add(null, d2);
                }
            }
        }
    }
    if (tokens.length == 0){
        tokens = null;
    }
    return tokens;
}

function formatDollarValue(val){
    val = Math.floor(val * 100)/100;
    return val;
}

/* This is the function that actually highlights a text string by
 * adding HTML tags before and after all occurrences of the search
 * term. You can pass your own tags if you'd like, or if the
 * highlightStartTag or highlightEndTag parameters are omitted or
 * are empty strings then the default <font> tags will be used. From nsftools.com.
 */
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag)
{
    // the highlightStartTag and highlightEndTag parameters are optional
    if ((!highlightStartTag) || (!highlightEndTag)) {
        highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
        highlightEndTag = "</font>";
    }

    // find all occurences of the search term in the given text,
    // and add some "highlight" tags to them (we're not using a
    // regular expression search, because we want to filter out
    // matches that occur within HTML tags and script blocks, so
    // we have to do a little extra validation)
    var newText = "";
    var i = -1;
    var lcSearchTerm = searchTerm.toLowerCase();
    var lcBodyText = bodyText.toLowerCase();

    while (bodyText.length > 0) {
        i = lcBodyText.indexOf(lcSearchTerm, i+1);
        if (i < 0) {
            newText += bodyText;
            bodyText = "";
        } else {
            // skip anything inside an HTML tag
            if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
                // skip anything inside a <script> block
                if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
                    newText += bodyText.substring(0, i) + highlightStartTag +
                        bodyText.substr(i, searchTerm.length) + highlightEndTag;
                    bodyText = bodyText.substr(i + searchTerm.length);
                    lcBodyText = bodyText.toLowerCase();
                    i = -1;
                }
            }
        }
    }

    return newText;
}


/* This is sort of a wrapper function to the doHighlight function.
 * It takes the searchText that you pass, optionally splits it into
 * separate words, and transforms the text on the current web page.
 * Only the "searchText" parameter is required; all other parameters
 * are optional and can be omitted. From nsftools.com.
 */
function highlightSearchTerms(
        searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag) {

    if (!searchText ){
        kvPairs = processQueryString();
        if (kvPairs != null){
            searchText = decodeURI(kvPairs.getByKey('searchTerms'));
            treatAsPhrase = (kvPairs.getByKey('treatAsPhrase') == 'true');
        } else {
            return;
        }
    }

    // if the treatAsPhrase parameter is true, then we should search for
    // the entire phrase that was entered; otherwise, we will split the
    // search string so that each word is searched for and highlighted
    // individually
    if (treatAsPhrase) {
        searchArray = [searchText];
    } else {
        searchArray = searchText.split(" ");
    }

    if (!document.body || typeof(document.body.innerHTML) == "undefined") {
        if (warnOnFailure) {
            alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
        }
        return false;
    }

    var bodyText = document.body.innerHTML;
    for (var i = 0; i < searchArray.length; i++) {
        bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
    }

    document.body.innerHTML = bodyText;
    return true;
}


/* This displays a dialog box that allows a user to enter their own
 * search terms to highlight on the page, and then passes the search
 * text or phrase to the highlightSearchTerms function. All parameters
 * are optional. From nsftools.com.
 */
function searchPrompt(defaultText, treatAsPhrase, textColor, bgColor) {
    // This function prompts the user for any words that should
    // be highlighted on this web page
    if (!defaultText) {
        defaultText = "";
    }

    // we can optionally use our own highlight tag values
    if ((!textColor) || (!bgColor)) {
        highlightStartTag = "";
        highlightEndTag = "";
    } else {
        highlightStartTag = "<font style='color:" + textColor + "; background-color:" + bgColor + ";'>";
        highlightEndTag = "</font>";
    }

    if (treatAsPhrase) {
        promptText = "Please enter the phrase you'd like to search for:";
    } else {
        promptText = "Please enter the words you'd like to search for, separated by spaces:";
    }

    searchText = prompt(promptText, defaultText);

    if (!searchText)  {
        alert("No search terms were entered. Exiting function.");
        return false;
    }

    return highlightSearchTerms(searchText, treatAsPhrase, true, highlightStartTag, highlightEndTag);
}

/*******
Array handling methods
*******/

/** Delete an element from an array */
function deleteArrayElement(arr, apos){
    var delResult = new Array();

    if (apos == 0){
        delResult = arr.slice(1);
    } else if (apos < (arr.length - 1)) {
        delResult = arr.slice(0, apos);
        var tmppart = arr.slice(apos + 1);
        for (delI = apos; delI < (arr.length - 1); delI++){
            delResult[delI] = arr[delI + 1];
        }
    } else {
        delResult = arr.slice(0, arr.length - 1);
    }

    return delResult;
}

/** Insert an element into an array
  *  arr - The array
  *  apos - The position where the element will be found
  *  elem - an object that may be contained in an array
  */
function insertArrayElement(arr, apos, elem){
    var insResult = new Array();

    if (apos == 0){
        insResult[0] = elem;
        for (ii = 0; ii < arr.length; ii++){
            insResult[ii + 1] = arr[ii];
        }
    } else if (apos < (arr.length)) {
        for (ii = 0; ii < apos; ii++){
            insResult[ii] = arr[ii];
        }
        insResult[insResult.length] = elem;
        for (ii = apos; ii < arr.length; ii++){
            insResult[ii + 1] = arr[ii];
        }
    } else {
        insResult = arr;
        insResult[insResult.length] = elem;
    }

    return insResult;
}

function switchArrayElement(arr2, fromPos, toPos){
    var theElem = arr2[fromPos];
    var resArray = deleteArrayElement(arr2, fromPos);
    resArray = insertArrayElement(resArray, toPos, theElem);
    return resArray;
}

/**** Misc Google Maps functions ****/

function showGMap(smallMap, newspageName, articleID, mapType, mapURL){
    var sMap = (smallMap == true);
    if (newspageName != null){
        mapURL += '?newspageName=' + newspageName;
    } else {
        mapURL += '?newspageAll=true';
    }
    if (articleID != null){
        mapURL += '&articleID=' + articleID;
    }
    if (mapType != null){
        mapURL += '&mapType=' + mapType;
    }
    if (sMap){
        window.open(mapURL,'','top=50,left=50,resizable=yes,location=yes,menubar=no,scrollbars=yes,status=no,toolbar=no,fullscreen=no,dependent=yes,height=800,width=800');
    } else {
        window.open(mapURL,'','top=50,left=50,directories=no,resizable=yes,location=no,menubar=no,scrollbars=no,status=no,toolbar=no,fullscreen=no,dependent=yes,height=800,width=975');
    }
}

/**** POINT OBJECT ***/

function Point(){
    this.x = 0;
    this.y = 0;
}

function newPoint(pX, pY){
    var point = new Point();
    if ((pX != null) && (pY != null)){
        point.x = pX;
        point.y = pY;
    }
    return point;
}

var startPosition = newPoint();

/**** NEWSPAGE OBJECT ***/

/*
    Newspage
        .length
        .capacity
        .allowDuplicateKeys <-- note get()
            will only get the first duplicate if true
        .add()
        .getByKey()
        .getItemByIndex() -- zero-based
        .getKeyByIndex() -- zero-based

    Constructor function
        newNewspage(allowDupKeys)
*/

function Newspage(){
    this.name = '';
    this.id = -1;
    this.title = '';
    this.subTitle = '';
    this.headlineType = 'brief';
    this.pageType = 'articles';
    this.sectionName = '';

    this.column = 0;
    this.displayNum = 4;
    this.rank = -1;
    this.isVisible = true;
    this.pageOwner = '';
    this.isBlog = false;
    this.expires = 'Never';
    this.active = true; // can be updated
    this.sortType = 'date: newest first';

    this.promptComments = 'add a comment';
    this.allowComments = false;
    this.defaultIconID = 0;
}

function newNewspage(name, id, title, subTitle, headlineType, pageType, sectionName,
        column, displayNum, rank, isVisible, pageOwner, isBlog, expires, active,
        sortType, promptComments, allowComments, isRoute, defaultIconID){
    var newspage = new Newspage();
    if (name != null){
        newspage.name = name;
        newspage.id = id;
        newspage.title = title;
        newspage.subTitle = subTitle;
        newspage.headlineType = headlineType;
        newspage.pageType = pageType;
        newspage.sectionName = sectionName;
        newspage.column = column;
        newspage.displayNum = displayNum;
        newspage.rank = rank;
        newspage.isVisible =
            ((isVisible == '1') || (isVisible == 'true') || (isVisible == 'True'));
        newspage.pageOwner = pageOwner;
        newspage.isBlog =
            ((isBlog == '1') || (isBlog == 'true') || (isBlog == 'True'));
        newspage.active =
            ((active == '1') || (active == 'true') || (active == 'True'));
        newspage.sortType = sortType;
        newspage.promptComments = promptComments;
        newspage.allowComments =
            ((allowComments == '1') || (allowComments == 'true') || (allowComments == 'True'));
        newspage.isRoute =
            ((isRoute == '1') || (isRoute == 'true') || (isRoute == 'True'));

        if (expires == 'Never'){
            newspage.expires = 'Never';
        } else {
            newspage.expires = parseInt(expires);
        }
        newspage.defaultIconID = parseInt(defaultIconID);
    }
    return newspage;
}

/*************** EVENT HANDLING ********************/

// Detect the enter key on a keydown/keyup/keypressed event
function detectEnterKey(e){
    var unicode=e.keyCode? e.keyCode : e.charCode;
    return (unicode == 13);
}


/**************** AJAX STUFF *************************/
function callAJAXURL(url, listenerFunction) {
    var httpRequest = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        httpRequest = new XMLHttpRequest();
        if (httpRequest.overrideMimeType) {
            httpRequest.overrideMimeType('text/plain');
            // See note below about this line
        }
    } else if (window.ActiveXObject) { // IE
        try {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!httpRequest) {
        alert('AJAX Error: Cannot create an XMLHTTP instance');
    } else {
        httpRequest.onreadystatechange = function() { listenerFunction(httpRequest); };
        httpRequest.open('GET', url, true);
        httpRequest.send(null);
    }

    return !httpRequest;
}

/*
function alertContents(httpRequest) {
    if (httpRequest.readyState == 4) {
        if (httpRequest.status == 200) {
            alert(httpRequest.responseText);
        } else {
            alert('There was a problem with the request.');
        }
    }

}
*/

/********** PASSWORD STUFF ************/

function checkRestrictedAccess(sectionName, newspageName, newspageLink, extraInfo){
    var authorized = false;

    // Get cookie value
    //setCookie('yakjive.' + SITE_ID + '.restrictedAccess', 'hello');
    var cookieVal = getCookie('yakjive.' + SITE_ID + '.restrictedAccess');
    //alert(cookieVal);
    authorized = (cookieVal != null);

    getByID('rSectionName').value = sectionName;
    if (newspageName != null){
        getByID('rNewspageName').value = newspageName;
        getByID('rNewspageLink').value = newspageLink;
    }

    if (extraInfo != null){
        getByID('rExtraInfo').value = extraInfo;
    }

    if (authorized){
        checkCookie(cookieVal);
    } else {
        showPasswordBox();
    }
}

function getAntiCacheingPair(){
    return '&antiCacheing=' + Math.round(Math.random() * 100000000);
}

function showPasswordBox(){
    changeElementStyle('pageMask', 'pageMaskShow');
    getByID('passwordDialog').className = 'pwdDlgShow';
    getByID('rUsername').focus();
    if (getByID('rUsername').value != ''){
        setTimeout('getByID(\'rPassword\').focus()',100);
    }
}

function hidePasswordBox(item){
    changeElementStyle('pageMask', 'pageMaskHide');
    getByID('passwordDialog').className = 'pwdDlgHide';
    getByID('rUsername').value = '';
    getByID('rPassword').value = '';
}

function showSelectPageBox(){
    getByID('selectPageDialog').className = 'pageDlgShow';
    changeElementStyle('pageMask', 'pageMaskShow');
    setTimeout('getFromForm(\'submit\', \'selectPageForm\').focus();');
}

function hideSelectPageBox(){
    getByID('selectPageDialog').className = 'pageDlgHide';
    changeElementStyle('pageMask', 'pageMaskHide');
}

function changeElementStyle(eName, eStyleClass){
    getByID(eName).className = eStyleClass;
}

function checkCookie(cval){
    var ccURL = ADMIN_URL + 'dispatch_authentication.py?' +
        'operation=check_cookie' +
        '&rCheckAccess=' + cval +
        '&rSectionName=' + getByID('rSectionName').value +
        '&rNewspageName=' + getByID('rNewspageName').value +
        '&rNewspageLink=' + getByID('rNewspageLink').value;

    ccURL += getAntiCacheingPair();

    // Submit authorization request
    callAJAXURL(ccURL, checkCookieResponseListener);
}

function makeRerouteURL(pSectionName, pNewspageName, pNewspageLink, pExtraInfo){
    var rURL = ADMIN_URL;
    if (pSectionName == null){
        rURL += 'dispatch_authentication.py?' +
            'operation=reroute' +
            '&rSectionName=' + getByID('rSectionName').value +
            '&rNewspageName=' + getByID('rNewspageName').value +
            '&rNewspageLink=' + getByID('rNewspageLink').value +
            getAntiCacheingPair() +
            '&' + getByID('rExtraInfo').value;
    } else {
        rURL += 'dispatch_authentication.py?' +
            'operation=reroute' +
            '&rSectionName=' + pSectionName +
            '&rNewspageName=' + pNewspageName +
            '&rNewspageLink=' + pNewspageLink +
            getAntiCacheingPair() +
            '&' + pExtraInfo;
    }
    return rURL;
}

function checkCookieResponseListener(httpRequest){
    try{
        if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {
                //alert(httpRequest.responseText.trim());
                if (httpRequest.responseText.trim() == 'true'){
                    try {
                        document.location = makeRerouteURL();
                    } catch (e) {
                        alert('Unable to find location ' + httpRequest.responseText);
                    }
                } else if (httpRequest.responseText.trim().indexOf('section:') == 0){
                    var sName = httpRequest.responseText.trim().substring(8);
                    getByID('rSectionName').value = sName;
                    getByID('rNewspageName').value = '';
                    getByID('rNewspageLink').value = '';
                    document.location = makeRerouteURL();
                } else if (httpRequest.responseText.trim().indexOf('sections:') == 0){
                    //Select from a couple of sections
                    var sNames = httpRequest.responseText.trim().substring(9);
                    sNames = tokenize(sNames, '::::');
                    var selSectionName = getByID('rSectionNameSelect');
                    clearSelect2(selSectionName);
                    var tSect = '';
                    for (i = 0; i < sNames.length; i++){
                        tSect = sNames.get(i);
                        var tokTSect = tokenize(tSect, '||||');
                        addToSelect2(selSectionName, tokTSect.get(0), tokTSect.get(1));
                    }
                    showSelectPageBox();
                } else if (httpRequest.responseText.trim() == 'false') {
                    getByID('pwdMessage').innerHTML = '<font color="#0000FF">Login required</font>'
                    showPasswordBox();
                } else {
                    getByID('pwdMessage').innerHTML = '<font color="#0000FF">Exception verifying cookies</font>'
                    //alert('[ccr]' + httpRequest.responseText);
                    showPasswordBox();
                }
            } else {
                getByID('pwdMessage').innerHTML = '<font color="#0000FF">Login required [2:' + httpRequest.status + ']</font>'
                showPasswordBox();
            }
        }
    } catch (e) {
        alert('Exception ' + e);
    }
}

function checkEnterPressed(e){
   if (detectEnterKey(e)){
       submitPasswordBox();
   }
}

function submitPasswordBox(){
    var pd = getByID('passwordDialog');
    var pwdURL = '';

    // Create the url
    pwdURL = ADMIN_URL + 'dispatch_authentication.py?' +
        'operation=check_password' +
        '&rUsername=' + getByID('rUsername').value +
        '&rPassword=' + getByID('rPassword').value +
        '&rSectionName=' + getByID('rSectionName').value +
        '&rNewspageName=' + getByID('rNewspageName').value +
        '&rNewspageLink=' + getByID('rNewspageLink').value;

    //alert(pwdURL);

    if (getByID('rExpire').checked){
        pwdURL += '&rExpire=true'
    }
    pwdURL += getAntiCacheingPair();

    // Submit authorization request
    getByID('pwdMessage').innerHTML = '<font color="#0000FF">Authorizing...<img src="http://www.yakjive.com/styles/images/blueslice.gif"></font>';
    callAJAXURL(pwdURL, passwordResponseListener);
}

function passwordResponseListener(httpRequest){
    if (httpRequest.readyState == 4) {
        if (httpRequest.status == 200) {
            //alert(httpRequest.responseText.trim());
            if (httpRequest.responseText.trim() == 'true'){
                getByID('pwdMessage').innerHTML = '<font color="#007700">Authorized</font>';
                try {
                    document.location = makeRerouteURL();
                    // Don't forget to set the cookie in the response
                } catch (e) {
                    getByID('pwdMessage').innerHTML = '<font color="#FF0000">Error. Unable to login.</font>';
                }
            } else if (httpRequest.responseText.trim().indexOf('section:') == 0){
            	//Go directly to the section
                var sName = httpRequest.responseText.trim().substring(8);
                getByID('rSectionName').value = sName;
                getByID('rNewspageName').value = '';
                getByID('rNewspageLink').value = '';
                document.location = makeRerouteURL();
            } else if (httpRequest.responseText.trim().indexOf('sections:') == 0){
                //Choose from several sections
                var sNames = httpRequest.responseText.trim().substring(9);
                sNames = tokenize(sNames, '::::');
                var selSectionName = getByID('rSectionNameSelect');
                clearSelect2(selSectionName);
                var tSect = '';
                for (i = 0; i < sNames.length; i++){
                    tSect = sNames.get(i);
                    var tokTSect = tokenize(tSect, '||||');
                    addToSelect2(selSectionName, tokTSect.get(0), tokTSect.get(1));
                }
                showSelectPageBox();
            } else if (httpRequest.responseText.trim() == 'false') {
                getByID('pwdMessage').innerHTML = 'Login failed';
                getByID('rUsername').value = '';
                getByID('rPassword').value = '';
            } else {
                getByID('pwdMessage').innerHTML = '<font color="#0000FF">Unable to login at this time [1]</font>'
                //alert('[prl]' + httpRequest.responseText);
            }
        } else {
            getByID('pwdMessage').innerHTML = '<font color="#FF0000">Error [' + httpRequest.status + ']. Unable to login.</font>';
        }
    }
}

function checkCookieStatus(){
    var cookieVal = getCookie('yakjive.' + SITE_ID + '.restrictedAccess');
    if ((cookieVal != null) && (cookieVal != '')){
        var ccURL = ADMIN_URL + 'dispatch_authentication.py?' +
            'operation=check_cookie_status' +
            '&rCheckAccess=' + cookieVal;

        ccURL += getAntiCacheingPair();

        // Submit authorization request
        writeMessageDiv("flashMessage", "Checking access...");
        callAJAXURL(ccURL, checkCookieStatusListener);
    } else {
        var toolbarDiv = getByID('toolbarDialog');
        toolbarDiv.className = 'toolbarDlgHide';
    }
}

function checkCookieStatusListener(httpRequest){
    if (httpRequest.readyState == 4) {
        if (httpRequest.status == 200) {
            //alert('PageName = ' + PAGE_NAME + '\n' + httpRequest.responseText.trim());
            var adminMods = '';
            var articleMods = '';
            var newspageMods = '';
            var theResponse = httpRequest.responseText.trim();
            if (theResponse.indexOf(':publish:') > -1){
                adminMods += '<a class=\'toolbarIcon\' href=\'' + ADMIN_URL +
                    'dispatch_authentication.py?operation=publish\' title=\'Publish website\' onclick=\'javascript:writeMessageDiv("flashMessage", "Publishing website...");\'>' +
                    '<img alt=\'Publish website\' width=\'22\' height=\'29\' src=\'' + STYLE_URL + '/images/icons/publish.png\'/></a\n>';
            }
            if (theResponse.indexOf(':manage:') > -1){
                adminMods += '<a class=\'toolbarIcon\' href=\'' + ADMIN_URL +
                    'dispatch_authentication.py?operation=manage\' title=\'Edit site properties\'  onclick=\'javascript:writeMessageDiv("flashMessage", "Finding properties...");\'>' +
                    '<img alt=\'Edit site properties\' width=\'28\' height=\'28\' src=\'' + STYLE_URL + '/images/icons/gear.png\'/></a\n>';
            }
            if (theResponse.indexOf(':admin:') > -1){
                adminMods += '<a class=\'toolbarIcon\' href=\'' + ADMIN_URL +
                    'dispatch_wizard.py?operation=show_default_page\' title=\'Goto administration interface\'  onclick=\'javascript:writeMessageDiv("flashMessage", "Finding admin site...");\'>' +
                    '<img alt=\'Goto Admin interface\' width=\'25\' height=\'27\' src=\'' + STYLE_URL + '/images/icons/bluelock.png\'/></a\n>';
            }
            if (theResponse.indexOf(':add_section:') > -1){
                adminMods += '<a class=\'toolbarIcon\' href=\'' + ADMIN_URL +
                    'dispatch_wizard.py?operation=section&step=1&route=toolbar&routeSection=' + SECTION_NAME + '&routePage=' +
                    PAGE_NAME + '\' title=\'Add a section\'  onclick=\'javascript:writeMessageDiv("flashMessage", "Loading...");\'>' +
                    '<img alt=\'Add a section\' width=\'25\' height=\'25\' src=\'' + STYLE_URL + '/images/icons/add_section2.png\'/></a\n>';
            }
            if (theResponse.indexOf(':add_newspage:') > -1){
                if (SECTION_NAME != '$INFO_PAGE'){
                    adminMods += '<a class=\'toolbarIcon\' href=\'' + ADMIN_URL +
                        'dispatch_wizard.py?operation=newspage&step=1&route=toolbar&routeSection=' + SECTION_NAME +
                        '\' title=\'Add newspage to this section\'  onclick=\'javascript:writeMessageDiv("flashMessage", "Loading...");\'>' +
                        '<img alt=\'Add newspage to this section\' width=\'25\' height=\'25\' src=\'' + STYLE_URL + '/images/icons/add_newspage2.png\'/></a\n>';
                }
            }
            if (theResponse.indexOf(':layout:') > -1){
                adminMods += '<a class=\'toolbarIcon\' href=\'' + ADMIN_URL +
                    'dispatch_wizard.py?operation=layout_init&route=toolbar&layoutStartSection=' + SECTION_NAME +
                    '\' title=\'Edit site layout\'  onclick=\'javascript:writeMessageDiv("flashMessage", "Layout editor...");\'>' +
                    '<img alt=\'Edit site layout\' width=\'26\' height=\'28\' src=\'' + STYLE_URL + '/images/icons/layout2.png\'/></a\n>';
            }
            if (theResponse.indexOf(':style:') > -1){
                adminMods += '<a class=\'toolbarIcon\' href=\'' + ADMIN_URL +
                    'manage_styles_basic.py?route=toolbar\' title=\'Edit site styles\'  onclick=\'javascript:writeMessageDiv("flashMessage", "Style editor...");\'>' +
                    '<img alt=\'Edit site styles\' width=\'27\' height=\'27\' src=\'' + STYLE_URL + '/images/icons/colorwheel.png\'/></a\n>';
            }
            if (theResponse.indexOf(':logout:') > -1){
                adminMods += '<a class=\'toolbarIcon\' href=\'' + ADMIN_URL +
                    'dispatch_authentication.py?operation=logout\' title=\'Logout and clear cookies\'  onclick=\'javascript:writeMessageDiv("flashMessage", "Logging out...");\'>' +
                    '<img alt=\'Logout\' width=\'24\' height=\'29\' src=\'' + STYLE_URL + '/images/icons/logout.png\'/></a\n>';
                adminMods += '<a class=\'toolbarIcon\' href=\'' + ROOT_URL + '\' title=\'Goto your home page\'>' +
                    '<img alt=\'Home page\' width=\'25\' height=\'28\' src=\'' + STYLE_URL + '/images/icons/home.png\'/></a\n>';
            }
            if (theResponse.indexOf(':add_article:') > -1){
                newspageMods += '<a class="toolbarIcon" href="' + ADMIN_URL +
                    'dispatch_authentication.py?operation=add_article&nid=insertNID" title="Add an article to this newspage">' +
                    '<img alt=\'Add an article to this newspage\' width="21" height="21" src="' + STYLE_URL + '/images/icons/add.png"/></a\n>';
                newspageMods += '<a class="toolbarIcon" href="' + ADMIN_URL +
                    'dispatch_authentication.py?operation=manage_articles&nid=insertNID" title="Manage articles on this newspage">' +
                    '<img alt=\'Manage articles on this newspage\' width="22" height="26" src="' + STYLE_URL + '/images/icons/edit_folder2.png"/></a\n>';
                if ((PAGE_NAME != null) && (theResponse.indexOf('|' + PAGE_NAME + ':') > 0)){
                    articleMods += '<a class="toolbarIcon" href="' + ADMIN_URL +
                        'dispatch_authentication.py?operation=add_article&aid=insertAID" title="Add an article to this newspage">' +
                        '<img alt=\'Add an article to this newspage\' width="21" height="21" src="' + STYLE_URL + '/images/icons/add.png"/></a\n>';
                }
            }
            if ((PAGE_NAME != null) && (theResponse.indexOf('|' + PAGE_NAME + ':e') > 0)){
                articleMods += '<a class="toolbarIcon" href="' + ADMIN_URL +
                    'dispatch_authentication.py?operation=edit_article&aid=insertAID" title="Edit this article">' +
                    '<img alt=\'Edit this article\' width="15" height="21" src="' + STYLE_URL + '/images/icons/edit.png"/></a\n>';
                articleMods += '<a class="toolbarIcon" href="' + ADMIN_URL +
                    'dispatch_authentication.py?operation=hide_article&aid=insertAID" title="Hide this article"  onclick=\'javascript:writeMessageDiv("flashMessage", "Hiding article...");\'>' +
                    '<img alt=\'Hide this article\' width="21" height="21" src="' + STYLE_URL + '/images/icons/delete.png"/></a\n>';
            }
            if (adminMods != ''){
                var toolbarDiv = getByID('toolbarDialog');
                toolbarDiv.className = 'toolbarDlgHide';
                toolbarDiv.className = 'toolbarDlgShow';
                //alert('before:' + toolbarDiv.innerHTML + '\n' + toolbarDiv.className);
                toolbarDiv.innerHTML = adminMods + '';
            }
            var allDivs = document.getElementsByTagName('div');
            var aID = '';
            var nID = '';
            if (newspageMods != ''){
                newspageMods = '<div class="articleToolBar">' + newspageMods + '</div>';
            }
            if (articleMods != ''){
                articleMods = '<div class="articleToolBar">' + articleMods + '</div>';
            }
            for (i = 0; i < allDivs.length; i++){
                if ((USE_NEWSPAGE_TOOLBAR) && (allDivs[i].className == 'articleBox')){
                    nID = allDivs[i].attributes.getNamedItem('id').value; // = allDivs[i].id;
                    nID = nID.substring(3);
                    //alert(httpRequest.responseText + '\n\n' + nID);
                    if (theResponse.indexOf('|' + nID + ':') > 0){
                        allDivs[i].innerHTML = newspageMods.replace(/insertNID/g, nID) + allDivs[i].innerHTML;
                    }
                }
                if (articleMods != ''){
                    if ((USE_ARTICLE_TOOLBAR) && (allDivs[i].className == 'articleBox')){
                        aID = allDivs[i].attributes.getNamedItem('id').value; // = allDivs[i].id;
                        if ((aID != null) && (aID != '')){
                            allDivs[i].innerHTML = articleMods.replace(/insertAID/g,aID.substring(3)) + allDivs[i].innerHTML;
                        }
                    }
                }
            }
            if ((adminMods == '') && (newspageMods == '') && (articleMods == '')){
                var toolbarDiv = getByID('toolbarDialog');
                toolbarDiv.className = 'toolbarDlgHide';
            }
        }
    }
    hideMessageDiv("flashMessage");
}

/****************************** Write MOV window ****************************/
function writeMovWindow(rk, docSrc, notes, scriptURL){
    var mWin = eval('movWindow' + rk);
    mWin.document.open();
    mWin.document.write('<html><head><title>' + notes + 
        '</title><SCRIPT TYPE=\'text/javascript\' SRC=\'' + scriptURL + 
        'scripts/AC_QuickTime.js\'></SCRIPT></head><body>\n' + 
        '<div class="movieDiv"><script type="text/javascript">QT_WriteOBJECT(\'' + docSrc + 
        '\' , \'320\', \'260\' , \'\', \'AUTOPLAY\', \'False\');</script>\n' + 
        '</body></html>');
    mWin.document.close();
}