NS.createNS("UI");

UI.getControlName = function(obj,prefix)
{
	var classes = Utils.CSS.getClasses(obj);
	var controlName = null;
		
	for (var i = 0; i < classes.length; i++)
	{
		var parts = classes[i].split("-");
		if (parts.length == 2 && parts[0] == prefix)
		{
			controlName = parts[1];
			break;
		}
	}
	return controlName;
}

UI.clearDefault = function(obj)
{
	obj.value = "";
	Utils.CSS.remClass(obj,'default');
}

UI.switchDropdownToInput = function(dropdownObj,newDropdownVal,newId,newVal,fixed)
{
	if (dropdownObj.nodeName != "SELECT")
		return;
		
	var dropdownId = dropdownObj.id;

	var obj = document.createElement('INPUT');
	obj.type = "hidden";
	obj.value = newDropdownVal;
	obj.name = dropdownObj.name;
	obj.readonly = true;
	obj.oldObj = dropdownObj;
	
	dropdownObj.parentNode.insertBefore(obj,dropdownObj);
	dropdownObj.parentNode.removeChild(dropdownObj);
	obj.id = dropdownId;
	
	var newObj = document.createElement('INPUT');
	newObj.type = "text";
	newObj.className = "text";
	newObj.value = newVal;
	newObj.name = newId;
	newObj.id = newId;

	if (fixed)
		newObj.readOnly = true;

	obj.parentNode.insertBefore(newObj,obj);
}

UI.switchInputToDropdown = function(inputObj,hiddenInputObj)
{
	inputObj.parentNode.removeChild(inputObj);
	hiddenInputObj.parentNode.insertBefore(hiddenInputObj.oldObj,hiddenInputObj);
	hiddenInputObj.parentNode.removeChild(hiddenInputObj);
}

UI.AutoComplete = function(inputBoxVal,listenerVal)
{
	var minChars;
	var inputBox = null;
	var listener = null;
	
	var curKey = null;
	var timer = null;
	
	this._init(inputBoxVal,listenerVal);
}

UI.AutoComplete.prototype = 
{
	_init:function(inputBoxVal,listenerVal)
	{
		this.inputBox = inputBoxVal;
		this.listener = listenerVal;
		this.minChars = 4;

		Utils.EventManager.addListener(this.inputBox,"keypress",new Callback(this,this.handleKeyPress));
		Utils.EventManager.addListener(this.inputBox,"keydown",new Callback(this,this.handleKeyDown));
	},
	
	handleKeyDown:function(e)
	{
		this.curKey = e._e.keyCode;
	},
	
	handleKeyPress:function(e)
	{
		this.stopTimer();
		
		if (this.inputBox.value.length < this.minChars)
			return;

		var keyCode = this.curKey;
		this.curKey = null;
		
		//var validChar = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90))
		var validChar = true;

		if (!validChar)
		{
			return;
		}
		
		if (keyCode == 13)
		{
			e.preventDefault();
			e.stopPropagation();
			return false;
		}
		
		this.startTimer();
	},
	
	startTimer:function()
	{
		if (this.timer != null)
			this.stopTimer();

		var self = this;
		this.timer = setInterval(function(){self.onTimer()},400);
	},
	
	stopTimer:function()
	{
		clearInterval(this.timer);
		this.timer = null;
	},
	
	onTimer:function()
	{
		this.stopTimer();
		this.listener.doAutoComplete(this.inputBox);
	}
};

UI.LocationControl = function() {};

UI.LocationControl.ZipAutoCompleteListener = function() {};
UI.LocationControl.ZipAutoCompleteListener.prototype =
{
	doAutoComplete:function(obj)
	{
		UI.LocationControl.getLocationFromZip(obj.value,g('country').value);
	}
};

UI.LocationControl.stateTarget = null;
UI.LocationControl.cityTarget = null;
UI.LocationControl.loadingEl = null;

UI.LocationControl.createLoadingEl = function(obj)
{	
	if (!UI.LocationControl.loadingEl)
	{
		loadingEl = document.createElement("DIV");
		loadingEl.className = "small loader";
		loadingEl.innerHTML = "loading...";
		UI.LocationControl.loadingEl = loadingEl;
	}
	
	obj.parentNode.insertBefore(UI.LocationControl.loadingEl,obj.nextSibling);
}

UI.LocationControl.getLocationFromZip = function(zip,countryId)
{
	if (countryId == 3 && zip.indexOf(" ") == -1)
		zip = zip.substr(0,3) + " " + zip.substr(3,5);
		
	g('locationmessage').style.visibility = 'visible';
	g('locationmessage').style.display = 'block';
	
	g('locationmessage').innerHTML = '<img src="/images/small-loader.gif"/>Please wait while we look up your city...';
	g('location-extra').style.display = 'none';
	var xmlObj = getXml("GET","/cityList.php?type=findcity&zip="+zip+"&cid="+countryId+"&format=json",null,true,new Callback(UI.LocationControl,UI.LocationControl.onLocationFromZipXML));
}

UI.LocationControl.onLocationFromZipXML = function(xmlObj)
{
	if (xmlObj.readyState == XML_COMPLETE)
	{
		var obj = eval('('+xmlObj.responseText+')');
	
		if (obj == null)
		{
			g('locationmessage').style.visibility = 'visible';
			g('locationmessage').style.visibility = 'block';
			g('locationmessage').innerHTML = "We were unable to automatically locate your city and state.  Please choose them from the list below.";
			
			if (g('stateid').nodeName != 'SELECT')
			{
				UI.switchInputToDropdown(g('statename'),g('stateid'));
				UI.switchInputToDropdown(g('cityname'),g('cityid'));
			}
			
			this.getStateList(g('country').value,g('stateid'),g('cityid'));
		}
		else
		{
			if (!g('city').disabled)
				this.hideManualCityInput(g('locationcontrol'));
			
			if (g('stateid').nodeName == 'SELECT')
			{				
				UI.switchDropdownToInput(g('stateid'),obj[0].stateid,'statename',obj[0].state,true);
				UI.switchDropdownToInput(g('cityid'),obj[0].cityid,'cityname',obj[0].city,true);
			}
			else
			{
				g('stateid').value = obj[0].stateid;
				g('statename').value = obj[0].state;
				g('cityid').value = obj[0].cityid;
				g('cityname').value = obj[0].city;
			}
			
			g('locationmessage').innerHTML = 'city located';
			g('cityentrylink').style.display = 'none';
		}
		
		g('location-extra').style.display = 'block';
	}
}

UI.LocationControl.showManualCityInput = function(obj)
{
	var autoCityRow = Utils.DOM.getElementsByClassName(obj,'city')[0];
	var manualCityRow = Utils.DOM.getElementsByClassName(obj,'manualcity')[0];
	
	autoCityRow.style.display = "none";
	manualCityRow.style.display = "block";
	g('city').value = 'type the name of your city';
	Utils.CSS.addClass(g('city'),'default');
	g('city').disabled = false;
}

UI.LocationControl.hideManualCityInput = function(obj)
{
	var autoCityRow = Utils.DOM.getElementsByClassName(obj,'city')[0];
	var manualCityRow = Utils.DOM.getElementsByClassName(obj,'manualcity')[0];

	autoCityRow.style.display = "block";
	manualCityRow.style.display = "none";
	g('city').value = "";
	g('city').disabled = true;
}

UI.LocationControl.getStateList = function(country,stateTarget,cityTarget)
{
	g('location-extra').style.display = 'none';

	if (country == 2)
	{
		g('ziplabel').innerHTML = 'Zip Code';
		g('statelabel').innerHTML = 'State';
	}
	else
	{
		g('ziplabel').innerHTML = 'Postal Code';
		g('statelabel').innerHTML = 'Province';
	}

	if (cityTarget.nodeName != "SELECT")
	{
		UI.switchInputToDropdown(g('statename'),g('stateid'));
		UI.switchInputToDropdown(g('cityname'),g('cityid'));
		cityTarget = g('cityid');
		stateTarget = g('stateid');
	}
	
	cityTarget.options.length = 0;
	stateTarget.options.length = 0;
	cityTarget.disabled = true;
	stateTarget.disabled = true;

	this.createLoadingEl(stateTarget);

	g('cityentrylink').style.display = 'none';
	
	getXml("GET","/cityList.php?type=state&id="+country,null,true,new Callback(UI.LocationControl,UI.LocationControl.onListXML),stateTarget);
}

UI.LocationControl.getCityList = function(state,stateTarget,cityTarget)
{
	cityTarget.options.length = 0;
	cityTarget.disabled = true;
	
	this.createLoadingEl(cityTarget);
	g('cityentrylink').style.display = 'none';
	
	if (!g('city').disabled)
		this.hideManualCityInput(g('locationcontrol'));

	getXml("GET","/cityList.php?type=city&id="+state,null,true,new Callback(UI.LocationControl,UI.LocationControl.onListXML),cityTarget);
}

UI.LocationControl.onListXML = function(xmlObj,target)
{
	if (xmlObj.readyState == XML_COMPLETE)
	{
		var xml = null;
		xml = xmlObj.responseXML;

		var options = xml.getElementsByTagName("option");

		if (target.nodeName != 'SELECT')
			return;

		target.options.length = 0;
		target.disabled = true;

		var hasDefaultOption = false;
		var offset = 0;
		
		if (target.id != "cityid")
		{
			target.options[0] = new Option('Select...','-1');
			target.options[0].disabled = true;
			hasDefaultOption = true;
			offset = 1;
		}
		
		for (var i = 0; i < options.length; i++)
		{
			if (!browser.isIE)
			{
				var optionEl = document.createElement("OPTION");
				optionEl.text = options[i].textContent;
				optionEl.value = options[i].getAttribute("value");
			
				target.add(optionEl,null);
			}
			else
			{	
				target.options[i+offset] = new Option(options[i].firstChild.nodeValue,options[i].getAttribute("value"));
			}
		}
		
		target.disabled = false;
		
		if (UI.LocationControl.loadingEl.parentNode)
			UI.LocationControl.loadingEl.parentNode.removeChild(UI.LocationControl.loadingEl);
		
		if (target.id == "cityid")
		{
			if (options.length == 0)
			{
				this.showManualCityInput(g('locationcontrol'));
			}
			else
			{
				g('cityentrylink').style.display = 'inline';
				if (!g('city').disabled)
					this.hideManualCityInput(g('locationcontrol'));
			}
		}
	}
}

UI.HeightControl = function()
{
}

UI.HeightControl.metricToImperial = function(cm)
{
	var obj = {};

	obj.inches = cm * 0.393700787;
	obj.feet = Math.floor(obj.inches / 12);
	obj.inches = Math.round(obj.inches - (obj.feet * 12));
	
	return obj;
}

UI.HeightControl.imperialToMetric = function(feet,inches)
{
	if (isNaN(inches))
		inches = 0;
		
	var totalInches = (feet * 12) + inches;
	return Math.ceil(totalInches * 2.54);
}

UI.HeightControl.switchType = function(obj,type)
{
	var impObj = Utils.DOM.getElementsByClassName(obj,'imperial')[0];
	var metObj = Utils.DOM.getElementsByClassName(obj,'metric')[0];
	
	
	if (type == UI.HeightControl.TYPE_METRIC)
	{
		impObj.style.display = 'none';
		metObj.style.display = 'inline';
	}
	else
	{
		impObj.style.display = 'inline';
		metObj.style.display = 'none';
	}
	
	UI.HeightControl.sync(obj,type);
}

UI.HeightControl.sync = function(obj,type)
{
	var cmInput = Utils.DOM.getElementsByClassName(obj,'cm')[0];
	var feetInput = Utils.DOM.getElementsByClassName(obj,'feet')[0];
	var inchesInput = Utils.DOM.getElementsByClassName(obj,'inches')[0];

	if (type == UI.HeightControl.TYPE_METRIC)
	{
		cmInput.value = UI.HeightControl.imperialToMetric(Number(feetInput.value),Number(inchesInput.value));
	}
	else
	{
		var measurements = UI.HeightControl.metricToImperial(Number(cmInput.value));
		feetInput.value = measurements.feet;
		inchesInput.value = measurements.inches;
	}
}

UI.HeightControl.TYPE_METRIC = 1;
UI.HeightControl.TYPE_IMPERIAL = 2;

UI.Expander = function()
{
}

UI.Expander.expand = function(node)
{
	if (Utils.CSS.hasClass(node,'collapsed'))
		Utils.CSS.remClass(node,'collapsed');
	else
		Utils.CSS.addClass(node,'collapsed');
}

UI.Dialog = function(objVal,useOverlay)
{
	this.obj = null;
	this.useOverlay = false;
	this.visible = false;

	this._init(objVal,useOverlay);
}

UI.Dialog.overlayObj = null;

UI.Dialog.showMessage = function(title,message,type,useOverlay)
{
	if (useOverlay == null)
		useOverlay = true;
		
	var obj = document.createElement('DIV');
	obj.className = "dialog message";
	obj.innerHTML = "<h1>"+title+"</h1><div class=\"content\">"+message+'</div>';

	if (type != 'loading')
		obj.innerHTML += '<div class="buttonpanel autoclear"><button onclick="parentNode.parentNode._dialog.close();" class="button">OK</button></div>';

	document.getElementById("main").insertBefore(obj,g('content'));
	var dialog = new UI.Dialog(obj,useOverlay);
	dialog.show();
	
	return dialog;
}

UI.Dialog.createExtDialog = function(id,url,useOverlay,extClass)
{
	var obj = document.createElement('DIV');
	obj.id = id;
	obj.className = "dialog";
	if (extClass)
		obj.className = obj.className + " " + extClass;
		
	obj.innerHTML = "loading...";
	document.getElementById("main").insertBefore(obj,g('content'));
	
	var dialog =  new UI.Dialog(obj,useOverlay);
	var xmlObj = getXml("GET",url,null,true,new Callback(UI.Dialog,UI.Dialog.onDialogContentXML),dialog);

	return dialog;
}

UI.Dialog.onDialogContentXML = function(xmlObj,dialog)
{
	if (xmlObj.readyState == XML_COMPLETE)
	{
		dialog.getObj().innerHTML = "";
		
		if (!xmlObj.responseText)
			return;
				
		var obj = eval('('+xmlObj.responseText+')');
		
		var content = obj.content.replace(/\\x/g,'%');
		dialog.getObj().innerHTML = decodeURIComponent(content);
		dialog.updatePos();
		
		for(var i = 0; i < obj.jsfiles.length; i++)
		{
			var scriptEl = dialog.getObj().appendChild(document.createElement("SCRIPT"));
			scriptEl.id = obj.id+"_script";
			scriptEl.src = obj.jsfiles[i];
		}
	}
}

UI.Dialog.prototype =
{
	_init:function(objVal,useOverlayVal)
	{
		this.obj = objVal;
		this.obj._dialog = this;

		if (useOverlayVal == null)
			useOverlayVal = true;

		this.useOverlay = useOverlayVal;
		
		if (UI.Dialog.overlayObj == null)
			UI.Dialog.overlayObj = document.getElementById('overlay');
		
		Utils.EventManager.addListener(window,"resize",new Callback(this,this.handleViewResize));
		
		if (browser.isIE)
			Utils.EventManager.addListener(window,"scroll",new Callback(this,this.handleScroll));
	},
	
	updatePos:function()
	{
		Utils.DOM.centerEl(this.obj);
		
		if (this.useOverlay)
		{
			var docBounds = Utils.DOM.getDocumentBounds();
			UI.Dialog.overlayObj.style.width = docBounds.w+"px";
			UI.Dialog.overlayObj.style.height = docBounds.h+"px";
		}
	},
	
	handleViewResize:function()
	{
		if (!this.visible)
			return;
			
		this.updatePos();
	},
	
	handleScroll:function()
	{
		if (!this.visible)
			return;

		Utils.DOM.centerEl(this.obj);
	},
	
	hide:function()
	{		
		this.visible = false;
		this.obj.style.display = "none";
		
		if (this.useOverlay)
				UI.Dialog.overlayObj.style.display = "none";

		this.onHide();
		
		return false;
	},
	
	show:function()
	{
		this.visible = true;
		this.onShow();
		
		if (this.useOverlay)
				UI.Dialog.overlayObj.style.display = "block";
		
		this.obj.style.display = "block";
		
		this.updatePos();
		
		return false;
	},
	
	getObj:function()
	{
		return this.obj;
	},
	
	close:function()
	{
		this.hide();
		this.obj.parentNode.removeChild(this.obj);
	},
	
	onShow:function()
	{
	},
	
	onHide:function()
	{
	}
};

UI.BasicDialog = function(objVal)
{
	this._init(objVal);
}

Utils.OOP.extend(UI.BasicDialog,UI.Dialog);

UI.BasicDialog.prototype.onShow = function()
{
	var objs = Utils.DOM.getElementsByClassName(this.obj,'message');

	for (var i =0; i < objs.length; i++)
	{
		objs[i].style.display = 'none';
		//objs[i].style.visibility = "hidden";
		objs[i].innerHtml = '';
	}
}