/*extern KIC, Ajax, AjaxUpdater, dhtmlHistory, tinyMCE, Zapatec, $  */
/*extern Admin, Faq, KicEvent, KicScript, Library, Product, Promotion, Recipe, UserAdmin  */

if(typeof KIC              == "undefined") { var KIC       = {}; }
if(typeof KIC.UI           == "undefined") { KIC.UI        = {}; }
if(typeof KIC.UI.Selector  == "undefined") { KIC.UI.Selector  = {}; }	// left nav area
if(typeof KIC.UI.Workspace == "undefined") { KIC.UI.Workspace = {}; }	// main area
if(typeof KIC.UI.Panels    == "undefined") { KIC.UI.Panels    = {}; }
if(typeof KIC.UI.Search    == "undefined") { KIC.UI.Search = {}; }   
if(typeof KIC.UI.SubSearch == "undefined") { KIC.UI.SubSearch = {}; }

///////////////////////////////////////////////////////////////////////////
//	could probably be renamed KIC.UI.Search
///////////////////////////////////////////////////////////////////////////
KIC.UI.Selector.Clear = function() {
	var ui = KIC.UI;
	ui.destroyEditors();					// remove any tinyMCE fragments

	ui.hideControlPanel();					// hide control panel
	ui.hideRecordNav();						// hide record nav

	ui.setHeaderContent( "" );				// clear header
	ui.setLocation( "" );
	ui.showHeaderContent();

	ui.setWorkspaceRecordContent( "" );		// clear workspaces (record only, not search)
//	ui.setWorkspaceSearchContent( "" );

	ui.setSelectorNavContent( "" );			// clear selector (record nav only, not search)

	ui.searchCollapseDiv();					// collapse the expanded selector div if needed

	// reset the MainMenu to direct user to Home
	ui.MainMenu.setConfirmationHandler( null );
	ui.MainMenu.setBackHandler( function() { KIC.home(); } );
	ui.MainMenu.show();

	KIC.homeCheckCallback = null;
};

KIC.UI.Selector.ReShow = function( section, requery )
{
	KIC.UI.PopupWindow.clearDropDowns();

	var form =  $('searchForm');
	if (form) {
		KIC.UI.Selector.Clear();
		KIC.UI.showSelectorSearch();

		if (section === 'document')        { KIC.UI.addHistory( "Search:Document" ); }
		else if (section === 'event')      { KIC.UI.addHistory( "Search:Event" ); }
		else if (section === 'faq')        { KIC.UI.addHistory( "Search:Faq" ); }
		else if (section === 'product')    { KIC.UI.addHistory( "Search:Product" ); }
		else if (section === 'promotion')  { KIC.UI.addHistory( "Search:Promotion" ); }
		else if (section === 'recipe')     { KIC.UI.addHistory( "Search:Recipe" ); }
		else if (section === 'script')     { KIC.UI.addHistory( "Search:Script" ); }
		else {
			KIC.UI.Selector.Show(section);
			return;
		}

		KIC.UI.setLocation(KIC.UI.lastLocation);
		KIC.UI.lastLocation = '';
		
		KIC.UI.MainMenu.showExpandButton();

		if (requery) {
			KIC.UI.Selector.Search( form );
		} else {
			KIC.UI.showWorkspaceSearch();
		}
	} else {
		KIC.UI.Selector.Show(section);
	}

};

KIC.UI.Selector.Show = function( section )
{
	KIC.UI.Selector.Clear();		// clear header, workspaces, & selector; hide control panel & record nav

	KIC.UI.showSelectorLoading();

	KIC.UI.previousSearch = null;
	KIC.UI.disabledFormElements = []; /* new Array */

	section = section.toLowerCase();
	if (section == 'document')        { KIC.Search.Document(); }
	else if (section == 'event')      { KIC.Search.Event(); }
	else if (section == 'faq')        { KIC.Search.Faq(); }
	else if (section == 'product')    { KIC.Search.Product();  }
	else if (section == 'promotion')  { KIC.Search.Promotion();  }
	else if (section == 'recipe')     { KIC.Search.Recipe();  }
	else if (section == 'script')     { KIC.Search.Script();  }
	else if (section == 'user')       { UserAdmin.init();  }
	else if (section == 'group')      { UserAdmin.init();  }
	else if (section == 'admin')      { Admin.load();  }
	else if (section == 'report')     { KIC.Report.load();  }
	else 
	{ 
		KIC.UI.showAlert('Unknown navigation section: ' + section ); 
		return false;
	}
	return true;
};

// should rename this KIC.UI.Search.Submit
KIC.UI.Selector.Search = function( form, sort_field, sort_order )
{
	KIC.UI.searchCollapseDiv();				// collapse the search form, if it's expanded

	KIC.UI.previousSearch = form;
	KIC.UI.disableFormElements( form );

	KIC.UI.showWorkspaceLoading();			// show the loading screen
	KIC.UI.clearWorkspaceSearchContent();	// clear the existing search results

	// add sort order, if provided
	var additional_params;
	if (sort_field) {
		additional_params = "sortField=" + sort_field;
		if (sort_order) {
			if (sort_order == "desc") {
				// descending
				additional_params = additional_params + "&sortAsc=false";
			} else {
				// default to ascending
				additional_params = additional_params + "&sortAsc=true";
			}
		}
	}

	// submit request
	submit_ajax( form, null, KIC.UI.Search.handleSearch, additional_params );
	return false;
};

KIC.UI.Search.handleSearch = function()
{
	if ( KIC.Services.isReady() ) {
		var response = Ajax.getResponse();
		var responseArray = response.split(SECTION_DIVIDER);
		var responseObj = parseJSONWithLogin( responseArray[0] );
		
		if (responseObj.Success)
		{
			KIC.UI.setWorkspaceSearchContent( responseArray[1] );
			KIC.UI.showWorkspaceSearch();
			// turn search form back on
			KIC.UI.reenabledFormElements( KIC.UI.previousSearch );
		}
		else
		{
			KIC.UI.showAlert(responseObj.Message);
		}
	}
};

// could be deprecated
KIC.UI.Selector.Back = function() 
{
	alert("warning -- KIC.UI.Selector.Back is deprecated");
	// this should use a stack to keep a breadcrumb trail of where the user has been, but for now, just go back to main nav list
	if (dhtmlHistory.getCurrentLocation().toLowerCase().substring(0, 6) == "search") {
		KIC.home();
	} else {
		alert(dhtmlHistory.getCurrentLocation());
	}
};

///////////////////////////////////////////////////////////////////////////
//	KIC.UI.SubSearch
///////////////////////////////////////////////////////////////////////////
KIC.UI.SubSearch.Show = function( section, manager )
{
	section = section.toLowerCase();
	this.manager = manager;
	KIC.UI.show( 'subsearch_left_loading' );
	KIC.UI.hide( 'subsearch_left_display' );
	KIC.UI.hide( 'subsearch_right_loading' );
	KIC.UI.show( 'subsearch_right_display' );
	if (section == 'document')		{ AjaxUpdater.update( 'GET', '/content/Document/SearchForm.aspx?subsearch=1',		KIC.UI.SubSearch.handleShowForm ); }
	else if (section == 'faq')		{ AjaxUpdater.update( 'GET', '/content/FAQ/SearchForm.aspx?subsearch=1',		KIC.UI.SubSearch.handleShowForm ); }
	else if (section == 'package')	{ AjaxUpdater.update( 'GET', '/content/Product/SearchForm.aspx?subsearch=1&package=1',	KIC.UI.SubSearch.handleShowForm ); }
	else if (section == 'product')		{ AjaxUpdater.update( 'GET', '/content/Product/SearchForm.aspx?subsearch=1&single=0',	KIC.UI.SubSearch.handleShowForm ); }
	else if (section == 'product_single')	{ AjaxUpdater.update( 'GET', '/content/Product/SearchForm.aspx?subsearch=1&single=1',	KIC.UI.SubSearch.handleShowForm ); }
	else if (section == 'recipe_ingredient')	{ AjaxUpdater.update( 'GET', '/content/Product/SearchForm.aspx?subsearch=1&single=1&ingredient=1',	KIC.UI.SubSearch.handleShowForm ); }
	else if (section == 'promotion')	{ AjaxUpdater.update( 'GET', '/content/Promotion/SearchForm.aspx?subsearch=1&single=0',	KIC.UI.SubSearch.handleShowForm ); }
	else if (section == 'promotion_single')	{ AjaxUpdater.update( 'GET', '/content/Promotion/SearchForm.aspx?subsearch=1&single=1',	KIC.UI.SubSearch.handleShowForm ); }
	else if (section == 'recipe')		{ AjaxUpdater.update( 'GET', '/content/Recipe/SearchForm.aspx?subsearch=1',		KIC.UI.SubSearch.handleShowForm ); }
	else if (section == 'script')		{ AjaxUpdater.update( 'GET', '/content/Script/SearchForm.aspx?subsearch=1',		KIC.UI.SubSearch.handleShowForm ); }
	else 
	{ 
		KIC.UI.showAlert('Unknown subsearch section: ' + section ); 
		return false;
	}
	KIC.UI.show("subsearch_container");		// show search div
	return true;
};

KIC.UI.SubSearch.handleShowForm = function() {
	if ( KIC.Services.isReady() ) {
		var response = Ajax.getResponse();
		var responseArray = response.split(SECTION_DIVIDER);
		var responseObj = parseJSONWithLogin( responseArray[0] );
		
		if (responseObj.Success)
		{
			KIC.UI.setContent( 'subsearch_left_display', responseArray[1] );
			KIC.UI.hide( 'subsearch_left_loading' );
			KIC.UI.show( 'subsearch_left_display' );
			KIC.UI.subsearchExpandDiv();				// expand form to full width
		}
		else
		{
			KIC.UI.showAlert(responseObj.Message);
		}
	}
};

KIC.UI.SubSearch.Search = function( form, sort_field, sort_order )
{
	KIC.UI.show( 'subsearch_right_loading' );
	KIC.UI.hide( 'subsearch_right_display' );
	KIC.UI.subsearchCollapseDiv();				// collapse form
	KIC.UI.disableFormElements( form );
	KIC.UI.previousSubSearch = form;
	// clear the current search results container
	//setInnerHTML($('subsearch_right'), ""); 

//	var additional_params = "subsearch=1";	// subsearch is part of form, don't repeat it
	var additional_params;
	if (sort_field) {
		additional_params = "sortField=" + sort_field;
		if (sort_order) {
			if (sort_order == "desc") {
				// descending
				additional_params = additional_params + "&sortAsc=false";
			} else {
				// default to ascending
				additional_params = additional_params + "&sortAsc=true";
			}
		}
	}
	submit_ajax( form, null, KIC.UI.SubSearch.handleSearch, additional_params );
	return false;
};

KIC.UI.SubSearch.handleSearch = function()
{
	if ( KIC.Services.isReady() ) {
		var response = Ajax.getResponse();
		var responseArray = response.split(SECTION_DIVIDER);
		var responseObj = parseJSONWithLogin( responseArray[0] );
		
		if (responseObj.Success)
		{
			KIC.UI.setContent( 'subsearch_right_display', responseArray[1] );
			KIC.UI.hide( 'subsearch_right_loading' );
			KIC.UI.show( 'subsearch_right_display' );
		
			// turn search form back on
			KIC.UI.reenabledFormElements( KIC.UI.previousSubSearch );
		}
		else
		{
			KIC.UI.showAlert(responseObj.Message);
		}
	}
};

KIC.UI.SubSearch.AddAssociations = function (form, strType)
{
	if (typeof form == "string") {
		form = $(form);
	}
	if (form) {
		for ( var i = 0; i < form.elements.length; i++ ) 
		{
			var element = form.elements[i];
			if ( (element.type == "checkbox"||element.type == "radio") && element.checked === true)
			{
				var obj = this.CreateAssociationObject(strType, element.id);
				this.manager.AddAssociationObject(strType, obj);
			}
		}
		this.Close();
	}
};

KIC.UI.SubSearch.CreateAssociationObject = function(strType, element_id)
{
	var obj = {};

	// common properties
	var tmp = element_id.split("_");
	obj.Id = tmp[1];
	obj.Text = $(element_id + "_text").value;
	obj.RecordStatus = $(element_id + '_status').value;
	
	// additional properties based on search type
	switch (strType) {
		case 'script':
			obj.Code = $(element_id + "_code").value;
			break;
		case 'product':
			obj.UpcList = [];
			// TESTING
			/*
			obj.CompanyId = '0';
			obj.CompanyName = 'Foo';
			obj.CPN = 0;
			*/
			//debugObj(obj);
			break;
		case 'foo':
			break;
	}

	return obj;
};

KIC.UI.SubSearch.Close = function()
{
	// clear form and results, hide container
	setInnerHTML($('subsearch_left_display'), ""); 
	setInnerHTML($('subsearch_right_display'), ""); 
	KIC.UI.hide('subsearch_container');

	// call onClose handler, if present
	if ( this.onClose ) {
		this.onClose.call();
	}
	this.onClose = null;
};

KIC.UI.SubSearch.setOnClose = function( handler ) {
	this.onClose = handler;
};

///////////////////////////////////////////////////////////////////////////
// Page History/URI
///////////////////////////////////////////////////////////////////////////
KIC.UI.addHistory = function(newHash)
{
	// many examples, see for instance: http://ajaxpatterns.org/Unique_URLs
	// this library comes from here: http://www.onjava.com/pub/a/onjava/2005/10/26/ajax-handling-bookmarks-and-back-button.html
	if (dhtmlHistory.getCurrentLocation().toLowerCase() != newHash.toLowerCase()) {
		dhtmlHistory.add(newHash); // , "");
	}
};

KIC.UI.initializeState = function()
{
	var tempHashString = dhtmlHistory.getCurrentLocation();
	if ((typeof tempHashString == "undefined") || tempHashString === '' || tempHashString.toLowerCase() == 'home')
	{
		KIC.home();
	}
	else
	{
		tempHashString = tempHashString.toLowerCase();
		var tempArray = tempHashString.split(':');
		if (tempArray[0] == "search")
		{
			KIC.UI.Selector.Show(tempArray[1]);
		}
		else if (tempArray[0] == "view")
		{
			KIC.CsrPreviewLoad(tempArray[1], tempArray[2]);
		}
		else if (tempArray[0] == "detail")
		{
			// product detail, recipe, etc
			if (tempArray[1] == "product") {
				if (tempArray[2] == "new") {
					Product.load();
				} else {
					Product.load( tempArray[2] );
				}
			}
			else if (tempArray[1] == "recipe") {
				if (tempArray[2] == "new") {
					Recipe.load();
				} else {
					Recipe.load( tempArray[2] );
				}
			}
			else if (tempArray[1] == "script") {
				KicScript.load( tempArray[2] );
			}
			else if (tempArray[1] == "document") {
				Library.load( tempArray[2] );
			}
			else if (tempArray[1] == "event") {
				KicEvent.load( tempArray[2] );
			}
			else if (tempArray[1] == "faq") {
				Faq.load( tempArray[2] );
			}
			else if (tempArray[1] == "promotion") {
				if (tempArray[2] == "new") {
					Promotion.load();
				} else {
					Promotion.load( tempArray[2] );
				}
			}
			else if (tempArray[1] == "user") {
				if (tempArray[2] == "new") {
					UserAdmin.UserAdd.load();
				} else {
					UserAdmin.UserEdit.load( tempArray[2] );
				}
			}
			else if (tempArray[1] == "group") {
				if (tempArray[2] == "new") {
					UserAdmin.GroupAdd.load();
				} else {
					UserAdmin.GroupEdit.load( tempArray[2] );
				}
			}
		}
		else if (tempArray[0] == "admin") {
			Admin.load();
		}
		else if (tempArray[0] == "report") {
			if(tempArray[1]) {
				KIC.Report.loadSearch(tempArray[1]);
			} else {
				KIC.Report.load();
			}
		}
		else
		{
			KIC.UI.showAlert("unknown location\r\n" + tempArray.join("\r\n"));
		}
	
 	}
};

KIC.UI.clearViewHistory = function( table ) {
	KIC.Services.General.clearViewHistory( table, function() { KIC.UI.handleClearViewHistory(); } );
};

KIC.UI.handleClearViewHistory = function() {
	if ( KIC.Services.isReady() ) {
		var response = parseJSONWithLogin( Ajax.getResponse() );
		if ( response.Success ) {
			// starting from the DIV, find the search results table
			var div = $('workspace_search');
			for ( var i = 0; i < div.childNodes.length; i++ ) {
				var table = div.childNodes[i];
				if ( table.className == 'search_results' ) {
					// take off the viewed class on each row
					for ( var j = 0; j < table.rows.length; j++ ) {
						css( table.rows[j], 'remove', 'row_viewed' );
					}
				}
			}
		}
		else {
			KIC.UI.showAlert( response.Message );
		}
	}
};

///////////////////////////////////////////////////////////////////////////
// MAIN MENU
///////////////////////////////////////////////////////////////////////////

KIC.UI.MainMenu = {
	confirmationHandler: null,

	open: function() {
		$('tdMainMenuToggle').onclick = function() { KIC.UI.MainMenu.close(); };
		KIC.UI.show('main_menu_nav');
	},

	close: function() {
		$('tdMainMenuToggle').onclick = function() { KIC.UI.MainMenu.open(); };
		KIC.UI.hide('main_menu_nav');
	},

	show: function() {
		KIC.UI.show( 'main_menu_btns' );
	},

	hide: function() {
		KIC.UI.hide( 'main_menu_btns' );
	},

	setBackHandler: function( handler ) {
		$('tdMainMenuBack').onclick = handler;
		this.showBackButton();
	},

	showBackButton: function() {
		KIC.UI.show('tdMainMenuBack');
		KIC.UI.hide('tdMainMenuExpandSearch');
		KIC.UI.hide('tdMainMenuCollapseSearch');
	},

	showExpandButton: function() {
		KIC.UI.hide('tdMainMenuBack');
		KIC.UI.show('tdMainMenuExpandSearch');
		KIC.UI.hide('tdMainMenuCollapseSearch');
	},

	setConfirmationHandler: function( handler ) {
		this.confirmationHandler = handler;
	},

	confirm: function() {
		if ( this.confirmationHandler === null ) {
			return true;
		}
		return this.confirmationHandler.call();
	}
};

///////////////////////////////////////////////////////////////////////////
// HEADER
///////////////////////////////////////////////////////////////////////////

KIC.UI.setHeaderContent = function( html ) {
	setInnerHTML($('header_content'), html);
	KIC.UI.showHeaderContent();
};

KIC.UI.showHeaderLoading = function() {
	KIC.UI.hide('header_content');
	KIC.UI.show('header_loading');
};

KIC.UI.showHeaderContent = function() {
	KIC.UI.show('header_content');
	KIC.UI.hide('header_loading');
};

KIC.UI.setLocation = function( html ) {
	if ( html !== '' ) {
		document.title = KIC.UI.originalTitle + ' - ' + html;
	}
	else {
		document.title = KIC.UI.originalTitle;
	}
	setInnerHTML($('header_location'), html);
};

///////////////////////////////////////////////////////////////////////////
// SELECTOR
///////////////////////////////////////////////////////////////////////////

KIC.UI.setSelectorSearchContent = function( html ) {
	setInnerHTML( $('selector_search'), html );
};

KIC.UI.setSelectorNavContent = function( html ) {
	setInnerHTML( $('selector_nav'), html );
};

KIC.UI.showSelectorLoading = function() {
	KIC.UI.show('selector_loading');
	KIC.UI.hide('selector_search');
	KIC.UI.hide('selector_nav');
};

KIC.UI.showSelectorSearch = function() {
	KIC.UI.hide('selector_loading');
	KIC.UI.show('selector_search');
	KIC.UI.hide('selector_nav');
};

KIC.UI.showSelectorNav = function() {
	KIC.UI.hide('selector_loading');
	KIC.UI.hide('selector_search');
	KIC.UI.show('selector_nav');
};

///////////////////////////////////////////////////////////////////////////
// WORKSPACE
///////////////////////////////////////////////////////////////////////////

KIC.UI.setWorkspaceSearchContent = function( html ) {
	setInnerHTML( $('workspace_search'), html );
};

KIC.UI.clearWorkspaceSearchContent = function() {
	setInnerHTML( $('workspace_search'), "" );
};

KIC.UI.setWorkspaceRecordContent = function( html ) {
	setInnerHTML( $('workspace_record'), html );
};

KIC.UI.setWorkspaceFormContent = function( html ) {
	setInnerHTML( $('workspace_form'), html );
};

KIC.UI.showWorkspaceLoading = function() {
	KIC.UI.show('workspace_loading');
	KIC.UI.hide('workspace_search');
	KIC.UI.hide('workspace_record');
	KIC.UI.hide('workspace_form');
};

KIC.UI.showWorkspaceSearch = function() {
	KIC.UI.hide('workspace_loading');
	KIC.UI.show('workspace_search');
	KIC.UI.hide('workspace_record');
	KIC.UI.hide('workspace_form');
};

KIC.UI.showWorkspaceRecord = function() {
	KIC.UI.hide('workspace_loading');
	KIC.UI.hide('workspace_search');
	KIC.UI.show('workspace_record');
	KIC.UI.hide('workspace_form');
};

KIC.UI.showWorkspaceForm = function() {
	KIC.UI.hide('workspace_loading');
	KIC.UI.hide('workspace_search');
	KIC.UI.hide('workspace_record');
	KIC.UI.show('workspace_form');
};

///////////////////////////////////////////////////////////////////////////
// MESSAGING
///////////////////////////////////////////////////////////////////////////

KIC.UI.Panels.TextPanel = function(  container_name, content_name )
{
	// this has to be done like this, since UI.js might be called before the rest of the page has loaded
	this.container_name = container_name;
	this.content_name   = content_name;
	this.container_div  = null;
	this.content_div    = null;
};
KIC.UI.Panels.TextPanel.prototype = 
{
	set_content: function(html_fragment) 
	{
		if (this.content_div === null) {
			this.content_div = $(this.content_name);
		}
		if (this.content_div !== null) {
			setInnerHTML( this.content_div, html_fragment );
		}
	},
	show_content: function(html_fragment) 
	{
		this.set_content(html_fragment);
		this.show();
	},
	show: function()
	{
		if (this.container_div === null) {
			this.container_div = $(this.container_name);
		}
		if (this.container_div !== null) {
			this.container_div.style.display = '';
		}
	},
	hide: function() 
	{
		if (this.container_div === null) {
			this.container_div = $(this.container_name);
		}
		if (this.container_div !== null) {
			this.container_div.style.display = 'none';
		}
	}
};
KIC.UI.ErrorBox = new KIC.UI.Panels.TextPanel( 'error_container', 'error_content' );
// IE6 has bug with floating divs & dropdown menus; so, just use browser alert function
//KIC.UI.ErrorBox.alert = KIC.UI.ErrorBox.show_content;	// create an alias for show_content

/*
 *	KIC.UI.showError is now only used by parseJSONWithLogin, because that has to show
 *	the error message, and afterwards, redirect user to another page (the login screen).
 */
KIC.UI.showError = function( msg, handler ) {
	KIC.UI.ErrorBox.set_content( msg );
	var onclose = handler ?
		function() {
			handler.call();
			KIC.UI.hideError();
		} :
		function() {
			KIC.UI.hideError();
		};
	$('bErrorClose').onclick = onclose;
	$('sErrorClose').onclick = onclose;
	KIC.UI.ErrorBox.show();
};

KIC.UI.hideError = function() {
	KIC.UI.ErrorBox.hide();
};

/*
 *	KIC.UI.showAlert replaces KIC.UI.ErrorBox.alert and KIC.UI.showError
 */
KIC.UI.showAlert = function( msg, handler ) {
	if (handler) {
		debug("mistakenly calling showAlert with a callback: " + handler);
	}
	window.alert( msg );
};

KIC.UI.showConfirm = function( msg, trueHandler, falseHandler ) {
	if ( window.confirm( msg ) ) {
		trueHandler.call();
	}
	else {
		if ( falseHandler ) {
			falseHandler.call();
		}
	}
};

KIC.UI.PictureBox = new KIC.UI.Panels.TextPanel( 'picture_container', 'picture_container' );
KIC.UI.PictureBox.show_image = function(img)
{
	if (typeof this.isvisible == "undefined")
	{
		this.isvisible = true;
	}
	this.set_content("<img src='" + img + "'>");
	this.show();
};
KIC.UI.PictureBox.toggle = function(img)
{
	if (typeof this.isvisible == "undefined")
	{
		this.isvisible = false;
	}
	this.isvisible = ! this.isvisible;
	if (this.isvisible)
	{
		this.show_image(img);
	}
	else
	{
		this.hide();
	}
};

KIC.UI.showImage = function(ev, elem, img)
{
	// stop other events from occurring
	stopEventPropagation(ev);

	// move the div up to the current mouse location
	if (ev.pageY) {
		$('picture_container').style.top = ev.pageY - 130;
	} else {
		$('picture_container').style.top = ev.clientY + document.body.scrollTop - 130;
	}

	// add the img to the box
	KIC.UI.PictureBox.show_image(img);
};

///////////////////////////////////////////////////////////////////////////
// UTILITIES
///////////////////////////////////////////////////////////////////////////

KIC.UI.disableFormElements = function( form ) {
	KIC.UI.disabledFormElements = []; /* new Array */
	for ( var i = 0; i < form.elements.length; i++ ) {
		var e = form.elements[i];
		if ( !e.disabled ) {
			KIC.UI.disabledFormElements.push( e );
			e.disabled = true;
		}
	}
};

KIC.UI.reenabledFormElements = function( form ) {
	for ( var i = 0; i < KIC.UI.disabledFormElements.length; i++ ) {
		for ( var j = 0; j < form.elements.length; j++ ) {
			var e = form.elements[j];
			if ( KIC.UI.disabledFormElements[i] == e ) {
				e.disabled = false;
			}
		}
	}
};

KIC.UI.setContent = function( elem_id, html ) {
	setInnerHTML( $(elem_id), html );
};

KIC.UI.show = function( elem ) {
	if (typeof elem === "string") { 
		// this is an id, rather than the DOM element itself
		//debug("KIC.UI.show('" + elem + "')");
		elem = $(elem);
	}
	if (elem) { elem.style.display = ''; }
};

KIC.UI.hide = function( elem ) {
	if (typeof elem === "string") { 
		// this is an id, rather than the DOM element itself
		//debug("KIC.UI.hide('" + elem + "')");
		elem = $(elem);
	}
	if (elem) { elem.style.display = 'none'; }
};

KIC.UI.disableButton = function( id, text ) {
	var elem = $(id);
	if (elem) {
		if ( text ) {
			elem.value = text;
		}
		elem.disabled = true;
	}
};

KIC.UI.enableButton = function( id, text ) {
	var elem = $(id);
	if (elem) {
		if ( text ) {
			elem.value = text;
		}
		elem.disabled = false;
	}
};

KIC.UI.toggleCheckBox = function( elem_id )
{
	var elem = $(elem_id);
	if (elem.disabled) {
		return;
	}
	elem.checked = !elem.checked;
};

KIC.UI.setActiveAndFocus = function( section, input ) {
	KIC.UI.SelectorNav.setActive( section );
	$(input).focus();
};

/*
	Date and Date/Time pickers
		Set up the date/time pickers.  there are two date formats used; 
		the ifFormat field (inputField format) which uses the w3 subset of the ISO 8601 date format
		[ see http://www.w3.org/TR/NOTE-datetime ]
		[ see also http://www.cl.cam.ac.uk/~mgk25/iso-time.html ]
		and the daFormat field (displayArea format), which should present the 
		current date in a locale-specific format to the user
 */
KIC.UI.initDatePicker = function( id, closeHandler, displayFormat ) {
	if (typeof displayFormat == "undefined") {
		displayFormat = DATE_DISPLAY_FORMAT; // "%m/%d/%Y";
	}

	var btn  = $(id+'_button');
	var elem = $(id+'_hidden');
	// if the button isn't there, then the control has been disabled
	if (btn && elem) {
		Zapatec.Calendar.setup({
			weekNumbers	: false,
			showOthers	: true,
			range		: [1900.01, 2999.12],
			electric	: false,
			inputField	: id+'_hidden',
			displayArea	: id+'_label',
			button		: id+'_button',
			date		: elem.value,
			ifFormat	: "%m/%d/%Y",
			daFormat	: displayFormat,
			onClose		: function( cal ) { closeHandler.call(); cal.destroy(); return false; }
		});
	}
};
KIC.UI.initDateTimePicker = function( id, closeHandler, displayFormat, twelve_hour ) {
	if (typeof displayFormat == "undefined") {
		displayFormat = DATETIME_DISPLAY_FORMAT; // "%m/%d/%Y %I:%M %p";
	}
		
	var time_format = "24";
	if (twelve_hour) {
		time_format = "12";
	}

	var btn  = $(id+'_button');
	var elem = $(id+'_hidden');
	var disp = $(id+'_label');
	// if the button isn't there, then the control has been disabled
	if (btn && elem) {
		Zapatec.Calendar.setup({
			weekNumbers	: false,
			showOthers	: true,
			range		: [1900.01, 2999.12],
			electric	: false,
			inputField	: id+'_hidden',
			displayArea	: id+'_label',
			button		: id+'_button',
			date		: elem.value,
			ifFormat	: "%m/%d/%Y %I:%M %p",
			daFormat	: displayFormat,
			showsTime	: true,
			timeFormat	: time_format,
			onClose		: function( cal ) { closeHandler.call(); cal.destroy(); return false; }
		});

// this was an attempt to update the displayed value to local time, but doesn't work
//		disp.innerHTML = getLocalDate(new Date(elem.value)).toLocaleString()
	}
};
KIC.UI.getFileBlobUrl = function( id ) {
	return '/FileBlob.ashx?id='+id;
};
KIC.UI.getLibraryBlobUrl = function( id ) {
	return '/LibraryBlob.ashx?id='+id;
};

KIC.UI.syncPictureHelper = function( idField, elem, removeButton ) {
	var file_id = $(idField).value;
	var img = $(elem);
	if ( file_id !== '' && file_id != '0' ) {
		img.src =  KIC.UI.getFileBlobUrl( file_id );
		KIC.UI.enableButton(removeButton);
	}
	else {
		img.src = '/images/no_pic.gif';
		KIC.UI.disableButton(removeButton);
	}
};

KIC.UI.syncFileLink = function( hidden, hyperlink, button ) {
	var file_id = $(hidden).value;
	var link_elem = $(hyperlink);
	var btn_elem  = $(button);
	if ( file_id !== '' && file_id !== '0' && file_id !== 0 ) {
		link_elem.href = KIC.UI.getFileBlobUrl( file_id );
		KIC.UI.show(link_elem);
		KIC.UI.enableButton( button );
	}
	else {
		KIC.UI.hide(link_elem);
		KIC.UI.disableButton( button );
	}
};

///////////////////////////////////////////////////////////////////////////
//	tinyMCE Editor related methods
///////////////////////////////////////////////////////////////////////////

KIC.UI.tinyMCEEventHandler = function ( e ) {};

KIC.UI.convertEditor = function( id, index ) {
	var elem, READONLY_INDEX, ed;
	READONLY_INDEX = 2;
	
	if ( !KIC.UI.editorExists(id) ) {
		elem = $(id);
		if (elem && elem.style.display !== 'none' ) {
			if (elem.disabled || elem.readOnly) {
				// readonly
				tinyMCE.init( KIC.UI.EditorConfigs[READONLY_INDEX] );
			} else {
				tinyMCE.init( KIC.UI.EditorConfigs[index] );
			}
			//tinyMCE.execCommand( 'mceAddEditor', false, id );
			// manually perform steps of mceAddEditor, so we can add _isFinishedLoading property
			// NOTE: tinymce is the namespace, tinyMCE is an alias of tinymce.EditorManager
			// SEE ALSO: http://wiki.moxiecode.com/index.php/TinyMCE:API
			// Or, could possibly handle it like this:
			// http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/init_instance_callback
			ed = new tinymce.Editor(id, tinyMCE.settings);
			ed._isFinishedLoading = false;
			ed.onLoadContent.add(function(ed, o) { ed._isFinishedLoading = true; });
			ed.render();
		}
	}
};

// Only used and tested for Recipe ingredient control
// which is either present and enabled or not present.
// This works (the text can't be edited), but it doesn't
// hide the toolbar, so it's sort of useless.
KIC.UI.setEditorReadOnly = function( id, ro ) {
	var editor = KIC.UI.getEditorInstance(id);
	var d;
	if (editor)
	{
		d = editor.getDoc();
		if (ro)
		{
			editor.settings.readonly = true;
			d.designMode = 'Off';
		}
		else
		{
			editor.settings.readonly = false;
			d.designMode = 'On';
		}
	}
};

KIC.UI.convertTinyMCESimple = function( id ) {
	KIC.UI.convertEditor( id, 0 );
};

KIC.UI.convertTinyMCEFull = function( id ) {
	KIC.UI.convertEditor( id, 1 );
};

KIC.UI.removeTinyMCE = function( id ) {
	tinyMCE.execCommand( 'mceRemoveEditor', false, id );
};

KIC.UI.destroyEditors = function() {
	var id;
	for (id in tinyMCE.editors)	if (tinyMCE.editors.hasOwnProperty(id)) {
		KIC.UI.removeTinyMCE(id);
	}
};

KIC.UI.toggleEditor = function( elem_id, mode ) {
	var addBreaks = function( elem_id )	{
		var elem, val, foo;
		elem = $(elem_id);
		val = elem.value;
		// process away any paragraph tags
		val = val.replace(/<p[^>]*>/g, "");
		val = val.replace(/\s*<\/p>\s*/g, "<br/>");
		// add breaks for any remaining newlines
		val = val.replace(/\r{0,1}\n/g, "<br/>");
		// save value
		elem.value = val;
	};

	var editor = KIC.UI.getEditorInstance( elem_id );
	if ( editor ) { 
		if ( editor.isHidden() ) {
			addBreaks(elem_id);
		}
		tinyMCE.execCommand( 'mceToggleEditor', false, elem_id ); 
	} else { 
		// replace line breaks with br tags
		addBreaks(elem_id);

		if ( mode === "Full" ) {
			KIC.UI.convertTinyMCEFull( elem_id ); 
		} else {
			KIC.UI.convertTinyMCESimple( elem_id ); 
		}
	}
	
};

KIC.UI.editorExists = function( id ) {
	if (tinyMCE.get(id)) {
		return true;
	} else {
		return false;
	}
};

//
// This has to be used carefully; if the prototype of 
// tinymce.Editor changes, things could break elsewhere
//
KIC.UI.getEditorInstance = function( id ) {
	return tinyMCE.get(id);
};

KIC.UI.getActiveEditorId = function() {
	return tinyMCE.activeEditor.id;
};


// resetIframeForm - given the name of the iframe, reset the first form within
KIC.UI.resetIframeForm = function( name ) {
	for ( var i = 0; i < window.frames.length; i++ ) {
		// find the correct iframe
		var frame = window.frames[i];
		if ( frame.name == name ) 
		{
			// clear the first form in that frame
			frame.document.forms[0].reset();
		}
	}
};

// this is used to rebuild a drop down list with a new list of entries from a JSON object
KIC.UI.updateList = function(form_select, list, valueField, textField)
{
	KIC.UI.updateListHelper(form_select, list, 1, valueField, textField);
};

KIC.UI.updateListBox = function(form_select, list, valueField, textField)
{
	KIC.UI.updateListHelper(form_select, list, 0, valueField, textField);
};

KIC.UI.updateListHelper = function(form_select, list, startRow, valueField, textField)
{
	// list must not be null or undefined
	if (list === null || typeof list === "undefined")
		return;
	
	var i, x, text, value;
	form_select.length = startRow;
	
	// Most of the time, we use an IdValueTuple class
	if (!valueField) { valueField = "Id"; }
	if (!textField)  { textField = "Value"; }

	for ( i = 0; i < list.length; i++ ) 
	{
		x = list[i];
		// strip html
		text = x[textField];
		text = text.replace(/&reg;/g, "\u00AE");
		text = text.replace(/&copy;/g, "\u00A9");
		text = text.replace(/&trade;/g, "\u2122");
		text = text.replace(/&nbsp;/g, " ");
		text = text.replace(/<\/{0,1}[a-zA-Z0-9]+>/g, "");	// handle any html tags

		value = x[valueField];
		form_select.options[i + startRow] = new Option( text, value );
	}
};


//
// KIC.UI.PopupWindow object
//
KIC.UI.PopupWindow = {
	isOpen: false,
	onClose: null,
	dropDowns: []	// array of DropDownLists to hide when opening popup (workaround for IE6 bug)
};

KIC.UI.PopupWindow.open = function( title ) {
	this.isOpen = true;
	var i, e_id;
	for (i in this.dropDowns) if (this.dropDowns.hasOwnProperty(i)) {
		e_id = this.dropDowns[i];
		//debug(e_id);
		KIC.UI.hide(e_id);
	}
	KIC.UI.show('popform_container');
};

KIC.UI.PopupWindow.close = function() {
	this.isOpen = false;
	KIC.UI.hide('popform_container');
	var i, e_id;
	for (i in this.dropDowns) if (this.dropDowns.hasOwnProperty(i)) {
		e_id = this.dropDowns[i];
		//debug(e_id);
		KIC.UI.show(e_id);
	}
	if ( this.onClose ) {
		this.onClose.call();
	}
	this.onClose = null;
};

KIC.UI.PopupWindow.setTitle = function( title ) {
	setInnerHTML( $('tdPopupTitle'), title );
};

KIC.UI.PopupWindow.setContent = function( content ) {
	setInnerHTML( $('tdPopupContent'), content );
};

KIC.UI.PopupWindow.setOnClose = function( handler ) {
	this.onClose = handler;
};

KIC.UI.PopupWindow.setDropDowns = function( dd ) {
	// this only really needs to be done for IE6, but code isn't set up
	// at the moment to handle browser detection
	if (typeof dd !== "object" || !(dd instanceof Array)) {
		debug("Error: param not an array in KIC.UI.PopupWindow.setDropDowns");
		return;
	}
	this.dropDowns = dd;
};

KIC.UI.PopupWindow.clearDropDowns = function() {
	this.dropDowns = [];
};

// popup window for associated products
KIC.UI.ProductShowMoreInfo = function(id) {
	window.open( '/content/Product/MoreInfoView.aspx?id='+id, 'product_moreinfo_'+id, CSRPREVIEW_FEATURES );
};

///////////////////////////////////////////////////////////////////////////
// the incredible expanding search div
///////////////////////////////////////////////////////////////////////////
KIC.UI.searchExpandDiv = function()
{
	// widen search div
	var div = $('selector_top');
	div.style.width = "975px";
	
	// hide workspace div
	KIC.UI.hide('workspaces_top');

	// toggle "expand/collapse form" divs
	KIC.UI.show('tdMainMenuCollapseSearch');
	KIC.UI.hide('tdMainMenuExpandSearch');

	// set the select dropdown width
	var form = $('searchForm');
	KIC.UI.adjustForm(form, "500px");
};

KIC.UI.searchCollapseDiv = function()
{
	// remove search div width setting
	var div = $('selector_top');
	div.style.width = "";

	// show workspace div
	KIC.UI.show('workspaces_top');
	
	// toggle "expand/collapse form" divs
	KIC.UI.hide('tdMainMenuCollapseSearch');
	KIC.UI.show('tdMainMenuExpandSearch');

	// clear the select dropdown width
	var form = $('searchForm');
	KIC.UI.adjustForm(form, "");
};

KIC.UI.subsearchExpandDiv = function()
{
	// set search div width and height
	var div = $('subsearch_left');
	div.style.width = "925px";
	div.style.height = "392px";
	
	// hide workspace div
	KIC.UI.hide('subsearch_right');
	
	// toggle "expand/collapse form" divs
	KIC.UI.show('collapseSubsearch');
	KIC.UI.hide('expandSubsearch');

	// set the select dropdown width
	var form = $('subSearchForm');
	KIC.UI.adjustForm(form, "500px", true);
};

KIC.UI.subsearchCollapseDiv = function()
{
	// show workspace div
	KIC.UI.show('subsearch_right');
	
	// toggle "expand/collapse form" div
	KIC.UI.hide('collapseSubsearch');
	KIC.UI.show('expandSubsearch');

	// clear the select dropdown width
	var form = $('subSearchForm');
	KIC.UI.adjustForm(form, "");

	// don't know if this matters, but do this last just in case
	// remove search div width setting
	var div = $('subsearch_left');
	div.style.width = "";
	div.style.height = "";
};

KIC.UI.adjustForm = function(form, w, hack)
{
	var i, x, out, element, length;
	if (form) {
		for (i = 0; i < form.elements.length; i++)
		{
			element = form.elements[i];
			if ( element.type == 'select-multiple' || element.type == 'select-one' ) 
			{
				element.style.width = w;
				// there's something strange with the subsearch div and IE
				// it doesn't want to expand the size after it has been collapsed
				// that's what the hack is for
				if (hack) {
					length = element.options.length;
					element.options[length] = new Option( "-- clever hack --", "" );	// add something to force resize of select elem
					element.options.length = length;									// trim off hack item
				}
			}
		}
	}
};

///////////////////////////////////////////////////////////////////////////
// debug div
///////////////////////////////////////////////////////////////////////////
KIC.UI.closeDebugDiv = function()
{
	$('debug').innerHTML='';
	KIC.UI.hide('debug_container');
};


// create an alias for the UI object/namespace
// this is deprecated, future code should all use KIC.UI
var UI = KIC.UI;

