var request;
var searchWindows;
var DirListingWindow;
var MiddleColumnWindow;
var queryString;   //will hold the POSTed data

// This function will do the ajax post
function getData(url){
    httpRequest("POST",url,true);
}

function getURL(url) {
	//alert("sending get" + url);
    httpRequest("GET",url,true);
}

function getURL_p(query, url) {
	//alert("sending get" + url);
	if (confirm(query)) {
		httpRequest("GET",url,true);
	}
	return false;
}

function showList(url) {
	//alert("we're in showList!");
	if(typeof(url) != 'undefined') {
		//alert("return url is " + url);
		window.location=url;
	}
	else {
		window.location='/contacts';
	}
}

function doreload() {
	loadAJAX();
	hidePopupDiv();
}


//event handler for XMLHttpRequest
function handleResponse(){
    if(request.readyState == 4){
        if(request.status == 200){
           //alert("Text: " + request.responseText);
           //alert("XML: " + request.responseXML);
		   var info = request.responseText;
           var doc = request.responseXML;
           //var info = getDocInfo(doc);
		   searchWindows = 2;
		   var StartIdentifier = info.indexOf(':') + 1;
		   var EndIdentifier = info.indexOf('&');
		   var StartDivId = info.indexOf('&') + 1;
		   var EndDivId = info.indexOf('|');
		   var Startjs = info.indexOf('|') + 1;
		   var Endjs = info.indexOf('#');
		   var Identifier = info.substring(StartIdentifier,EndIdentifier);
		   var DivId = info.substring(StartDivId,EndDivId);
		   var runjs = info.substring(Startjs,Endjs);
		   //alert("Identifier: " + Identifier);
		   //alert("DivId: " + DivId);
		   //alert("runjs: " + runjs);
           if (Identifier == "AjaxLocation") {
			  // This just saves the current html in this div
              // MiddleColumnWindow = document.getElementById(DivId).innerHTML;
			  // Now we'll replace it with the new data
  		      //alert("info: " + info);
  		      //alert("DivId: " + DivId);
			  if (DivId == "addContact") {
		            //alert("info: " + info);
					//popWrapper.bindAsEventListener( null, 600, 600, info, 0.85, 1 );
		  		    //alert("DivId: " + DivId);
					stylizeDiv(info,document.getElementById(DivId));
					
					//PopDiv( 600, 600, $('addContact'), 1 );
			  }
			  else {
					stylizeDiv(info,document.getElementById(DivId));
			  }
		   }
		   if (runjs != "") {
		      eval( runjs );
		   }
        } else {
           alert("Text: " + request.responseText);
            alert("Sorry! An error occurred getting the item you requested. Please reclick the link to try again (" + request.status + ")");
        }
    }//end outer if
}


/* Initialize a Request object that is already constructed */
function initReq(reqType,url,bool){
    /* Specify the function that will handle the HTTP response */
    request.onreadystatechange=handleResponse;
    request.open(reqType,url,bool);
    request.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    /* Only works in Mozilla-based browsers */
    //request.overrideMimeType("text/XML");
    request.send(queryString);
}


/* Wrapper function for constructing a Request object.
 Parameters:
  reqType: The HTTP request type such as GET or POST.
  url: The URL of the server program.
  asynch: Whether to send the request asynchronously or not. */
function httpRequest(reqType,url,asynch){
    //Mozilla-based browsers
    if(window.XMLHttpRequest){
        request = new XMLHttpRequest();
    } else if (window.ActiveXObject){
        request=new ActiveXObject("Msxml2.XMLHTTP");
        if (! request){
            request=new ActiveXObject("Microsoft.XMLHTTP");
        }
     }
    //the request could still be null if neither ActiveXObject
    //initializations succeeded
    if(request){
       initReq(reqType,url,asynch);
    }  else {
        alert("Your browser does not permit the use of all "+
        "of this application's features!");}
}

function setQueryString(){
    queryString="";
    //var frm = document.forms[1];
	// This sets the sorce form where data will be gathered, we're using categories form
    var frm = document.categories;
    var numberElements =  frm.elements.length;
    for(var i = 0; i < numberElements; i++)  {
            if(i < numberElements-1)  {
                queryString += frm.elements[i].name+"="+
                               encodeURIComponent(frm.elements[i].value)+"&";
            } else {
                queryString += frm.elements[i].name+"="+
                               encodeURIComponent(frm.elements[i].value);
            }

    }
}


function setFormData(formId){
    queryString="";
    //var frm = document.forms[1];
	// This sets the sorce form where data will be gathered, we're using categories form
    var frm = document.forms[formId];
    var numberElements =  frm.elements.length;
    for(var i = 0; i < numberElements; i++)  {
            if(i < numberElements-1)  {
                queryString += frm.elements[i].name+"="+
                               encodeURIComponent(frm.elements[i].value)+"&";
            } else {
                queryString += frm.elements[i].name+"="+
                               encodeURIComponent(frm.elements[i].value);
            }

    }
}


function clearDiv(DivId){
    //reset DIV content
	div = document.getElementById(DivId)
    div.innerHTML="";
}

function stylizeDiv(bdyTxt,div){
    //reset DIV content
    div.innerHTML="";
    div.style.backgroundColor="";
     div.innerHTML=bdyTxt;
}

function getDocInfo(doc){
    var root = doc.documentElement;
     var info = "";
     var nds;
     if(root.hasChildNodes())  {
           nds=root.childNodes;
           //info+= "<h4>Root node's child node names/values:<h4/>";
           for (var i = 0; i < nds.length; i++){
               //info+=  nds[i].nodeName;
               if(nds[i].hasChildNodes()){
                  info+=  nds[i].firstChild.nodeValue+"<br />";
               } else {
                  info+=  " <br />";
               }
           }
    }
    return info;
}

function contactAdded() {
	activatePopupDivs();
	fdTableSort.init();
	fdTableSort.jsWrapper('cclist', [1]);
}

function contactsTableLoaded() {
	activatePopupDivs();
	fdTableSort.init();
	fdTableSort.jsWrapper('cclist', [1]);
	fdTableSort.jsWrapper('list', [1]);
}

function contactsTableLoadNext(CP1id) {
	activatePopupDivs();
	fdTableSort.init();
	getURL('/contacts/getContacts/' + CP1id);
}

