debug = false;

// get the html params from the URL
function queryParam() {
    var qsParm = new Array();
    var query = unescape(window.location.hash.substring(1));
//    alert(window.location.hash);
    if(!query) {
        query = unescape(window.location.search.substring(1));
//        alert(query);
    }

    var pos = query.indexOf('?');
//    alert("?  position: "+pos);
    if(pos == -1) {
        pos = query.indexOf('@');
    }
    if(pos > 0) {
        qsParm["page"] = query.substring(0, pos);
//        alert("key: page value: "+qsParm["page"]);

        query = query.substring(pos+1);
    }
    var parms = query.split('&');
    for(var i=0; i<parms.length; i++) {
        var pos=parms[i].indexOf('=');
        if(pos > 0) {
            var key = parms[i].substring(0, pos);
            var val = parms[i].substring(pos+1);
//            alert("key: "+key+" value: "+val);
            qsParm[key] = val;
        }
    }
    return qsParm;
}

function updateRemove(res, status, resXML, args) {
    if(status != 404) {
        putContent4(res, status, resXML, args);
    } else {
//        alert(args);
//        alert(args[0]);
        var id = args[0];
        var el = document.getElementById(id);
         el.innerHTML = "";
    }

}

var params = queryParam();
if(params["debug"] != null) {
    debug = true;
}

function updatePage(location) {
    location = location.replace("?", "@");
    window.location.hash= location;
    var n = params["n"];
    var n2 = params["n2"];
    params = queryParam();
    if(params["debug"]) {
        debug = true;
    }
//    alert(params["page"]);
    var pathname = window.location.pathname;
    var shortPath;
    if(pathname.indexOf("/") == 0) {
        shortPath = pathname.substring(1);
    }
//    alert(params["page"] +" =? "+pathname+(params["page"] == pathname));
    if(params["page"] != pathname && params["page"] != shortPath) {
        var url = params["page"] + "?";
//        alert(params.length);
        var first = true;
        for(var i in params) {
//            alert(params[i]);
            if(i != "page") {
                url += (first ? "" : "&")+i+"="+params[i];
                first = false;
            }
        }
//        alert(url);
        window.location = url;
    } else {
        var temp = new ajaxObject('http://'+window.location.host+'/alfresco/service/antech/content3.json',putContent4,"contentMarker");
        temp.update('tag='+params["p"]+'&guest=true'+(params["workingCopy"] != null ? '&workingCopy=true' : ''));
    }
//    alert(n + " "+params["n"]);
    if(params["n"] != n) {
        var temp = new ajaxObject('http://'+window.location.host+'/alfresco/service/antech/menuLeft.json',putContent4,"leftcol");
        temp.update('menu='+params["n"]+'&guest=true'+(params["workingCopy"] != null ? '&workingCopy=true' : ''));
    }
//    alert(n2 + " "+params["n2"]);
    if(!params["n2"]) {
//        alert("test");
        updateRemove("res",404,"resXML", new Array("rightcol") );
    } else
        if(params["n2"] != n2) {
        var temp2 = new ajaxObject('http://'+window.location.host+'/alfresco/service/antech/content3.json',updateRemove,"rightcol");
        temp2.update('tag='+params["n2"]+'&guest=true'+(params["workingCopy"] != null ? '&workingCopy=true' : ''));
    }
}

function highlightCurrent() {
   var anchors = document.getElementsByTagName("a");
   for(var i=0; i< anchors.length; i++) {
      if(anchors[i].className == "mainlevel" || anchors[i].className == "sublevel") {
         //alert(anchors[i].href);
         var hrefParm = new Array();
         var query = anchors[i].href;
         var parms = query.split('&');
         for(var j=0; j<parms.length; j++) {
            var pos=parms[j].indexOf('=');
            if(pos > 0) {
               var key = parms[j].substring(0, pos);
               var val = parms[j].substring(pos+1);
               hrefParm[key] = val;
            }
         }
         //alert(hrefParm["p"]);
         if(hrefParm["p"] == params["p"]) {
            //alert(params["p"]);
            //anchors[i].style.backgroundImage="url(http://www.antech-online.com/images/nav/menu-arrow.gif)";
            anchors[i].style.fontWeight="bold";
         }
         //alert(params["p"]);
      }
     // alert(anchors[i]);
   }
   //alert(anchors.length);
}

var urlQueue = new Queue();
var scriptQueue = new Queue();
var urlCount = 0;
var loadedCount = 0;
var ajaxReturnCount = 0;
var noscripts = true;

function careerCitySort(a, b) {
    if(a.city == b.city) {
        return a.title < b.title ? -1 : 1;
    } else {
        return a.city < b.city ? -1 : 1;
    }
}


function putContent4(res, status, resXML, args) {
//    if(args[2]) {
//        var addFunc = args[2];
//    }
//    if(args[1]) {
//        var sortFunc = args[1];
//    }
    var id = args[0];
    var data =  eval('(' + res + ')');
    var el = document.getElementById(id);
    if(el) {
        if(data) {

            if(params["div"] == id) {
                var index = idArray.length;
                idArray[index] = new Array();
                idArray[index][0] = id;  // the main content div id i.e. "contentMarker"
                idArray[index][1] = new Array();  // the div id of each individual piece of content, usually the CMS GUID
                 if(params["verbose"] == "true") {
                     idArray[index][2] = new Array();  // the contentState of the node, only used for editing
                     idArray[index][3] = new Array();  // the workflow name, only used for editing
                     idArray[index][4] = new Array();  // the workflow links, only used for editing
                 }
            }
            var result = "";
            if(data.nodes) {
                // sort the nodes
//                if(sortFunc) {
//                    data.nodes.sort(sortFunc);
//                }
                for(var i = 0; i < data.nodes.length; i++) {
                    if(data.nodes[i].content) {
                        if(params["div"] == id) {
                            idArray[index][1][i] = data.nodes[i].id;
                        }
//                        if(addFunc) {
//                            result += addFunc(data.nodes[i], data.nodes[i].id);
                        if(params["verbose"] == "true" && params["div"] == id) {
//                            alert(data.nodes[i].workflowLinks);
//                            alert("verboseMode: "+i);
//                            alert(data.nodes[i].contentState);
//                            alert(i+1 < data.nodes.length);
//                            if(i+1 < data.nodes.length) { alert("i: "+i+ " "+data.nodes[i+1].contentState);}
                            if(i+1 < data.nodes.length && (data.nodes[i+1].contentState == "modified" || data.nodes[i+1].contentState == "workflow2") ) {  //|| data.nodes[i+1].contentState == "workflow"
                                if(data.nodes[i].contentState == "workflow1") {
                                    idArray[index][2][i] = "WF1";
                                    if(data.nodes[i].workflowAuthorized == "true") {
                                        idArray[index][3][i] = data.nodes[i].workflowLinks;
                                    }
                                    idArray[index][4][i] = data.nodes[i].workflowName;
                                } else {
                                    idArray[index][2][i] = "R";
                                }
//                                alert("modifed");
                                result += combineDivs(data.nodes[i], data.nodes[i+1], params["verbose"] == "true" ? data.nodes[i].contentState : null, params["verbose"] == "true" ? data.nodes[i+1].contentState : null);

                                // Now we are working with "i+1" since we are incrementing i
                                i++;
                                idArray[index][1][i] = data.nodes[i].id;
                                if(data.nodes[i].contentState == "modified") {
                                    idArray[index][2][i] = "RW";
                                } else if(data.nodes[i].contentState == "workflow2") {
                                    idArray[index][2][i] = "WF2";
                                    if(data.nodes[i].workflowAuthorized == "true") {
//                                        alert(data.nodes[i].workflowAuthorized);
                                        idArray[index][3][i] = data.nodes[i].workflowLinks;
                                    }
                                    idArray[index][4][i] = data.nodes[i].workflowName;
//                                    alert(i+" "+idArray[index][3][i]);
                                }
//                                } else {
//                                    result += processResult(data.nodes[i].content, data.nodes[i].id, params["div"] == id);
//                                }
                            } else {
//                                alert(data.nodes[i].contentState);
                                if(data.nodes[i].contentState == "workflow1" || data.nodes[i].contentState == "workflow2") {
                                    idArray[index][2][i] = "WF2";
                                    if(data.nodes[i].workflowAuthorized == "true") {
                                        idArray[index][3][i] = data.nodes[i].workflowLinks;
                                    }
                                    idArray[index][4][i] = data.nodes[i].workflowName;
//                                    alert(i+" "+idArray[index][3][i]);

                                } else {
                                    idArray[index][2][i] = "RW";
                                }
                                result += processResult(data.nodes[i].content, data.nodes[i].id, params["div"] == id, params["verbose"] == "true" ? data.nodes[i].contentState : null);
                            }
                        } else {
                            result += processResult(data.nodes[i].content, data.nodes[i].id, params["div"] == id, params["verbose"] == "true" ? data.nodes[i].contentState : null);
                        }
                    }
                }
                el.innerHTML = result;
//                if(debug) {
//                    alert(result);
//                }
                document.write = document.writeNew;
                document.writeln = document.writelnNew;
//                loadJSUrls();
            } else {
                if(params["div"] == id) {
                    idArray[index][1][0] = "new";
//                    if(addFunc) {
//                        result += addFunc("", "new");
//                    } else {
                        result += processResult("No content, click the plus icon to add new content.", "new", params["div"] == id);
//                    }
                    el.innerHTML = result;
                }

            }
        }
    }
    ajaxReturnCount++;
//    alert("ajaxReturnCount: "+ajaxReturnCount+" ajaxArray.length: "+ajaxArray.length);
//    alert(ajaxReturnCount >= ajaxArray.length);
    if(ajaxReturnCount >= ajaxArray.length) {
        loadJSUrls();
    }
    if(ajaxReturnCount == ajaxArray.length && noscripts) {
        setTimeout('drawDiv()', 500);
    }
}

function processResult(content, id, drawDiv) {
//    alert(content);
    var div2 = document.createElement("div");
    // IE hack.  Without this innerHTML will omit scripts withing content that starts with a script tag
    div2.innerHTML = "<input type='hidden'/>"+content;
    div2.id = id;
    loadJS(div2);
    var div = document.createElement("div");
    div.appendChild(div2);
    return(div.innerHTML);
}

function loadJS(el) {
    for(var i = 0; i < el.childNodes.length; i++) {
        if(el.childNodes[i].tagName == "SCRIPT") {
//            alert(el.childNodes[i].innerHTML);
            if(el.childNodes[i].innerHTML == "") {
//                alert("url: "+el.childNodes[i]);
                urlQueue.enqueue(el.childNodes[i]);
            } else {
//                alert("script: "+el.childNodes[i]);
                scriptQueue.enqueue(el.childNodes[i]);
            }
            noscripts = false;
            el.removeChild(el.childNodes[i]);
            i--;
        }
    }
}


function dhtmlLoadScript(script) {
//alert(script);
   var e = document.createElement("SCRIPT");
    if(params["verbose"] == "true") {
        while(script != script.replace("guest=true", "")) { script = script.replace("guest=true", ""); };
    } else {
        script = script.replace("&guest=true", "");
    }
   e.text = script;
   e.type="text/javascript";
   document.getElementsByTagName("head")[0].appendChild(e);
}

function dhtmlUrlLoadScript(url) {
//    if(debug) {
//    alert(url);
//    }
   urlCount++;
   var e = document.createElement("SCRIPT");
   e.src = url;
   e.type="text/javascript";
   e.onreadystatechange = function() {
       if(//this.readyState == 'complete' ||
          this.readyState == 'loaded' ||
          this.readyState == 'interactive') {
           urlready();
//           setTimeout('urlready()', 1000);
       }
   };
    e.onload = urlready;
   document.getElementsByTagName("head")[0].appendChild(e);
}

function urlready() {
    loadedCount++;
    if(loadedCount >= urlCount) {
        ready();
    }
}

function ready() {
    if(urlQueue.isEmpty() && scriptQueue.getSize() != 0) {
    //if(debug) {
    //alert("test");
    //}
        loadJSScripts();
//        setTimeout('loadJSScripts()', 200);
    }
    if(ajaxReturnCount == ajaxArray.length && scriptQueue.isEmpty() && urlQueue.isEmpty()) {
        setTimeout('drawDiv()', 500);
    }
}

function loadJSUrls() {
    if(urlQueue.getSize() == 0) {
//    if(debug) {
//    alert("ready");
//    }
        ready();
    }
    while(!urlQueue.isEmpty()) {
        dhtmlUrlLoadScript(urlQueue.dequeue().src);
    }
}

function loadJSScripts() {
    while(!scriptQueue.isEmpty()) {
        dhtmlLoadScript(scriptQueue.dequeue().innerHTML);
    }
    ready();
}

function drawDiv() { }

var idArray = new Array();
var ajaxArray = new Array();

document.writelnOld = document.writeln;
document.writeOld = document.write;

   document.writelnNew = function(str){
//alert(str);
    var moz = !window.opera && !/Apple/.test(navigator.vendor);

    // Watch for writing out closing tags, we just
    // ignore these (as we auto-generate our own)
    if ( str.match(/^<\//) ) return;

    // Make sure & are formatted properly, but Opera
    // messes this up and just ignores it
    if ( !window.opera )
        str = str.replace(/&(?![#a-z0-9]+;)/g, "&");

    // Watch for when no closing tag is provided
    // (Only does one element, quite weak)
    str = str.replace(/<([a-z]+)(.*[^\/])>$/, "<$1$2></$1>");

    // Mozilla assumes that everything in <acronym title="Extensible HyperText Markup  Language">XHTML</acronym> innerHTML
    // is actually <acronym title="Extensible HyperText Markup Language">XHTML</acronym> - Opera  and Safari assume that it's <acronym title="Extensible Markup Language">XML</acronym>
    if ( !moz )
        str = str.replace(/(<[a-z]+)/g, "$1 xmlns='http://www.w3.org/1999/xhtml'");

    // The HTML needs to be within a XHTML element
//       var div = document.createElementNS("http://www.w3.org/1999/xhtml","div");
    var div = document.createElement("div");
    div.innerHTML = str;

    // Find the last element in the document
    var pos;

    // Opera and Safari treat getElementsByTagName("*") accurately
    // always including the last element on the page
    if ( !moz ) {
        pos = document.getElementsByTagName("*");
        pos = pos[pos.length - 1];

    // Mozilla does not, we have to traverse manually
    } else {
        pos = document;
        while ( pos.lastChild && pos.lastChild.nodeType == 1 )
            pos = pos.lastChild;
    }

    // Add all the nodes in that position
    var nodes = div.childNodes;
    while ( nodes.length ) {
        pos.parentNode.appendChild( nodes[0] );
    }
};
document.writeNew = document.writelnNew;

/* Queue.js - a function for creating an efficient queue in JavaScript
 *
 * The author of this program, Safalra (Stephen Morley), irrevocably releases
 * all rights to this program, with the intention of it becoming part of the
 * public domain. Because this program is released into the public domain, it
 * comes with no warranty either expressed or implied, to the extent permitted
 * by law.
 *
 * For more public domain JavaScript code by the same author, visit:
 *
 * http://www.safalra.com/web-design/javascript/
 */


/* Creates a new Queue. A Queue is a first-in-first-out (FIFO) data structure.
 * Functions of the Queue object allow elements to be enqueued and dequeued, the
 * first element to be obtained without dequeuing, and for the current size of
 * the Queue and empty/non-empty status to be obtained.
 */
function Queue(){

  // the list of elements, initialised to the empty array
  var queue = [];

  // the amount of space at the front of the queue, initialised to zero
  var queueSpace = 0;

  /* Returns the size of this Queue. The size of a Queue is equal to the number
   * of elements that have been enqueued minus the number of elements that have
   * been dequeued.
   */
  this.getSize = function(){
    // return the number of elements in the queue
    return queue.length - queueSpace;
  };

  /* Returns true if this Queue is empty, and false otherwise. A Queue is empty
   * if the number of elements that have been enqueued equals the number of
   * elements that have been dequeued.
   */
  this.isEmpty = function(){
    // return true if the queue is empty, and false otherwise
    return (queue.length == 0);
  };

  /* Enqueues the specified element in this Queue. The parameter is:
   *
   * element - the element to enqueue
   */
  this.enqueue = function(element){
    queue.push(element);
  };

  /* Dequeues an element from this Queue. The oldest element in this Queue is
   * removed and returned. If this Queue is empty then undefined is returned.
   */
  this.dequeue = function(){

    // initialise the element to return to be undefined
    var element = undefined;

    // check whether the queue is empty
    if (queue.length){

      // fetch the oldest element in the queue
      element = queue[queueSpace];

      // update the amount of space and check whether a shift should occur
      if (++queueSpace * 2 >= queue.length){

        // set the queue equal to the non-empty portion of the queue
        queue = queue.slice(queueSpace);

        // reset the amount of space at the front of the queue
        queueSpace=0;

      }

    }

    // return the removed element
    return element;
  };

  /* Returns the oldest element in this Queue. If this Queue is empty then
   * undefined is returned. This function returns the same value as the dequeue
   * function, but does not remove the returned element from this Queue.
   */
  this.getOldestElement = function(){

    // initialise the element to return to be undefined
    var element = undefined;

    // if the queue is not element then fetch the oldest element in the queue
    if (queue.length) element = queue[queueSpace];

    // return the oldest element
    return element;
  };

}
