//debug
//var host = "/DropdownXML";

function loadXMLDoc (url, dropdownSet, controlIndex, baseUrl) 
{
	this.dropdownSet = dropdownSet;
	this.controlIndex = controlIndex;
	this.url = url;
	this.baseUrl = baseUrl;
	/* branch for native XMLHttpRequest object */
	if (window.XMLHttpRequest) 
	{
		this.req = new XMLHttpRequest ();		
		var self = this;
		this.req.onreadystatechange = function ()
		{
			ProcessXML (self);
		}
		this.req.open ("GET", url, true);
		this.req.send (null);
	} 
	/* branch for IE/Windows ActiveX version */
	else if (window.ActiveXObject) 
	{
		this.req = new ActiveXObject ("Microsoft.XMLHTTP");
		var self = this;
		if (this.req) 
		{
			this.req.onreadystatechange = function ()
			{
				ProcessXML (self);
			}
			this.req.open ("GET", url, true);
			this.req.send ();
		}
	}
}

function urlencode(str) 
{
    return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

function LogError (errorCode, errorUrl, errorText)
{
    var errorReportUrl = "/pages/jsErrorLogger.aspx";
    var errorParams = "errorCode=" + urlencode (errorCode) + "&errorUrl=" + urlencode (errorUrl);
    if (window.XMLHttpRequest) 
	{
	    var errorReq = new XMLHttpRequest ();	
		errorReq.open ("GET", errorReportUrl, true);
	    errorReq.setRequestHeader("ErrorText", urlencode(errorText));
	    errorReq.setRequestHeader("ErrorCode", urlencode(errorCode));
	    errorReq.setRequestHeader("ErrorUrl", urlencode(errorUrl));
	    alert (errorParams);
		errorReq.send (null);
	} 
	else if (window.ActiveXObject) 
	{
		var errorReq = new ActiveXObject ("Microsoft.XMLHTTP");
		errorReq.open ("GET", errorReportUrl, true);
	    errorReq.setRequestHeader("ErrorText", urlencode(errorText));
	    errorReq.setRequestHeader("ErrorCode", urlencode(errorCode));
	    errorReq.setRequestHeader("ErrorUrl", urlencode(errorUrl));
		errorReq.send ();
	}
}

function ProcessXML (self)
{
	var controlIndex = self.controlIndex;
	/* only if req shows "complete" */
	if (self.req.readyState == 4) 
	{
		/* only if "OK" */
		if (self.req.status == 200) 
		{
			if (self.dropdownSet.ConsistencyCheckRecursive (self.url, controlIndex) == false)
				return;
			
			var response = self.req.responseText;
			
			if ((self.dropdownSet.urlList[controlIndex] == "JATOImage.aspx") ||
				(self.dropdownSet.urlList[controlIndex] == "NewCarImage.aspx"))
			{
				var control = self.dropdownSet.GetElement (self.dropdownSet.controlList[controlIndex]);
				control.src = self.dropdownSet.initValueList[controlIndex] + response;
			}
			else
			{
				var tabbedLists = response.split ("\n");
				if (tabbedLists.length >= 2)
				{
					var tags = tabbedLists[0].split ("\t");
					var valueTags = tabbedLists[1].split ("\t");

					if (tags.length != valueTags.length)
						return;
				    var control = self.dropdownSet.GetElement (self.dropdownSet.controlList[controlIndex]);
					if (control == null)
					    return;			
					control.length = 0;
					for (var i = 0; i < tags.length; i++)
					{
						if ((tags[i] != null && tags[i] != "") || (valueTags[i] != null && valueTags[i] != ""))
						{							
							control.options[control.options.length] = new Option (tags[i], valueTags[i]);							
					    }
					}
			
					control.disabled = false;
					
					for (i = 0; i < control.length && control.selectedIndex == 0; i++)
					{
						tempControlValue = control.options[i].value;
						if ((tempControlValue != null) && (tempControlValue.indexOf ("|") >= 0))
							tempControlValue = tempControlValue.substring (0, tempControlValue.indexOf ("|"));
						if (tempControlValue.toLowerCase() == self.dropdownSet.initValueList[controlIndex].toLowerCase())
							control.selectedIndex = i;
					}
					if (control.value != "")
					{
						hiddenControl = this.GetElement (self.dropdownSet.hiddenControlIdValueList[controlIndex][1]);
						hiddenControl.value = control.value;
						if ((hiddenControl.value != null) && (hiddenControl.value.indexOf ("|") >= 0))
							hiddenControl.value = hiddenControl.value.substring (0, hiddenControl.value.indexOf ("|"));
						self.dropdownSet.DropdownOnChange (controlIndex);
					}
				}
			}
		} 
		else 
		{
		    LogError (self.req.statusText, self.url, self.req.responseText);
		    alert("error: " + self.req.statusText);
		}
	}
}

function DropdownOnChange (index)
{
	this.InitControlRecursive (index);
	control = this.GetElement (this.controlList[index]);
	hiddenControlId = this.GetElement (this.hiddenControlIdValueList[index][0]);
	hiddenControlValue = this.GetElement (this.hiddenControlIdValueList[index][1]);					
	if ((hiddenControlId != null || hiddenControlValue != null) && control != null)
	{
	    if (hiddenControlValue != null)
	    {
	        hiddenControlValue.value = control.value;
		    if ((hiddenControlValue.value != null) && (hiddenControlValue.value.indexOf("|") >= 0))
		        hiddenControlValue.value = hiddenControlValue.value.substring (0, hiddenControlValue.value.indexOf ("|"));	    			    
	    }
	    if (hiddenControlValue != null && hiddenControlId != null && hiddenControlId.name != hiddenControlValue.name)
	    {
	        hiddenControlId.value = control.value;	        
		    if ((hiddenControlId.value != null) && (hiddenControlId.value.indexOf("|") >= 0))
			    hiddenControlId.value = hiddenControlId.value.substring (hiddenControlId.value.indexOf ("|")+1, hiddenControlId.value.length);		    
	    }
	}
	
	if ((control != null) && (control.value != ''))
	{
		this.initValueList[index] = control.value;
		for (var i = 0; i < this.childList[index].length; i++)
			this.PopulateDropdown (this.childList[index][i]);
	}
}

function DropdownSet (controlList, hiddenControlIdValueList, childList, parentList, urlList, displayValueList, nameTagList, initValueList, titleTagList, filterList, hostUrl, currentUrl, contentFilters, customScript, referenceType)
{    
	this.hostUrl = hostUrl
	this.controlList = controlList;
	this.hiddenControlIdValueList = hiddenControlIdValueList;
	this.childList = childList;
	this.parentList = parentList;
	this.urlList = urlList;
	this.displayValueList = displayValueList;
	this.nameTagList = nameTagList; 
	this.initValueList = initValueList;
	this.titleTagList = titleTagList;
	this.filterList = filterList;
	this.currentUrl = currentUrl;
	this.contentFilters = contentFilters;
	this.referenceType = referenceType;
	
	DropdownSet.prototype.DropdownOnChange = DropdownOnChange;
	DropdownSet.prototype.GetQueryString = GetQueryString;
	DropdownSet.prototype.PopulateDropdown = PopulateDropdown;
	DropdownSet.prototype.InitControlRecursive = InitControlRecursive;
	DropdownSet.prototype.InitControl = InitControl;
	DropdownSet.prototype.ConsistencyCheckRecursive = ConsistencyCheckRecursive;
	DropdownSet.prototype.GetParentQueryStringRecursive = GetParentQueryStringRecursive;
	DropdownSet.prototype.GetElement = GetElement;
	
	/* for postback, if hiddencontrol is already fill with values, use that instead of init values */
	for (var i = 1; i < this.controlList.length; i++)
	{
		var hiddenControl = this.GetElement (hiddenControlIdValueList[i][1]);	
		if ((hiddenControl != null) && (hiddenControl.value != ""))
		{
			initValueList[i] = hiddenControl.value;	
		}
	}
	
	this.InitControlRecursive ('0');
	
	if (customScript != null)
	{
	    eval(customScript);
	}
	for (i = 0; i < this.childList[0].length; i++)
		this.PopulateDropdown (this.childList[0][i]);
}

function InitControlRecursive (i)
{
	for (var j = 0; j < this.childList[i].length; j++)
	{
	    this.InitControl (this.controlList[this.childList[i][j]], this.hiddenControlIdValueList[this.childList[i][j]][1], this.displayValueList[this.childList[i][j]], this.titleTagList[this.childList[i][j]]);
		this.InitControlRecursive (this.childList[i][j]);
	}
}

function InitControl (controlId, hiddenControlId, displayedTag, titleTag)
{
    control = this.GetElement (controlId);
    hiddenControl = this.GetElement (hiddenControlId);
	
	if ((control != null) && (control.options != null))
	{
		control.length = 0;	
		if ((titleTag != null) && (titleTag != ""))
		    control.options[control.options.length] = new Option (titleTag);
		else
		    //control.options[control.options.length] = new Option ('Select ' + displayedTag, '');
		    control.options[control.options.length] = new Option (displayedTag, '');
		control.disabled = true;
	}
	if ((hiddenControl != null) && (control != null))
	{
		hiddenControl.value = control.value;
		if ((hiddenControl.value != null) && (hiddenControl.value.indexOf("|") >= 0))
			hiddenControl.value = hiddenControl.value.substring (0, hiddenControl.value.indexOf ("|"));
	}
}

function PopulateDropdown (i)
{
	var url = this.hostUrl + '/' + this.urlList[i] + '?' + this.GetQueryString (i);
	new loadXMLDoc (url, this, i, this.urlList[i]);
}

function ConsistencyCheckRecursive (url, i)
{
	if ((this.parentList[i] != null) && (this.parentList[i] != "") && (this.parentList[i] != "0"))
	{
		if ((url.indexOf (this.nameTagList[this.parentList[i]] + "=") < 0) || (url.indexOf (GetIndividualQueryString (this.nameTagList[this.parentList[i]], this.GetElement (this.controlList[this.parentList[i]]).value)) < 0))
			return false;
		else
			return this.ConsistencyCheckRecursive (url, this.parentList[i]);
	}
	return true;
}

function GetParentQueryStringRecursive (i)
{
	if (this.parentList[i] == 0)
		return "";
	else
		return GetIndividualQueryString (this.nameTagList[this.parentList[i]], this.GetElement (this.controlList[this.parentList[i]]).value) + this.GetParentQueryStringRecursive (this.parentList[i]);
}

function GetQueryString (i)
{
	queryString = this.GetParentQueryStringRecursive (i);
	for (i = 0; i < this.filterList.length; i++)
		queryString += GetIndividualQueryString (this.filterList[i][0], this.filterList[i][1]);
		
	return queryString + 'currentUrl=' + escape (this.currentUrl) + '&contentFilters=' + this.contentFilters + '&';
}

function GetIndividualQueryString (tag, value)
{
	if ((value != null) && (value != ""))
		return tag + '=' + escape (value) + '&';
	else return '';
}

function GetElement (id)
{
    if (this.referenceType == 'ByMboxControlId')
        return GetElementByMboxControlId (id);
    else
        return document.getElementById (id);
}

function GetElementByMboxControlId (id)
{
    var pattern = new RegExp ('\\b' + id + '\\b');
    
    var elem = document.getElementsByTagName ('select');
    for (var i = 0; i < elem.length; i++) 
    {
        if ((elem[i] != null) && (elem[i].attributes != null) && (elem[i].attributes['mboxControlId'] != null))
        {
            var mboxControlId = elem[i].attributes['mboxControlId'].value;
            if (pattern.test (mboxControlId)) 
                return elem[i];
        }
    }
    elem = document.getElementsByTagName ('input');
    for (i = 0; i < elem.length; i++) 
    {
        if ((elem[i] != null) && (elem[i].attributes != null) && (elem[i].attributes['mboxControlId'] != null))
        {
            var mboxControlId = elem[i].attributes['mboxControlId'].value;
            if (pattern.test (mboxControlId)) 
                return elem[i];
        }
    }
    return null;
}; 