
var ajaxTimerDelay      = 10000;

// array to store CXMLReq objects that wrap the XMLHttpRequest
// used for executing concurrent AJAX requests

var divPosMap = new Array();
var xmlreqs = new Array();
var gDivId = 0;

// helper functions
// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}

function getAjaxMsgElement(id)
{
    if(getElement(id) == null)
    {
        return null;
    }
        
    var parentNode = getElement(id).parentNode;
    
    if(parentNode == null)
    {
        return null;
    }
    
    // run through the child nodes of the parent for matching ajax message
    for (var itemi=0; itemi<parentNode.childNodes.length; itemi++) {
		var childNode = parentNode.childNodes[itemi];
		
		// does this childNode has the class with name ajax_status_box
		if(childNode.className == "ajax_status_box")
		  return childNode;
    }
    
    parentNode = parentNode.parentNode;
    
    if(parentNode == null)
    {
        return null;
    }
    
    // run through the child nodes of the parent for matching ajax message
    for (var itemi=0; itemi<parentNode.childNodes.length; itemi++) {
		var childNode = parentNode.childNodes[itemi];
		
		// does this childNode has the class with name ajax_status_box
		if(childNode.className == "ajax_status_box")
		  return childNode;
    }
    
    return null;
}

function getElement(id)
{
  if (document.getElementById)
     return document.getElementById(id);
  if (document.all)
     return document.all[id];
  return null;
}

function showHideDivs(showDiv, hideDiv)
{
    if(getElement(showDiv) != null)
	   getElement(showDiv).style.display = 'inline';

	if(getElement(hideDiv) != null)
	   getElement(hideDiv).style.display = 'none';
}

function showHideDivBlocks(showDiv, hideDiv)
{
    if(getElement(showDiv) != null)
	   getElement(showDiv).style.display = 'block';

	if(getElement(hideDiv) != null)
	   getElement(hideDiv).style.display = 'none';
}

function extractFromCDATA(xmlDoc, section_name)
{
    var ret_val = null;
    
    if(xmlDoc.getElementsByTagName(section_name))
    {     
        if(xmlDoc.getElementsByTagName(section_name)[0])
        {
            if(xmlDoc.getElementsByTagName(section_name)[0].firstChild)
            {
                if(xmlDoc.getElementsByTagName(section_name)[0].firstChild.data)
                {
                    ret_val = xmlDoc.getElementsByTagName(section_name)[0].firstChild.data;
                    if(ret_val == "")
                        ret_val = null;
                }
            }
        }
    }
    
    return ret_val;
}

// AJAX business starts here
function CXMLReq(freed, originalDivPrefix, newDivPrefix, imageDivPrefix, ajaxFinalHandlerObj) 
{ 
    this.freed          = freed;
    this.xmlHttp        = false;
    
    this.ajaxTimerID    = null;
    this.divID          = null;
    
    this.originalDivPrefix = originalDivPrefix;
    this.newDivPrefix      = newDivPrefix;
    this.imageDivPrefix    = imageDivPrefix;
    
    this.ajaxFinalHandlerObject  = ajaxFinalHandlerObj;
    
    // the post request change method
    this.postHandleRequestChange = postHandleRequestChange;
    
    // for reading the response from the server
    this.readResponse = readResponse;

    try
    {
        // this should work for all browsers except IE7 or older
        this.xmlHttp = new XMLHttpRequest();
    }
    catch(e)
    {
        // for IE7 and older
        var XmlHttpVersions = ["MSXML2.XMLHTTP.7.0",
                                "MSXML2.XMLHTTP.6.0",
                                "MSXML2.XMLHTTP.5.0",
                                "MSXML2.XMLHTTP.4.0",
                                "MSXML2.XMLHTTP.3.0",
                                "MSXML2.XMLHTTP",
                                "Microsoft.XMLHTTP"];
        
        for(var i = 0; i < XmlHttpVersions.length && !this.xmlHttp; i++)
        {
            try
            {   
                // try to create the XMLHttpRequest object
                this.xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
            }
            catch(e)
            {
            } // ignore potential error
        }
    }
    
    if(!this.xmlHttp)
        alert('AJAX object creation failed!');
}

function postHandleRequestChange(xmlDoc, success, ajaxReply)
{
    if(this.ajaxTimerID != null)
    {
        window.clearInterval(this.ajaxTimerID);
        this.ajaxTimerID = null;
    }
    
    this.ajaxFinalHandlerObject.handler(this.originalDivPrefix, this.newDivPrefix, this.imageDivPrefix, this.divID, success, ajaxReply, xmlDoc);
    
    // finally, free the CXMLReq object
    this.freed = 1;
    
    // remove from the pos map
    divPosMap[this.divID] = -1;
}

// apply the label to an item - call end handler
function RemoveLabelAJAXEndCallHandler(id, label)
{
    this.id         = id;
    this.labelName  = label;
    this.handler    = removeLabelEndCallHandler;
}

// the add label ajax call end handler
function removeLabelEndCallHandler(originalDivPrefix, newDivPrefix, imageDivPrefix, divID, success, ajaxReply, xmlDoc)
{
    // what is the dropdown control id for this action
    var selectCtrlID = 'dropdown_tag_select_' +  this.id;
    
    // take action only if the operation was a success    
    if(success == 1)
    {        
        if(ajaxReply == "##success##")
        {
            // add the label to the option list
            insertOptionNode(getElement(selectCtrlID), createOptionNode(this.labelName));
            
            // remove the label from the label list for the listed object
            removeTagNode(this.id, this.labelName);
        }
    }
}

// apply the label to an item - call end handler
function ApplyLabelAJAXEndCallHandler(id, label)
{
    this.id         = id;
    this.labelName  = label;
    this.handler    = applyLabelEndCallHandler;
}

// the add label ajax call end handler
function applyLabelEndCallHandler(originalDivPrefix, newDivPrefix, imageDivPrefix, divID, success, ajaxReply, xmlDoc)
{
    // remove the processing node
    var selectCtrlID = 'dropdown_tag_select_' +  this.id;
    
    // take action only if the operation was a success    
    if(success == 1)
    {        
        if(ajaxReply == "##success##")
        {          
            // remove the label from the drop down select list
            deleteOptionNode(getElement(selectCtrlID), this.labelName);
            
            // todo - add the applied label to the label list for the listed object
            insertTagNode(this.id, this.labelName, createTagNode(this.id, this.labelName));
        }
    }

    deleteProcessingNode(getElement(selectCtrlID));
    
    // enable the select control
    getElement(selectCtrlID).disabled = false;
    
    // show the first option - which is "Select Tag ..."
    selectFirstOption(getElement(selectCtrlID));
}

function deleteOptionNode(selectNode, tagNameToDelete)
{    
    // insert in the correct spot
    var i = 0;
    
    // phantom node problem in gecko based browser like FF
    // need to check the nodeType first, else attribute id is not there
    while(selectNode.childNodes[i]) {
    
        if(selectNode.childNodes[i].nodeType !== 1)
        {
            ++i;
            continue;
            
        }
        
        // what is the label name of this node?
        tagName = selectNode.childNodes[i].value;
        
        if(tagNameToDelete == tagName.toLowerCase())
        {
            selectNode.removeChild(selectNode.childNodes[i]);
            
            return true;
        }

		i++;
	}
    
    return false;
}

function insertOptionNodeFirstPosition(selectNode, optionNode)
{    
    var i = 0;
    
    // phantom node problem in gecko based browser like FF
    // need to check the nodeType first, else attribute id is not there
    while(selectNode.childNodes[i]) {
    
        if(selectNode.childNodes[i].nodeType !== 1)
        {
            ++i;
            continue;
            
        }
        
        selectNode.insertBefore(optionNode, selectNode.childNodes[i]);
        
        break;
	}
}

function selectFirstOption(selectNode)
{    
    var i = 0;
    
    // phantom node problem in gecko based browser like FF
    // need to check the nodeType first, else attribute id is not there
    while(selectNode.childNodes[i]) {
    
        if(selectNode.childNodes[i].nodeType !== 1)
        {
            ++i;
            continue;
            
        }
        
        selectNode.childNodes[i].selected = true;
        
        break;
	}
}

function deleteProcessingNode(selectNode)
{    
    var i = 0;
    
    // phantom node problem in gecko based browser like FF
    // need to check the nodeType first, else attribute id is not there
    while(selectNode.childNodes[i]) {
    
        if(selectNode.childNodes[i].nodeType !== 1)
        {
            ++i;
            continue;
            
        }
        
        if(selectNode.childNodes[i].value == 'Processing ...')
        {
            // remove the "Processing ..." tag
            selectNode.removeChild(selectNode.childNodes[i]);
            
            break;
        }
	}
}

function insertOptionNode(selectNode, optionNode)
{
    var tagNameToInsert = optionNode.value;
    
    // insert in the correct spot
    var i = 0;
    
    // phantom node problem in gecko based browser like FF
    // need to check the nodeType first, else attribute id is not there
    while(selectNode.childNodes[i]) {
    
        if(selectNode.childNodes[i].nodeType !== 1)
        {
            ++i;
            continue;
            
        }
        
        // what is the label name of this node?
        tagName = selectNode.childNodes[i].value;
        
        if(tagName == '__#noaction#__')
        {
            ++i;
            continue;
        }
        
        if(tagNameToInsert.toLowerCase() < tagName.toLowerCase())
        {
            selectNode.insertBefore(optionNode, selectNode.childNodes[i]);
            
            return;
        }

		i++;
	}
    
    selectNode.appendChild(optionNode);
}

// get the label name from a label node

function readHiddenLabelName(node)
{
    // the node has a hidden div as a child
    // and that div has the label name as text node
    
    // <div class="hidden">label</div>
    
    var i = 0;
    
    // phantom node problem in gecko based browser like FF
    // need to check the nodeType first, else attribute id is not there
    while(node.childNodes[i]) {

        if(node.childNodes[i].nodeType !== 1)
        {
            ++i;
            continue;
        }
        
        if(node.childNodes[i].className == "hidden")
        {
            // we have a match
            // get the child text node
            var j = 0;
    
            // phantom node problem in gecko based browser like FF
            // need to check the nodeType first, else attribute id is not there
            while(node.childNodes[i].childNodes[j]) {
                
                if(node.childNodes[i].childNodes[j].nodeType !== 3)
                {
                    ++j;
                    continue;
                }
                
                return node.childNodes[i].childNodes[j].nodeValue;
            }
        }
        
        ++i;
    }
}

function createHiddenLabelNode(labelName)
{
    // the node has a hidden div as a child
    // and that div has the label name as text node
    
    // <div class="hidden">label</div>
    
    hiddenDiv = document.createElement("div");
    hiddenDiv.className = 'hidden';
    
    // insert the label name in the div
    labelNameText = document.createTextNode(labelName);
    hiddenDiv.appendChild(labelNameText);
    
    return hiddenDiv;
}

function deleteLabelNode(labelListNode, labelName)
{
    var i = 0;
    
    // phantom node problem in gecko based browser like FF
    // need to check the nodeType first, else attribute id is not there
    while(labelListNode.childNodes[i]) {

        if(labelListNode.childNodes[i].nodeType !== 1)
        {
            ++i;
            continue;
            
        }
        
        // var iLabelName = labelListNode.childNodes[i].getAttribute("title");
        var iLabelName = readHiddenLabelName(labelListNode.childNodes[i]);
        
        if(labelName.toLowerCase() == iLabelName.toLowerCase())
        {
            labelListNode.removeChild(labelListNode.childNodes[i]);
            return;
        }

		i++;
	}
}

function insertLabelNode(labelListNode, labelNode)
{
//    elId = labelNode.getAttribute("id");
//        
//    pattern = /tag_list_main_(.*)/;
//    var labelName = elId.replace(pattern, "$1");

    var labelName = readHiddenLabelName(labelNode);
    // var labelName = labelNode.getAttribute("title");
    
    // insert in the correct spot
    var i = 0;
    
    // phantom node problem in gecko based browser like FF
    // need to check the nodeType first, else attribute id is not there
    while(labelListNode.childNodes[i]) {

        if(labelListNode.childNodes[i].nodeType !== 1)
        {
            ++i;
            continue;
            
        }
        // what is the label name of this node?
//        elId = labelListNode.childNodes[i].getAttribute("id");
//        
//        pattern = /tag_list_main_(.*)/;
//        var iLabelName = elId.replace(pattern, "$1");

        // var iLabelName = labelListNode.childNodes[i].getAttribute("title");
        var iLabelName = readHiddenLabelName(labelListNode.childNodes[i]);
        
        if(labelName.toLowerCase() < iLabelName.toLowerCase())
        {
            labelListNode.insertBefore(labelNode, labelListNode.childNodes[i]);
            return;
        }

		i++;
	}
    
    labelListNode.appendChild(labelNode);
}

function createOptionNode(labelName)
{    
    optionNode = document.createElement("option");
    
    // set the value option for the select node
    optionNode.setAttribute("value", labelName);
    
    // create and add the tag text node
    tagNameText = document.createTextNode(labelName);
    optionNode.appendChild(tagNameText);
    
    return optionNode;
}

function createSelectNodeProcessing(labelName)
{    
    optionNode = document.createElement("option");
    
    // set the value option for the select node
    optionNode.setAttribute("value", labelName);
    
    // create and add the tag text node
    tagNameText = document.createTextNode(labelName);
    optionNode.appendChild(tagNameText);
    
    return optionNode;
}

function createTagNode(objectID, labelName)
{    
    labelActionList = document.createElement("div");
    labelActionList.className = 'label-action-list';
    
    // var tagObjID = labelName + '__plus__' + objectID;
    // labelActionList.setAttribute("id", tagObjID);
    
    // labelActionList.setAttribute("title", labelName);
    labelActionList.appendChild(createHiddenLabelNode(labelName));
    
    // the delete and rename links
    linkDiv = document.createElement("div");
    linkDiv.className = 'float_left';
    
        // the ul
        ulDiv = document.createElement("ul");
        
            // the li s
            liDivDel = document.createElement("li");
            liDivDel.className = 'del_label';
            
                // the del anchor element
                delAnchor = document.createElement("a");
                
                // set its href attribute with the setAttribute method
                hrefText = "javascript:removeTag_AJAX(\'" + objectID + "\', \'" + labelName + "\')";
                delAnchor.setAttribute("href", hrefText);
                
                titleText = "Remove Tag";
                delAnchor.setAttribute("title", titleText);
                                
                // append the anchor element to the div
                liDivDel.appendChild(delAnchor);
            
            // insert the li s into the ul
            ulDiv.appendChild(liDivDel);
        
        // insert the ul in the linkDiv
        linkDiv.appendChild(ulDiv);
    
    // the tag name
    tagNameDiv = document.createElement("div");
    tagNameDiv.className = 'float_left';
    
        // insert the tag name in the tag name div
        tagNameText = document.createTextNode(labelName);
        tagNameDiv.appendChild(tagNameText);
    
    labelActionList.appendChild(tagNameDiv);
    labelActionList.appendChild(linkDiv);
    
    return labelActionList;
}

function insertTagNode(objectID, tagName, tagNode)
{
    // get the master tag list with the given ID
    tagListNodeID = 'tags_applied_' + objectID;
    
    tagListNode = getElement(tagListNodeID);
    
    // insert in the correct spot
    var i = 0;
    
    // phantom node problem in gecko based browser like FF
    // need to check the nodeType first, else attribute id is not there
    while(tagListNode.childNodes[i]) {

        if(tagListNode.childNodes[i].nodeType !== 1)
        {
            ++i;
            continue;
            
        }
        
        if(tagListNode.childNodes[i].className !== 'label-action-list')
        {
            ++i;
            continue;
        }
        
        // what is the ID
        // labelName = tagListNode.childNodes[i].getAttribute("title");
        labelName = readHiddenLabelName(tagListNode.childNodes[i]);
        
        // what is the tag name of this node
        // tempArr = elId.split( "__plus__" );
        
        // lets do the comparison
        // if(tagName.toLowerCase() < tempArr[0].toLowerCase())
        if(tagName.toLowerCase() < labelName.toLowerCase())
        {
            tagListNode.insertBefore(tagNode, tagListNode.childNodes[i]);
            return;
        }

		i++;
	}
    
    tagListNode.appendChild(tagNode);
}

function removeTagNode(objectID, tagName)
{
    // get the master tag list with the given ID
    tagListNodeID = 'tags_applied_' + objectID;
    
    tagListNode = getElement(tagListNodeID);
    
    // insert in the correct spot
    var i = 0;
    
    // phantom node problem in gecko based browser like FF
    // need to check the nodeType first, else attribute id is not there
    while(tagListNode.childNodes[i]) {

        if(tagListNode.childNodes[i].nodeType !== 1)
        {
            ++i;
            continue;
            
        }
        
        if(tagListNode.childNodes[i].className !== 'label-action-list')
        {
            ++i;
            continue;
            
        }
        
        // what is the ID
        // labelName = tagListNode.childNodes[i].getAttribute("title");
        labelName = readHiddenLabelName(tagListNode.childNodes[i]);
        
        // what is the tag name of this node
        // tempArr = elId.split( "__plus__" );
        
        // lets do the comparison
        // if(tagName == tempArr[0])
        if(tagName == labelName)
        {
            tagListNode.removeChild(tagListNode.childNodes[i]);
            return true;
        }

		i++;
	}
    
    return false;
}

function localEscape(strToEscape)
{
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = strToEscape;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}

function createLabelNode(labelName)
{
    labelObj = document.createElement("div");
    
    // var labelObjID = 'tag_list_main_' + labelName;
    // labelObj.setAttribute("id", labelObjID);
    labelObj.appendChild(createHiddenLabelNode(labelName));
    
    // labelObj.setAttribute("title", labelName);
    
    labelActionList = document.createElement("div");
    labelActionList.className = 'label-action-list';
    
    // the delete and rename links
    linkDiv = document.createElement("div");
    linkDiv.className = 'float_left';
    
        // the ul
        ulDiv = document.createElement("ul");
        
            // the li s
            liDivDel = document.createElement("li");
            liDivDel.className = 'del_label';
            
                // the del anchor element
                delAnchor = document.createElement("a");
                
                // set its href attribute with the setAttribute method
                hrefText = "javascript:deleteLabelModalPrompt(\'" + labelName + "\')"
                delAnchor.setAttribute("href", hrefText);
                
                titleText = "Delete Tag";
                delAnchor.setAttribute("title", titleText);
                                
                // append the anchor element to the div
                liDivDel.appendChild(delAnchor);
            
            liDivRen = document.createElement("li");
            liDivRen.className = 'ren_label';
            
                // the ren anchor element
                renAnchor = document.createElement("a");
                
                // set its href attribute with the setAttribute method
                hrefText = "javascript:renameLabelModalPrompt(\'" + labelName + "\')"
                renAnchor.setAttribute("href", hrefText);
                
                titleText = "Rename Tag";
                renAnchor.setAttribute("title", titleText);
                                
                // append the anchor element to the div
                liDivRen.appendChild(renAnchor);
            
            // insert the li s into the ul
            ulDiv.appendChild(liDivDel);
            ulDiv.appendChild(liDivRen);
        
        // insert the ul in the linkDiv
        linkDiv.appendChild(ulDiv);
    
    // the tag name
    tagNameDiv = document.createElement("div");
    tagNameDiv.className = 'float_left';
    
        // create the span element
        spanEl = document.createElement("span");
        spanEl.className = 'clicklink';
    
            // insert the tag name in the tag name div
            labelAnchor = document.createElement("a");
            
            // set its href attribute with the setAttribute method
            hrefText = "/secure/linkclick/linkclick.php?function=displaytagged&tag=" + localEscape(labelName);
            labelAnchor.setAttribute("href", hrefText);
                    
            tagNameText = document.createTextNode(labelName);
            labelAnchor.appendChild(tagNameText);
            
            
       // insert the href in the span element
       spanEl.appendChild(labelAnchor);
       
    // insert the span in the tagNameDiv
    tagNameDiv.appendChild(spanEl);
    
    // spacer
    spacerDiv = document.createElement("div");
    spacerDiv.className = 'spacer';
    
    labelActionList.appendChild(linkDiv);
    labelActionList.appendChild(tagNameDiv);
    labelActionList.appendChild(spacerDiv);
    
    labelObj.appendChild(labelActionList);
    
    return labelObj;
}

// apply the label to an item - call end handler
function AddLabelAJAXEndCallHandler(label)
{
    this.labelName  = label;
    this.handler    = addLabelEndCallHandler;
}

function addLabelEndCallHandler(originalDivPrefix, newDivPrefix, imageDivPrefix, divID, success, ajaxReply, xmlDoc)
{    
    var imgDivID        = 'ajax_img_' + divID;
    var errorMsgDivID   = 'addlabel_error_' + divID;
    
    // 1. hide the rotating image irrespective of outcome
    
    showHideDivBlocks('', imgDivID);
    
    // 2. if it was a failure, display the failure message
    if(success == 0)
    {
        showHideDivBlocks(errorMsgDivID, '');
    }
    else
    {
        // the addition could be a success or it could have failed
        if(ajaxReply == "##success##")
        {            
            if(getElement('tag_list_main'))
            {
                insertLabelNode(document.getElementById('tag_list_main'), createLabelNode(this.labelName));
            }
            
            // run through the list of drop down tags in the page and add the tag name
            dropdownLists = getElementsByClassName("label_dropdown_class");
        
            // create the select tag item
            
            for(i = 0; i < dropdownLists.length; i++){
                    insertOptionNode(dropdownLists[i], createOptionNode(this.labelName));
                }
                
            // do the showing and hiding
            showHideDivBlocks('', errorMsgDivID);
            
            // hide the entire form div
            var formDiv = 'addlabel_form_' + divID;
            
            showHideDivBlocks('', formDiv);
            
            // display message in the success block
            var successMsg = "Tag: <span class=\"highlight_text\">" + this.labelName + "</span> added successfully."
            
            // show the success block
            successMsgDivID = 'addlabel_msg_success_' + divID;
            
            successMsgDiv = getElement(successMsgDivID);
            
            if(successMsgDiv != null)
            {
                successMsgDiv.innerHTML = successMsg;
            }
            
            successBlockDivID = 'addlabel_success_' + divID;
            
            showHideDivBlocks(successBlockDivID, '');
        }
        else
        {
            // display the error message
            msgDiv = getElement(errorMsgDivID);
            
            if(msgDiv != null)
            {
                msgDiv.innerHTML = ajaxReply;
            }
            
            showHideDivBlocks(errorMsgDivID, '');
            
            // show the button divs
            var btnDivID = 'ajax_addlabel_btns_' + divID;
            
            showHideDivBlocks(btnDivID, '');
        }
    }
}

// the delete label ajax call end handler
function DeleteLabelAJAXEndCallHandler(label)
{
    this.labelName  = label;
    this.handler    = delLabelEndCallHandler;
}

function delLabelEndCallHandler(originalDivPrefix, newDivPrefix, imageDivPrefix, divID, success, ajaxReply, xmlDoc)
{
    // alert(ajaxReply);
    
    var imgDivID        = 'ajax_img_' + divID;
    var errorMsgDivID   = 'deletelabel_error_' + divID;
    
    // 1. hide the rotating image irrespective of outcome
    
    showHideDivBlocks('', imgDivID);
    
    // 2. if it was a failure, display the failure message
    if(success == 0)
    {
        showHideDivBlocks(errorMsgDivID, '');
    }
    else
    {
        // the addition could be a success or it could have failed
        if(ajaxReply == "##success##")
        {   
            // what is the div in the label list?
            
            deleteLabelNode(document.getElementById('tag_list_main'), this.labelName);
            
//            var delLabelDivID = "tag_list_main_" + this.labelName;
            
//            if( getElement(delLabelDivID) != null)
//            {
//                var parent = getElement(delLabelDivID).parentNode;
//                
//                if(parent != null)
//                {
//                    parent.removeChild(getElement(delLabelDivID));
//                }
//            }
            
            // run through the list of drop down tags
            dropdownLists = getElementsByClassName("label_dropdown_class");
        
            // delete the matching option nodes
            
            for(i = 0; i < dropdownLists.length; i++){
                    deleteOptionNode(dropdownLists[i], this.labelName);
                }

            // run through the applied tags and remove the matching
            tagsAppliedList = getElementsByClassName("tags_applied");
        
            // delete the matching applied tag nodes
            
            for(i = 0; i < tagsAppliedList.length; i++){
                    // what is the object ID?
                    var elId = tagsAppliedList[i].getAttribute("id");
                    
                    var pattern = /tags_applied_(.*)/;
                    var objectID = elId.replace(pattern, "$1");
                    
                    removeTagNode(objectID, this.labelName);
                }
            
            showHideDivBlocks('', errorMsgDivID);
            
            // hide the entire form div
            var formDiv = 'form_' + divID;
            
            showHideDivBlocks('', formDiv);
            
            // display message in the success block
            var successMsg = "Tag: " + this.labelName + " deleted successfully."
            
            // show the success block
            successMsgDivID = 'msg_success_' + divID;
            
            successMsgDiv = getElement(successMsgDivID);
            
            if(successMsgDiv != null)
            {
                successMsgDiv.innerHTML = successMsg;
            }
            
            successBlockDivID = 'deletelabel_success_' + divID;
            
            showHideDivBlocks(successBlockDivID, '');
        }
        else
        {
            // display the error message
            msgDiv = getElement(errorMsgDivID);
            
            if(msgDiv != null)
            {
                msgDiv.innerHTML = ajaxReply;
            }
            
            showHideDivBlocks(errorMsgDivID, '');
            
            // show the button divs
            var btnDivID = 'ajax_deletelabel_btns_' + divID;
            
            showHideDivBlocks(btnDivID, '');
        }
    }
}

// the delete label ajax call end handler
function RenameLabelAJAXEndCallHandler(oldLabel, newLabel)
{
    this.oldLabelName  = oldLabel;
    this.newLabelName  = newLabel;
    
    this.handler    = renameLabelEndCallHandler;
}

function renameLabelEndCallHandler(originalDivPrefix, newDivPrefix, imageDivPrefix, divID, success, ajaxReply, xmlDoc)
{
    // alert(ajaxReply);
    
    var imgDivID        = 'ajax_img_' + divID;
    var errorMsgDivID   = 'renamelabel_error_' + divID;
    
    // 1. hide the rotating image irrespective of outcome
    
    showHideDivBlocks('', imgDivID);
    
    // 2. if it was a failure, display the failure message
    if(success == 0)
    {
        showHideDivBlocks(errorMsgDivID, '');
    }
    else
    {
        // the addition could be a success or it could have failed
        if(ajaxReply == "##success##")
        {  
            // first, delete the old label
            // what is the div in the label list?
            
            deleteLabelNode(document.getElementById('tag_list_main'), this.oldLabelName);
            
//            var delLabelDivID = "tag_list_main_" + this.oldLabelName;
//            
//            if( getElement(delLabelDivID) != null)
//            {
//                var parent = getElement(delLabelDivID).parentNode;
//                
//                if(parent != null)
//                {
//                    parent.removeChild(getElement(delLabelDivID));
//                }
//            }
            
            // then, insert the new label in the correct spot
            if(getElement('tag_list_main'))
            {
                insertLabelNode(document.getElementById('tag_list_main'), createLabelNode(this.newLabelName));
            }
            
            // delete the old name from the drop downs
            dropdownLists = getElementsByClassName("label_dropdown_class");
            
            for(i = 0; i < dropdownLists.length; i++){
            
                    // delete the old name
                    if(deleteOptionNode(dropdownLists[i], this.oldLabelName) == true)
                    {
                        // insert the new name - insert, only if there was a delete
                        insertOptionNode(dropdownLists[i], createOptionNode(this.newLabelName));
                    }
                }
                
           // run through the applied tags and rename the matching
            tagsAppliedList = getElementsByClassName("tags_applied");
        
            // delete the matching applied tag nodes
            
            for(i = 0; i < tagsAppliedList.length; i++){
                    // what is the object ID?
                    var elId = tagsAppliedList[i].getAttribute("id");
                    
                    var pattern = /tags_applied_(.*)/;
                    var objectID = elId.replace(pattern, "$1");
                    
                    // remove the old name
                    if(removeTagNode(objectID, this.oldLabelName) == true)
                    {
                        // insert the new name - insert, only if there was a remove
                        insertTagNode(objectID, this.newLabelName, createTagNode(objectID, this.newLabelName));
                    }
                }
                
            // do the showing and hiding of divs
            showHideDivBlocks('', errorMsgDivID);
            
            // hide the entire form div
            var formDiv = 'form_' + divID;
            
            showHideDivBlocks('', formDiv);
            
            // display message in the success block
            var successMsg = "Rename successful."
            
            // show the success block
            successMsgDivID = 'msg_success_' + divID;
            
            successMsgDiv = getElement(successMsgDivID);
            
            if(successMsgDiv != null)
            {
                successMsgDiv.innerHTML = successMsg;
            }
            
            successBlockDivID = 'renamelabel_success_' + divID;
            
            showHideDivBlocks(successBlockDivID, '');
            
        }
        else
        {
            // display the error message
            msgDiv = getElement(errorMsgDivID);
            
            if(msgDiv != null)
            {
                msgDiv.innerHTML = ajaxReply;
            }
            
            showHideDivBlocks(errorMsgDivID, '');
            
            // show the button divs
            var btnDivID = 'ajax_renamelabel_btns_' + divID;
            
            showHideDivBlocks(btnDivID, '');
        }
    }
}

// the normal ajax call end handler
function DefaultAJAXEndCallHandler()
{
    this.handler = defaultEndCallHandler;
}

function defaultEndCallHandler(originalDivPrefix, newDivPrefix, imageDivPrefix, divID, success, ajaxReply, xmlDoc)
{    
    var contentOriginal = originalDivPrefix + divID;
    var contentNew      = newDivPrefix      + divID;
    var imageDiv        = imageDivPrefix    + divID;
    
    // if successful, hide the original div
    if(success == 1)
        showHideDivs('', contentOriginal);
          
    // always show the loaded div
    // always hide the image
    showHideDivs(contentNew, imageDiv);
}

function ajaxTimeOut(pos)
{
    if(this.ajaxTimerID != null)
    {
        // terminate the ajax timeout timer
        // stop the timer
        window.clearInterval(xmlreqs[pos].ajaxTimerID);
        
        xmlreqs[pos].ajaxTimerID = null;
        
        // abort any pending ajax request
        xmlreqs[pos].xmlHttp.abort();
        
        var contentDiv = xmlreqs[pos].newDivPrefix + xmlreqs[pos].divID;
    
        // hide the contents and show the ajax loading image
        if(getAjaxMsgElement(contentDiv) != null)
        {
            var innerHTML = "Server Timed Out - Please try again ";
            
            getAjaxMsgElement(contentDiv).innerHTML  = innerHTML; 
        }
        
        // call the post ajax handler to update UI
        xmlreqs[pos].postHandleRequestChange(null, 0, innerHTML);
    }
}

function readResponse()
{    
    // retrieve the server's response
    var response = this.xmlHttp.responseText;
    
    // server error?
    if(response.indexOf("ERRNO") >= 0
    || response.indexOf("error:") >= 0
    || response.length == 0)
        throw(response.length == 0 ? "Server error." : response);
        
    // get response in XML format (assume response is valid XML)
    responseXml = this.xmlHttp.responseXML;
    
    // take the actions here
    // the result is sent in XML format
    xmlDoc = responseXml.documentElement;
    
    // extract information sent from the server
    var contentDiv = this.newDivPrefix + this.divID;
    
    var flagResponse   = "error";
    
    flagResponse       = extractFromCDATA(xmlDoc, "xml_flag_field");
    
    if(flagResponse == null)
        flagResponse = "error";
    
    var dataResponse   = extractFromCDATA(xmlDoc, "xml_data_field");
    
    var msgResponse    = extractFromCDATA(xmlDoc, "xml_ajaxmsg_field");
    
    // get the element div id for reporting ajax error or messages
    var ajaxMsgElement = getAjaxMsgElement(contentDiv);
    
    if(ajaxMsgElement != null)
    {
        // trim leading and trailing white spaces
        if(msgResponse != null)
        {
            msgResponse = trim(msgResponse);
            
            if(msgResponse.length != 0)
            {
                if(ajaxMsgElement != null)
                {
                    ajaxMsgElement.innerHTML = msgResponse;
                }
            }
        }
    }
    
    // set the extracted information to the page
    if(dataResponse != null)
    {
        if(getElement(contentDiv) != null)
        {
            getElement(contentDiv).innerHTML = dataResponse;
        }
    }
    else
    {
        // do not touch if there is nothing from the server
        // var innerHTML = '<br />Invalid response from server -  Please try again. ';
        // getElement(contentDiv).innerHTML += innerHTML;
    }
    
    if(flagResponse == "success")
    {
        this.postHandleRequestChange(xmlDoc, 1, msgResponse);
	       
	    return;
    }
    
    dataResponse = '';
    
    if(flagResponse == "error")
    {
        // getElement(contentDiv).innerHTML += '. Please try again. ';
    }
    else
    {
        var msgElement = getAjaxMsgElement(contentDiv);
        
        if(msgElement != null)
        {
            msgElement.innerHTML = '<br />Unrecognized response from server -  Please try again. ';
            dataResponse         = msgElement.innerHTML;
        }
    }
    
    this.postHandleRequestChange(xmlDoc, 0, dataResponse);
}

function handleRequestStateChange(pos)
{
    // when readyState is 4, we read the server response
    if(xmlreqs[pos].xmlHttp.readyState == 4)
    {
        // continue only if HTTP status is "OK"
        if(xmlreqs[pos].xmlHttp.status == 200)
        {
            try
            {
                if(xmlreqs[pos].ajaxTimerID != null)
                {
                    // terminate the ajax timeout timer
                    // stop the timer
                    window.clearInterval(xmlreqs[pos].ajaxTimerID);
                    xmlreqs[pos].ajaxTimerID = null;
                }
        
                // read the response from the server
                var response = xmlreqs[pos].readResponse();
            }
            catch(e)
            {
                var contentDiv = xmlreqs[pos].newDivPrefix + xmlreqs[pos].divID;
                
                dataResponse = '';
                
                if(getAjaxMsgElement(contentDiv) != null)
                {
                    // var innerHTML = e.toString() + '<br /> Please try again. ';
                    getAjaxMsgElement(contentDiv).innerHTML += ' Please try again. ';
                    
                    dataResponse = getAjaxMsgElement(contentDiv).innerHTML;
                }
                
                xmlreqs[pos].xmlHttp.abort();    
                xmlreqs[pos].postHandleRequestChange(null, 0, dataResponse);
            }
        }
        else
        {          
            var contentDiv = xmlreqs[pos].newDivPrefix + xmlreqs[pos].divID;
            
            dataResponse = '';
        
            if(getAjaxMsgElement(contentDiv) != null)
            {
               //  var innerHTML = xmlreqs[pos].xmlHttp.statusText + '<br /> Please try again. ';
                var innerHTML = ' Please try again';
                
                getAjaxMsgElement(contentDiv).innerHTML += innerHTML;
                
                dataResponse = getAjaxMsgElement(contentDiv).innerHTML;
            }
            
            xmlreqs[pos].xmlHttp.abort();  
            xmlreqs[pos].postHandleRequestChange(null, 0, dataResponse);
        }
    }
}

function ajaxSubmit(cgiCode, cgiArray, originalDivPrefix, newDivPrefix, imageDivPrefix, divid, arrayCount, ajaxFinalHandlerObj)
{   
    var pos = -1; 
    
    for (var i=0; i< xmlreqs.length; i++) 
    { 
        
        if (xmlreqs[i].freed == 1) 
        { 
            pos = i; 
            break;
        } 
    }
    
    if (pos == -1) 
    { 
        pos = xmlreqs.length; 
        xmlreqs[pos] = new CXMLReq(0, originalDivPrefix, newDivPrefix, imageDivPrefix, ajaxFinalHandlerObj); 
    }
    else
    {
        xmlreqs[pos].originalDivPrefix          = originalDivPrefix;
        xmlreqs[pos].newDivPrefix               = newDivPrefix;
        xmlreqs[pos].imageDivPrefix             = imageDivPrefix;
        xmlreqs[pos].ajaxFinalHandlerObject     = ajaxFinalHandlerObj;
    }
    
    if (xmlreqs[pos].xmlHttp) 
    {
        
        xmlreqs[pos].freed = 0;
        divPosMap[divid] = [pos];
        
        if(xmlreqs[pos].xmlHttp.readyState == 4 || xmlreqs[pos].xmlHttp.readyState == 0)
        {
            xmlreqs[pos].divID        = divid;
            
            // we shall send using GET
            var str = cgiCode;
            
            count = 0;
            for(var code in cgiArray)
            {
                str += code + '=' + encodeURIComponent(cgiArray[code]) ;
                count++;
                if(count < arrayCount)
                    str += '&';
            }
            
            xmlreqs[pos].xmlHttp.open('GET', str, true);
        
            // handler for receiving data from the server
            xmlreqs[pos].xmlHttp.onreadystatechange = function() 
            { 
                if (typeof(handleRequestStateChange) != 'undefined') 
                { 
                    handleRequestStateChange(pos); 
                } 
            }
            
            xmlreqs[pos].ajaxTimerID = window.setInterval("ajaxTimeOut()", ajaxTimerDelay, pos);
            
            // invoke the server
            xmlreqs[pos].xmlHttp.send(null);
        }
        else
        {
            // if connection is busy, try again after 1 second
            xmlreqs[pos].freed = 1;
            
            setTimeout('ajaxSubmit(cgiCode, cgiArray, originalDivPrefix, newDivPrefix, imageDivPrefix, divid, arrayCount);', 1000)
        }
    }
}

// ajax business ends here
function hideExpandedDivAJAX(divID)
{
    var contentOriginal = 'div_original_' + divID;
    var contentNew = 'div_expanded_' + divID;
    
    showHideDivs(contentOriginal, contentNew);
}

function jsCancelMessageBox()
{
    var d=document.getElementById("btc");
     
    if(d.childNodes.length > 0)
    {
        d.removeChild(d.firstChild);
    }

    // unlock the window input
    document.getElementById("modalBackground").style.display = "none";
    
    // clearInterval(scrollInterval);
}

function jsCloseModal(divId)
{
    // is there any pos element in the map ?
    if(divId in divPosMap)
    {
        if(divPosMap[divId] != -1)
        {
            pos = divPosMap[divId];
            xmlreqs[pos].xmlHttp.abort();    
            xmlreqs[pos].postHandleRequestChange(null, 0, '');
            
            return;
        }
    }
    
    var d=document.getElementById("btc");
    
    // get all ajax message tags inside this element (if any) and clear the status
    ajaxMsgBoxes = getElementsByClassAndNodeName('ajax_status_box', d);
    
    for(i=0; i<ajaxMsgBoxes.length; i++){
            ajaxMsgBoxes[i].innerHTML = '';
        }
        
    if(d.childNodes.length > 0)
        d.removeChild(d.firstChild);
        
    // unlock the window input
    document.getElementById("modalBackground").style.display = "none";
    
    // clearInterval(scrollInterval);
}

function handleUploadComplete(uploadStatus, divID, fileID, fileName)
{
    // it is possible that the upload failed
    // in that case, we can only know the divID from the global
    // variable, because the POST (that has the actual divid) did not complete
    
    if(divID == '#error_div_id')
    {
        divID       = gDivId;
        fileName    = '';
        fileID      = '';
    }
    else
    {
        document.forms['profile'].filename.value            = fileName;
        document.forms['profile'].filenameinform.value      = fileName;
        document.forms['profile'].fileid.value              = fileID;
        
        // if we have a successful upload, we should disable
        // the resume field and show special message
        if(fileName.length != 0)
        {
            // set a special message for the resume field
            document.forms['profile'].resume.value  = "** Please remove uploaded file (by clicking on the Remove File link) if you wish to copy-paste resume **";
            
            // disable it
            document.forms['profile'].resume.disabled = true;
            
            // show the Remove button
            getElement('remove_upload_div').style.display = 'inline';
            
            // other than this, for successful upload
            // we need to hide the upload mechanismand show success message
            
            var uploadDivID         = "uploadfile_form_" + divID;
            var uploadSuccessDivID  = "uploadfile_success_" + divID;
            
            var uploadMsgID = "uploadmsg_success_" + divID;
            var msgElement = getAjaxMsgElement(uploadMsgID);
            
            if(msgElement != null)
                msgElement.innerHTML = uploadStatus;
                
            // hide the upload div
            if(getElement(uploadDivID) != null)
        	   getElement(uploadDivID).style.display = 'none';

            // show the success message div
            if(getElement(uploadSuccessDivID) != null)
        	   getElement(uploadSuccessDivID).style.display = 'block';
        }
        else
        {
            // enable the disabled resume field
            document.forms['profile'].resume.disabled = false;
            
            // blank it out
            document.forms['profile'].resume.value  = "";
        }
    }
    
    var imageDiv   = 'ajax_img_' + divID;
    var uploadDiv  = 'ajax_upload_' + divID;
    
    showHideDivs(uploadDiv, imageDiv);
    
    // var msgElement = getAjaxMsgElement(uploadDiv);
    
    var uploadMsgID = "uploadmsg_" + divID;
    var msgElement = getAjaxMsgElement(uploadMsgID);
    
    if(msgElement != null)
        msgElement.innerHTML = uploadStatus;
}

function removeUploadedFile()
{
    document.forms['profile'].filename.value            = '';
    document.forms['profile'].filenameinform.value      = '';
    document.forms['profile'].fileid.value              = '';
    
    // enable the disabled resume field
    document.forms['profile'].resume.disabled = false;
    
    // blank it out
    document.forms['profile'].resume.value  = "";
    
    getElement('remove_upload_div').style.display = 'none';
}

function AJAX_CancelResumeUpload(divId)
{
    if(divId in divPosMap)
    {
        if(divPosMap[divId] != -1)
        {
            pos = divPosMap[divId];
            xmlreqs[pos].xmlHttp.abort();    
            xmlreqs[pos].postHandleRequestChange(null, 0, '');
            
            return;
        }
    }
    
    // simulate the browser stop
    // currently works only in IE and Firefox/Mozilla
    // browser_version= parseInt(navigator.appVersion);
	browser_type = navigator.appName;
	
	if(browser_type == "Microsoft Internet Explorer")
	{
	    document.execCommand('Stop');
	}
	else
	{
	    window.stop();
	}
	
	var imageDiv   = 'ajax_img_' + divId;
    var uploadDiv  = 'ajax_upload_' + divId;
    
    showHideDivs(uploadDiv, imageDiv);
    
    var msgElement = getAjaxMsgElement(uploadDiv);
    if(msgElement != null)
        msgElement.innerHTML = 'Upload Cancelled';
}

function UploadResume_AJAX(divid)
{
    var uploadForm = document.getElementById('uploadresume');
    if(uploadForm == null)
        return;
        
    if(trim(document.forms['uploadresume'].userfile.value) == '')
    {
        alert("Please specify a file for upload");
        return;   
    }
    
    var imageDiv   = 'ajax_img_' + divid;
    var uploadDiv  = 'ajax_upload_' + divid;
    
    // keep a global backup for error case
    gDivId = divid;
    
    showHideDivs(imageDiv, uploadDiv);
    
    // clear the message element contents here
    var msgElement = getAjaxMsgElement(uploadDiv);
    if(msgElement != null)
        msgElement.innerHTML = '';
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    
    var cgiArray = new Array();
    cgiArray['function']    = 'ajax_uploadresume';
    cgiArray['divid']       = divid;
    
    document.getElementById('uploadresume').submit();
    
    // ajaxSubmit(cgiCode, cgiArray, 'ajax_upload_', 'ajax_upload_', 'ajax_img_', divid, 2);
}

function SaveSearchOverWrite_AJAX(searchname, type, divid)
{
    var imageDiv   = 'div_ajax_img_' + divid;
    showHideDivs(imageDiv, '');
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    cgiArray['function']    = 'ajax_savesearch';
    cgiArray['overwrite']   = 1;
    cgiArray['divid']       = divid;
    cgiArray['type']        = type;
    cgiArray['searchname']  = searchname;
    
    ajaxSubmit(cgiCode, cgiArray, 'div_ajax_', 'div_ajax_', 'div_ajax_img_', divid, 5, new DefaultAJAXEndCallHandler());
}

function SaveSearchOverWrite_Close(divid)
{
    var msgDiv = getAjaxMsgElement('div_ajax_' + divid);
    msgDiv.innerHTML = '';
}

function SaveSearch_AJAX(formid, divid)
{
    var imageDiv   = 'div_ajax_img_' + divid;
    showHideDivs(imageDiv, '');
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    cgiArray['function']    = 'ajax_savesearch';
    cgiArray['divid']       = divid;
    cgiArray['type']        = document.forms[formid].elements['type'].value;
    cgiArray['searchname']  = document.forms[formid].elements['searchname'].value;
    
    ajaxSubmit(cgiCode, cgiArray, 'div_ajax_', 'div_ajax_', 'div_ajax_img_', divid, 4, new DefaultAJAXEndCallHandler());
}

function ApplyJob_AJAX(jobid, divid)
{
    var targetDiv = 'div_ajax_' + divid;
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']    = 'ajax_applyjob';
    cgiArray['divid']       = divid;
    cgiArray['jobid']       = jobid;
    
    // show the ajax loading image
    // hide the contents div
    var imageDiv   = 'div_ajax_img_' + divid;
    
    showHideDivs(imageDiv, targetDiv);
    
    ajaxSubmit(cgiCode, cgiArray, 'div_ajax_', 'div_ajax_', 'div_ajax_img_', divid, 3, new DefaultAJAXEndCallHandler());
}

function EnableDisableAlert_AJAX(createdOn, divid)
{
    var targetDiv = 'div_ajax_' + divid;
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']    = 'ajax_enabledisablealert';
    cgiArray['divid']       = divid;
    cgiArray['createdon']   = createdOn;
    
    // show the ajax loading image
    // hide the contents div
    var imageDiv   = 'div_ajax_img_' + divid;
    
    showHideDivs(imageDiv, targetDiv);
    
    ajaxSubmit(cgiCode, cgiArray, 'div_ajax_', 'div_ajax_', 'div_ajax_img_', divid, 3, new DefaultAJAXEndCallHandler());
}

function StarJob_AJAX(jobid, divid)
{
    var targetDiv = 'div_ajax_' + divid;
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']    = 'ajax_starjob';
    cgiArray['divid']       = divid;
    cgiArray['jobid']       = jobid;
    
    ajaxSubmit(cgiCode, cgiArray, 'div_ajax_', 'div_ajax_', '', divid, 3, new DefaultAJAXEndCallHandler());
}

function StarApplicant_AJAX(jobseekerid, divid)
{
    var targetDiv = 'div_ajax_' + divid;
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']    = 'ajax_starjobseeker';
    cgiArray['divid']       = divid;
    cgiArray['jobseekerid'] = jobseekerid;
    
    ajaxSubmit(cgiCode, cgiArray, 'div_ajax_', 'div_ajax_', '', divid, 3, new DefaultAJAXEndCallHandler());
}

function StarRecruiter_AJAX(recruiterid, divid)
{
    var targetDiv = 'div_ajax_' + divid;
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']    = 'ajax_starrecruiter';
    cgiArray['divid']       = divid;
    cgiArray['recruiterid'] = recruiterid;
    
    ajaxSubmit(cgiCode, cgiArray, 'div_ajax_', 'div_ajax_', '', divid, 3, new DefaultAJAXEndCallHandler());
}

function ValidateRecruiter_AJAX(divid)
{    
    var formid    = 'form_' + divid;
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']    = 'ajax_validaterec';
    cgiArray['divid']       = divid;
    cgiArray['recid']       = document.forms[formid].elements['recid'].value;;
    
    var linkDiv    = 'div_ajax_'  + divid;
    var imageDiv   = 'div_ajax_img_' + divid;
    
    showHideDivs(imageDiv, linkDiv);
    
    ajaxSubmit(cgiCode, cgiArray, 'div_ajax_', 'div_ajax_', 'div_ajax_img_', divid, 3, new DefaultAJAXEndCallHandler());
}

function MakeJobPremium_AJAX(divid)
{    
    var formid    = 'form_' + divid;
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']    = 'ajax_makejobpremium';
    cgiArray['divid']       = divid;
    cgiArray['jobid']       = document.forms[formid].elements['jobid'].value;;
    
    var linkDiv    = 'div_ajax_'  + divid;
    var imageDiv   = 'div_ajax_img_' + divid;
    
    showHideDivs(imageDiv, linkDiv);
    
    ajaxSubmit(cgiCode, cgiArray, 'div_ajax_', 'div_ajax_', 'div_ajax_img_', divid, 3, new DefaultAJAXEndCallHandler());
}

function DeleteJob_AJAX(divid)
{    
    var formid    = 'form_' + divid;
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']    = 'ajax_deletejob';
    cgiArray['divid']       = divid;
    cgiArray['jobid']       = document.forms[formid].elements['jobid'].value;;
    
    var linkDiv    = 'div_ajax_'  + divid;
    var imageDiv   = 'div_ajax_img_' + divid;
    
    showHideDivs(imageDiv, linkDiv);
    
    ajaxSubmit(cgiCode, cgiArray, 'div_ajax_', 'div_ajax_', 'div_ajax_img_', divid, 3, new DefaultAJAXEndCallHandler());
}

function DeleteUser_AJAX(divid)
{    
    var formid    = 'form_' + divid;
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']    = 'ajax_deleteuser';
    cgiArray['divid']       = divid;
    cgiArray['userid']      = document.forms[formid].elements['userid'].value;;
    
    var linkDiv    = 'div_ajax_'  + divid;
    var imageDiv   = 'div_ajax_img_' + divid;
    
    showHideDivs(imageDiv, linkDiv);
    
    ajaxSubmit(cgiCode, cgiArray, 'div_ajax_', 'div_ajax_', 'div_ajax_img_', divid, 3, new DefaultAJAXEndCallHandler());
}

function deleteLabel_AJAX(labelName)
{
    var cgiCode  = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    var divid    = 'id_deletelabel';
    
    cgiArray['function']    = 'ajax_deletelabel';
    cgiArray['divid']       = divid;

    cgiArray['label']       = labelName;
    
    // show the ajax loading image
    // hide the contents div
    var imageDiv   = 'ajax_img_'               + divid;
    var btnDiv     = 'ajax_deletelabel_btns_'  + divid;
    
    showHideDivBlocks(imageDiv, btnDiv);
    
    ajaxSubmit(cgiCode, cgiArray, '#none#', '#none#', '#none#', divid, 3, new DeleteLabelAJAXEndCallHandler(cgiArray['label']));
}

function renameLabel_AJAX()
{
    var cgiCode  = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    var divid    = 'id_renamelabel';
    
    var formid   = 'renamelabel_submit_form_' + divid;
    
    cgiArray['function']    = 'ajax_renamelabel';
    cgiArray['divid']       = divid;

    cgiArray['oldlabel']    = document.forms[formid].elements['oldlabel'].value;
    cgiArray['newlabel']    = document.forms[formid].elements['newlabel'].value;
    
    // show the ajax loading image
    // hide the contents div
    var imageDiv   = 'ajax_img_'               + divid;
    var btnDiv     = 'ajax_deletelabel_btns_'  + divid;
    
    showHideDivBlocks(imageDiv, btnDiv);
    
    ajaxSubmit(cgiCode, cgiArray, '#none#', '#none#', '#none#', divid, 4, new RenameLabelAJAXEndCallHandler(cgiArray['oldlabel'], cgiArray['newlabel']));
}

function AddLabel_AJAX(divid)
{
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']    = 'ajax_addlabel';
    cgiArray['divid']       = divid;
    
    var formid              = 'addlabel_submit_form_' + divid;
    cgiArray['label']       = document.forms[formid].elements['label'].value;
    
    // show the ajax loading image
    // hide the contents div
    var imageDiv   = 'ajax_img_' + divid;
    var btnDiv     = 'ajax_addlabel_btns_' + divid;
    
    showHideDivBlocks(imageDiv, btnDiv);
    
    ajaxSubmit(cgiCode, cgiArray, '#none#', '#none#', '#none#', divid, 3, new AddLabelAJAXEndCallHandler(cgiArray['label']));
}

function submitAddLabelAJAX(e, divID)
{
	 var code;
	 if (!e) var e = window.event;
	 if (e.keyCode) code = e.keyCode;
	 else if (e.which) code = e.which;
	 	 
	 if(code == 13){
	     
	 	 // encryptLoginPassword(document.forms[formname]);
	 	 // var fptr = encryptLoginPassword;
	 	 AddLabel_AJAX(divID);
	 	 
 	     return false;
	 }
	 
	return true;
}

function tagIt_AJAX(type, id, label)
{
    if(label == '__#noaction#__')
        return;
    
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']   = 'ajax_applylabel';
    cgiArray['type']       = type;
    cgiArray['id']         = id;
    cgiArray['label']      = label;
    
    var selectCtrlID = 'dropdown_tag_select_' +  id;
    
    // cue to the user that we are processing ... 
    insertOptionNodeFirstPosition(getElement(selectCtrlID), createSelectNodeProcessing("Processing ..."));
    
    // explicitly select the first node (that is the processing node)
    selectFirstOption(getElement(selectCtrlID));
    
    // disable the select control while we are processing
    
    getElement(selectCtrlID).disabled = true;
    
    ajaxSubmit(cgiCode, cgiArray, '#none#', '#none#', '#none#', '#none#', 4, new ApplyLabelAJAXEndCallHandler(id, label));
}

function removeTag_AJAX(id, label)
{
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']   = 'ajax_removelabel';
    cgiArray['id']         = id;
    cgiArray['label']      = label;
    
    ajaxSubmit(cgiCode, cgiArray, '#none#', '#none#', '#none#', '#none#', 3, new RemoveLabelAJAXEndCallHandler(id, label));
}

function submitRenameLabelAJAX(e)
{
	 var code;
	 if (!e) var e = window.event;
	 if (e.keyCode) code = e.keyCode;
	 else if (e.which) code = e.which;
	 	 
	 if(code == 13){
	     
	 	 // encryptLoginPassword(document.forms[formname]);
	 	 // var fptr = encryptLoginPassword;
	 	 renameLabel_AJAX();
	 	 
 	     return false;
	 }
	 
	return true;
}

function showPreviewByID_AJAX(type, divid, objid)
{
    var contentNew = 'div_expanded_' + divid;
    
    // optimize
    // if the expanded div already has contents, then do not need to invoke ajax
    if(getElement(contentNew) != null)
    {
	   if(trim(getElement(contentNew).innerHTML).length != 0)
	   {
	       var contentOriginal = 'div_original_' + divid;
	       showHideDivs(contentNew, contentOriginal);
	       return;
	   }
    }
    
    var imageDiv   = 'div_ajax_img_' + divid;
    
    // show the ajax loading image
    // do not hide the contents div
    showHideDivs(imageDiv, '');
    
    // ask the server side to process this
    var cgiCode = '/secure/AJAX/ajaxprocess.php?';
    var cgiArray = new Array();
    
    cgiArray['function']    = 'ajax_preview';
    cgiArray['type']        = type;
    cgiArray['divid']       = divid;
    cgiArray['objid']       = objid;
    
//    var promptString  = '<a class="clicklink" href="javascript:showPreviewByID_AJAX(';
//    promptString  += '\'' + type + '\'';
//    promptString  += ', ';
//    promptString  += '\'' + divid + '\'';
//    promptString  += ', ';
//    promptString  += '\'' + objid + '\'';
//    promptString  += ')">Show Details</a>';
    
    //<a class="clicklink" href="javascript:showPreviewByID_AJAX('jobdesc', {t_unique_desc}', '{t_jobid}')">
	//		  Show Details
	//	    </a>
    
    ajaxSubmit(cgiCode, cgiArray, 'div_original_', 'div_expanded_', 'div_ajax_img_', divid, 4, new DefaultAJAXEndCallHandler());
}

function JSDeleteJob(jobId, pageLimit)
{
    document.forms['form_deletejob'].elements['id'].value = jobId;
    document.forms['form_deletejob'].elements['pagelimit'].value = pageLimit;
    
    document.forms['form_deletejob'].submit();
    
    // page=1&pagelimit=10&type=job&amp;id=rec@saayan.com:2008-04-09 14:30:40&function=deljob
}
