var gMediaDoc = null;
var gClientCallback = null;
var gMediaCallback = null;;

function showRegistrantInfo(reg_info_url) {  
    var cid = getObj("CID").value;
    
    var cacheKiller = new Date().getTime(); // Make url unique to prevent loading it from cache
    var url = reg_info_url + "?USERNAME=" + getObj("loginusername").value + "&PASSWORD=" 
    + getObj("loginpassword").value + "&CID=" + cid + "&" + cacheKiller;
    
    loadXMLDocument(url, onRegistrantLoaded);       
}

function showRegistrantInfoWithCallback(callback, reg_info_url) {  
    var cid = getObj("CID").value;
    
    var cacheKiller = new Date().getTime(); // Make url unique to prevent loading it from cache
    var url = reg_info_url + "?USERNAME=" + getObj("loginusername").value + "&PASSWORD=" 
    + getObj("loginpassword").value + "&CID=" + cid + "&" + cacheKiller;
    
    gClientCallback = callback;
    loadXMLDocument(url, onRegistrantLoaded);   
}

function onRegistrantLoaded(aDoc)
{
    if (!aDoc || !aDoc.documentElement) {
        return;
    }
    
    //place current username and password in form for 
    //verification on server
    getObj("CURRENT_USERNAME").value = getObj("loginusername").value;
    getObj("CURRENT_PASSWORD").value = getObj("loginpassword").value;
    
    var child = aDoc.documentElement.firstChild;
    while (child) {
	var text = child.firstChild;

	if (text!=null) {

        if (child.nodeName=="LoginFailed") {
            getObj("CURRENT_USERNAME").value = "failed";
            break;
        }
        
        if (child.nodeName=="ID") {
            getObj("REGISTRANT_ID").value = text.nodeValue;
        }
        
        if (child.nodeName=="FirstName") {
            var firstname = getObj("txtFirstName");
            if (firstname!=null) {	
                firstname.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="LastName") {
            var lastname = getObj("txtLastName");
            if (lastname!=null) {
                lastname.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="Username") {
            var username = getObj("txtUsername");
            if (username!=null) {
                username.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="Password") {
            var password = getObj("txtPassword");
            if (password!=null) {
                password.value = text.nodeValue;
            }
            
            var passwordknowsme3 = getObj("txtPasswordKnowsMe3");
            if (passwordknowsme3!=null) {
                passwordknowsme3.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="Address1") {
            var address1 = getObj("txtAddress1"); 
            if (address1!=null) {
                address1.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="Address2") {
            var address2 = getObj("txtAddress2");
            if (address2!=null) {
                address2.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="City") {
            var city = getObj("txtCity");
            if (city!=null) {
                city.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="Province") {
            var province = getObj("txtProvince");
            if (province!=null) {
                province.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="PostalCode") {
            var postalcode = getObj("txtPostalCode");
            if (postalcode!=null) {
                postalcode.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="Phone") {
            var phone = getObj("txtPhone");
            if (phone!=null) {
                phone.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="Phone2") {
            var phone2 = getObj("txtPhone2");
            if (phone2!=null) {
                phone2.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="Fax") {
            var fax = getObj("txtFax");
            if (fax!=null) {
                fax.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="Email") {
            var email = getObj("txtEmail");
            if (email!=null) {
                email.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="CompanyName") {
            var companyname = getObj("txtCompanyName");
            if (companyname!=null) {
                companyname.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="Title") {
            var title = getObj("txtTitle");
            if (title!=null) {
                title.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="FullName") {
            var fullname = getObj("txtFullName");
            if (fullname!=null) {
                fullname.value = text.nodeValue;
            }
        }
        
        if (child.nodeName=="OptedIn") {
            var optin = getObj("chkOptIn");
            if (optin!=null) {
                if (text.nodeValue==1) {
                    optin.checked = true; 
                } else {
                    optin.checked = false;
                }
            }
        }
       
        //country is a drop down
        if (child.nodeName=="Country") {
            var country = getObj("ddCountry");
            if (country!=null) {
                for (var i=0; i<country.options.length; i++) {
                    if (country.options[i].text == text.nodeValue) {
                        country.selectedIndex=i;
                        break;
                    }
                }
            }
        }
        
        //preferences
        if (child.nodeName=="Preferences") {
            //get selected preferences from xml element
            var pref = child.firstChild;   
            while (pref) {
		text = pref.firstChild;
                checks = document.getElementsByName("PREFERENCE");
                if (checks) {      
                    for (var i = 0; i<checks.length; i++) {
                        if (text.nodeValue==checks[i].value) {
                            checks[i].checked = true;
                            break;
                        }
                    }
                }
                pref = pref.nextSibling;
            }
        }
        
        //visitor type
        if (child.nodeName=="VisitorType") {
            radios = document.getElementsByName("VISITOR_TYPE");
            if (radios) {
                for (var i = 0; i<radios.length; i++) {
                    if (text.nodeValue==radios[i].value) {
                        radios[i].checked = true;
                        break;
                    }
                }
            }
        }
          
	}

        child = child.nextSibling;
    }
    
    if (gClientCallback) {
      gClientCallback();
    }
}

/////////////////////////////////////////////////////////////////////
//// XML Document loading

function loadXMLDocument(aURL, aCallback)
{ 
  gMediaCallback = aCallback;
  
  if (window.ActiveXObject) {
    // Internet Explorer XML loading syntax
    gMediaDoc = new ActiveXObject(getControlPrefix() + ".XmlDom");
    gMediaDoc.onreadystatechange = onMediaReadyStateChange;
    gMediaDoc.async = true;
    gMediaDoc.load(aURL);
  } else {
    // Mozilla XML loading syntax
    gMediaDoc = document.implementation.createDocument("", "", null);
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.overrideMimeType("text/xml");
    xmlHttp.open("GET", aURL, false);
    xmlHttp.send(null);
    gMediaDoc.loadXML(xmlHttp.responseXML.xml); 
    onMediaLoaded();
  }

}

function onMediaLoaded()
{
  if (gMediaCallback) {
    gMediaCallback(gMediaDoc);
  }
}

function onMediaReadyStateChange()
{
  if (gMediaDoc.readyState == 4)
    onMediaLoaded();
}

/////////////////////////////////////////////////////////////////////
//// XML helper courtesy of http://webfx.eae.net/

function getControlPrefix()
{
  if (getControlPrefix.prefix)
    return getControlPrefix.prefix;

  var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
  var o, o2;
  for (var i = 0; i < prefixes.length; i++) {
    try {
      // try to create the objects
      o = new ActiveXObject(prefixes[i] + ".XmlHttp");
      o2 = new ActiveXObject(prefixes[i] + ".XmlDom");
      return getControlPrefix.prefix = prefixes[i];
    } catch (ex) { };
  }

  throw new Error("Could not find an installed XML parser");
}

// used to find the Automation server name
function getDomDocumentPrefix() {
	if (getDomDocumentPrefix.prefix)
		return getDomDocumentPrefix.prefix;
	
	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var o;
	for (var i = 0; i < prefixes.length; i++) {
		try {
			// try to create the objects
			o = new ActiveXObject(prefixes[i] + ".DomDocument");
			return getDomDocumentPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}
	
	throw new Error("Could not find an installed XML parser");
}

function getXmlHttpPrefix() {
	if (getXmlHttpPrefix.prefix)
		return getXmlHttpPrefix.prefix;
	
	var prefixes = ["MSXML2", "Microsoft", "MSXML", "MSXML3"];
	var o;
	for (var i = 0; i < prefixes.length; i++) {
		try {
			// try to create the objects
			o = new ActiveXObject(prefixes[i] + ".XmlHttp");
			return getXmlHttpPrefix.prefix = prefixes[i];
		}
		catch (ex) {};
	}
	
	throw new Error("Could not find an installed XML parser");
}

//////////////////////////
// Start the Real stuff //
//////////////////////////


// XmlHttp factory
function XmlHttp() {}

XmlHttp.create = function () {
	try {
		if (window.XMLHttpRequest) {
			var req = new XMLHttpRequest();
			
			// some versions of Moz do not support the readyState property
			// and the onreadystate event so we patch it!
			if (req.readyState == null) {
				req.readyState = 1;
				req.addEventListener("load", function () {
					req.readyState = 4;
					if (typeof req.onreadystatechange == "function")
						req.onreadystatechange();
				}, false);
			}
			
			return req;
		}
		if (window.ActiveXObject) {
			return new ActiveXObject(getXmlHttpPrefix() + ".XmlHttp");
		}
	}
	catch (ex) {}
	// fell through
	throw new Error("Your browser does not support XmlHttp objects");
};

// XmlDocument factory
function XmlDocument() {}

XmlDocument.create = function () {
	try {
		// DOM2
		if (document.implementation && document.implementation.createDocument) {
			var doc = document.implementation.createDocument("", "", null);
			
			// some versions of Moz do not support the readyState property
			// and the onreadystate event so we patch it!
			if (doc.readyState == null) {
				doc.readyState = 1;
				doc.addEventListener("load", function () {
					doc.readyState = 4;
					if (typeof doc.onreadystatechange == "function")
						doc.onreadystatechange();
				}, false);
			}
			
			return doc;
		}
		if (window.ActiveXObject)
			return new ActiveXObject(getDomDocumentPrefix() + ".DomDocument");
	}
	catch (ex) {}
	throw new Error("Your browser does not support XmlDocument objects");
};

// Create the loadXML method and xml getter for Mozilla
if (window.DOMParser &&
	window.XMLSerializer &&
	window.Node && Node.prototype && Node.prototype.__defineGetter__) {

	// XMLDocument did not extend the Document interface in some versions
	// of Mozilla. Extend both!
	//XMLDocument.prototype.loadXML = 
	Document.prototype.loadXML = function (s) {
		
		// parse the string to a new doc	
		var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
		
		// remove all initial children
		while (this.hasChildNodes())
			this.removeChild(this.lastChild);
			
		// insert and import nodes
		for (var i = 0; i < doc2.childNodes.length; i++) {
			this.appendChild(this.importNode(doc2.childNodes[i], true));
		}
	};
	
	
	/*
	 * xml getter
	 *
	 * This serializes the DOM tree to an XML String
	 *
	 * Usage: var sXml = oNode.xml
	 *
	 */
	// XMLDocument did not extend the Document interface in some versions
	// of Mozilla. Extend both!
	/*
	XMLDocument.prototype.__defineGetter__("xml", function () {
		return (new XMLSerializer()).serializeToString(this);
	});
	*/
	Document.prototype.__defineGetter__("xml", function () {
		return (new XMLSerializer()).serializeToString(this);
	});
}