/**
 *	General functions
 */


/* Notification  */
var notification_reg___id;
function MarkNotificationAsRead(n_id)
{
	Ext.Ajax.request({
		url: '/pages/_handlers/notification/notification.asp',
		success: function(response, options){
			
 			var result = Ext.util.JSON.decode(response.responseText);                                             
			if (result.success == 'true')
			{
			}
			else
			{
			}
		},

		failure: function(){},
		params: 
		{
			cmd : 'mark_as_read',
			id  : n_id
		}
	});
}



function GetNotifications()
{
	Ext.Ajax.abort();
	Ext.Ajax.request({
		url: '/pages/_handlers/notification/notification.asp',
		success: function(response, options){
			
			if (response.responseText.indexOf('content') >= 0 && response.responseText.indexOf('success') >= 0)
			{
 				var result = Ext.util.JSON.decode(response.responseText);                                             
				if (result.success == 'true')
				{
					UpdateNotification(result.num, result.content);
				}
				else
				{
					
				}
			}
			else
			{
				clearInterval(notification_reg___id);
			}
		},

		failure: function(){},
		params: 
		{
			
		}
	});
}





function UpdateNotification(num, content)
{
	if ($("nf__panel_nm"))
	{
		$("nf__panel_nm").innerHTML = num;
	}
	
	if ($("nf__panel"))
	{
		$("nf__panel").innerHTML = content;
	}
	
}


function RegisterNotificationUpdate()
{
	notification_reg___id = setInterval ( "GetNotifications()", 60000 );
}


function CaseDetailsPageDisplayMode(mode)
{
	Ext.Ajax.abort();
	Ext.Ajax.request({
		url: '/pages/_handlers/case_details_page.asp',
		success: function(response, options){
			
 			var result = Ext.util.JSON.decode(response.responseText);                                             
			if (result.success == 'true')
			{
			}
			else
			{
			}
		},

		failure: function(){},
		params: 
		{
			mode : mode,
			cmd  : 'mode_change'
		}
	});
}






 
function AlertSound() 
{
	var obj=document.getElementById('alert_sound');
	PlayEmbedSound(obj);
}
function SuccessSound() 
{
	var obj=document.getElementById('success_sound');
	PlayEmbedSound(obj);
}

function PlayEmbedSound(obj)
{
	if (obj)
	{
		try
		{
			obj.Play();
		}
		catch(err)
		{
		}
	}
}

function ResponsibilityCheck()
{
	if (IsEmptyString($('cc_responsibility_val').value) || $('cc_responsibility_val').value == "0")
	{
		alert('Missing \'Who Pays for Change\'.');
		return false;
	}
	
	return true;
}

function UpdateBillingResponsibility(ty)
{
	
	$('cc_responsibility_val').value = ty;
	
	var bChkOrgClient	= false;
	var bChkOrgManu		= false;
	
	switch (ty+''){
		case "10":
			bChkOrgClient	= true;
			bChkOrgManu		= true;
			break;
		case "20":
			bChkOrgClient	= false;
			bChkOrgManu		= true;
			break;
		case "30":			
			bChkOrgClient	= false;
			bChkOrgManu		= false;
			break;
	}
	
	
	var overall_include_original = $('cc_bIncludeOriginalPrice').checked;
	if (!overall_include_original)
	{
		bChkOrgClient	= false;
		bChkOrgManu		= false;
	}
	
	var org_client_label_obj	= $('label_cc_bill_c_ori');
	var org_client_amt_obj		= $('amt_cc_bill_c_ori');
	var org_manu_label_obj		= $('label_cc_bill_m_ori');
	var org_manu_amt_obj		= $('amt_cc_bill_m_ori');
	
	var org_client_chk_obj		= $('chk_cc_bill_c_ori');
	var org_manu_chk_obj		= $('chk_cc_bill_m_ori');
	
	org_client_chk_obj.value	= (bChkOrgClient)? '1' : '0';
	org_manu_chk_obj.value		= (bChkOrgManu)  ? '1' : '0';
	
	org_client_label_obj.className	= (bChkOrgClient)? 'bill_normal' : 'bill_removed';
	org_manu_label_obj.className	= (bChkOrgManu)? 'bill_normal' : 'bill_removed';
	org_client_amt_obj.className	= (bChkOrgClient)? 'bill_normal' : 'bill_removed';
	org_manu_amt_obj.className		= (bChkOrgManu)? 'bill_normal' : 'bill_removed';
	
	UpdateBillingResponsibilityAmounts();
	
}


function UpdateBillingResponsibilityAmounts()
{
	var org_manu_amt_obj		= $('val_cc_bill_m_ori');
	var new_manu_amt_obj		= $('val_cc_bill_m_new');
	var total_manu_amt_obj		= $('amt_cc_bill_m_total');
	
	var org_client_amt_obj		= $('val_cc_bill_c_ori');
	var new_client_amt_obj		= $('val_cc_bill_c_new');
	var total_client_amt_obj	= $('amt_cc_bill_c_total');
	
	var org_client_chk_obj		= $('chk_cc_bill_c_ori');
	var org_manu_chk_obj		= $('chk_cc_bill_m_ori');
	
	var net_amt_obj				= $('amt_cc_bill_sb_total');
	
	var c_total = ((org_client_chk_obj.value == '1')? parseFloat(org_client_amt_obj.value) : 0.0) + parseFloat(new_client_amt_obj.value);
	var m_total = ((org_manu_chk_obj.value == '1')? parseFloat(org_manu_amt_obj.value) : 0.0)     + parseFloat(new_manu_amt_obj.value);
	
	total_client_amt_obj.innerHTML = FormatMoney(c_total);
	total_manu_amt_obj.innerHTML = FormatMoney(m_total);
	
	net_amt_obj.innerHTML = FormatMoney(m_total - c_total);
	
}


function FormatMoney(v)
{
	if (v >= 0)
		return "$" + FormatNum(v,2);
	else
		return "($" + FormatNum(-v,2) + ")";
	
}




function GotoCase(case_id, bViewOnly)
{
	window.location.href = '/pages/forward/view_case.asp?case_id=' + case_id + ((bViewOnly)?'&view_only=1':'');
}
function GotoCaseEx(case_id, style, bViewOnly)
{
	window.location.href = '/pages/forward/view_case.asp?style=' + style + '&case_id=' + case_id + ((bViewOnly)?'&view_only=1':'');
}


function UpdateOfficeLead(lead1, lead2)
{
	l1_obj = $('office_lead_1');
	l2_obj = $('office_lead_2');
	
	if (l1_obj)	l1_obj.innerHTML = lead1;
	if (l2_obj)	l2_obj.innerHTML = lead2;
}


function UpdatePanAndBarcode(pan, barcode)
{
	pan_obj = $('pan_num');
	barcode_obj = $('manufacturer_barcode');
	
	if (pan_obj)		pan_obj.innerHTML		= pan;
	if (barcode_obj)	barcode_obj.innerHTML	= barcode;
}


function toogleShowHideDivs(show_div_name, hide_div_name)
{
	var obj1 = $(show_div_name);
	var obj2 = $(hide_div_name);
	var obj3 = $(show_div_name + '_label');
	var obj4 = $(hide_div_name + '_label');
	
	if (obj1) obj1.style.display = "block";
	if (obj2) obj2.style.display = "none";
	if (obj3) obj3.style.fontWeight = "bold";
	if (obj4) obj4.style.fontWeight = "normal";

}

function SetSearchMode(val)
{
	if (getEl('search_mode')) getEl('search_mode').value = val;
}

function show_standard_popup(url, popup_name, left, top, width, height)
{
	show_popup(url, popup_name, 0, 0, left, top, 1, 0, 1, 0, width, height);
}

function show_popup(url, popup_name, screen_x, screen_y, left, top, resizable, toolbar, scrollbars, location, width, height)
{
	var pairs = 
	[
		'screenX', screen_x,
		'screenY', screen_y, 
		'left', left,
		'top', top,
		'resizable', resizable,
		'toolbar', toolbar,
		'scrollbars', scrollbars,
		'location', location,
		'width', width,
		'height', height
	];
	var features = hash_string(pairs, ', ');
	var win = window.open(url, popup_name, features);
	win.focus();
}

/**
	*	Sorting function for numeric types, needed by sort();
	*/
function sort_numeric(a, b)
{
	return a - b;
}
	
function sort_value(list_str, delimiter, order, bSortNumeric)
{
	var arr = my_split(list_str, delimiter);
	if (bSortNumeric)
		arr.sort(sort_numeric);
	else
		arr.sort();
	if (order)
		arr.reverse();
	return arr_to_str(arr, delimiter);
}

function my_split(str, delimiter)
{
	if (str && delimiter)
	{
		var arr = str.split(delimiter);
		var arr2 = new Array();
		var i;
		for (i=0; i<arr.length; i++)
		{
			if (arr[i] != '')
				arr2.push(arr[i]);
		}
		return arr2;
	}
	else
	{
		return new Array();
	}
}

/**
	*	Checks whether a target value exists in a comma separated list, or
	*	an array of values
	*	@param target the target value to search
	*	@param list_v the comma separated list, or the array of values
	*	@param delimiter the value separator (applicable only when list_v is a 
	*		   comma separated list)
	*/
function exists(target, list_v, delimiter)
{
	var arr = (typeof(list_v) == 'string') ? 
			list_v.split(delimiter) : list_v;
	var i;
	for (i=0; i<arr.length; i++)
	{
		if (arr[i] == target)
			return true;
	}	
	return false;
}

/**
	*	This function adds a value into a comma separated list
	*	It supports two different list format
	*	Example 1: ,abc,def,ghi,
	*	Example 2: abc,def,ghi
	*	@param v the value to add
	*	@param list_str the comma separated list in either the
	*		   format of example 1 or example 2
	*	@param delimiter the string separator
	*	@return the resulting list
	*/
function add_value(v, list_str, delimiter)
{
	if (!exists(v, list_str, ','))
	{
		var arr = my_split(list_str, delimiter);
		arr.push(v);
		return arr_to_str(arr, delimiter);
	}
	return list_str;
}

/**
	*	This function removes a value from a comma separated list
	*/
function remove_value(v, list_str, delimiter)
{
	var arr = my_split(list_str, delimiter);
	var i;
	var arr2 = new Array();
	for (i=0; i<arr.length; i++)
	{
		if (v != arr[i])
			arr2.push(arr[i]);
	}
	return arr_to_str(arr2, delimiter);
}

/**
	*	Convert an array into a comma separated list
	*	@param arr the input array
	*	@param delimiter the string separator
	*	@return the resulting string
	*/
function arr_to_str(arr, delimiter)
{
	if (!arr || arr.length == 0)
		return '';
	var r = arr[0];
	for (i=1; i<arr.length; i++)
	{
		r += delimiter + arr[i];
	}
	return r;
}

function combine_fields(list, delimiter)
{
	var i, str;
	str = '';
	for (i=0; i<list.length; i++)
	{
		str = str + list[i];
		if (i < list.length - 1)
			str += delimiter;
	}
	return str;
}

function hash_string(pairs, delimiter)
{
	var i, str;
	str = '';
	for (i=0; i<pairs.length; i+=2)
	{
		str = str + pairs[i] + '=' + pairs[i+1]; 
		if (i < pairs.length - 2)
			str += delimiter;
	}
	return str;
}

function trim_str(str) { return str.replace(/^\s+(.*?)\s+$/, '$1'); }							
function get_xml(ajaxResponse)																	
{																								
	var xmldoc = MTGXML.parse( RicoUtil.getContentAsString( ajaxResponse ) );					
	var myxml = xmldoc.getElementsByTagName('myxml')[0];										
	return myxml;																				
}																								
function retrieve(xml, tag_name)																
{																								
	return trim_str(RicoUtil.getContentAsString( xml.getElementsByTagName(tag_name)[0] ));		
}	

/* Show the state transit page */

function ShowTransitPage( case_id, title )
{	// Show the inline window
	return ShowTransitPageEx( case_id, title, false )	
}

function ShowTransitPageEx( case_id, title, bReloadParent )
{	// Show the inline window
	var url, title, width, height, x, y
	url = '/pages/_common/state_transit.asp?style=popup&case_id=' + case_id + '&bReloadParent=' + ((bReloadParent)? '1' : '0');
	showLayer( title, url, '', '', 830, 605, '');	
	return false;
}

function ShowRemakeApprovalPage( remake_id, case_id, title )
{
	// Show the inline window
	var url, title, width, height, x, y
	url = '/pages/admin/remake/remake_approve_empty.asp?style=popup&cmd=edit&id=' + remake_id + '&case_id=' + case_id;
	showLayer( title, url, '', '', 805, 605, '');	
	return false;
}


function ShowCasePopUp( case_id )
{
	var url = '/pages/forward/view_case.asp?style=popup&case_id=' + case_id;
	var win = window.open(url,'_blank','screenX=0, screenY=0, left=10,top=10, resizable=1, toolbar=0, scrollbars=1, location=0, width=1015, height=765');
	win.focus();
}

function ShowCasePrintOutEx( case_id, dtb )
{
	//InlineWindowUtils.show( iwin_def, '/pages/documents/templates/rx_template.asp?case_id=' + case_id, 'Prinout', 770, 550, 10, 10);
	var url = '/pages/documents/templates/rx_template.asp?bPrint=1&case_id=' + case_id + '&dtb=' + dtb;
	var win = window.open(url,'_blank','screenX=0, screenY=0, left=10,top=10, resizable=1, toolbar=0, scrollbars=1, location=0, width=1015, height=780');
	win.focus();
}

function ShowCasePrintOut( case_id )
{
	ShowCasePrintOutEx( case_id, "" )
}

function ShowCaseCheckinPrintOut( case_id , b_auto_print )
{
	var autoprint = (b_auto_print)? '&auto_print=1' : ''
	var url = '/pages/documents/templates/checkin_case_sheet.asp?case_id=' + case_id + autoprint;
	var win = window.open(url,'_blank','screenX=0, screenY=0, left=10,top=10, resizable=1, toolbar=0, scrollbars=1, location=0,width=770,height=550');
	win.focus();
}

function show_shipment_printout(order_id, cmds)
{
	var url = '/pages/documents/templates/shipment_info_sheet.asp?style=popup&order_id=' + order_id + '&cmds=' + cmds;	
	show_standard_popup(url, 'shipment_info', 100, 100, 750, 650);
}

function show_active_case_printout()
{
	var url = '/pages/documents/templates/active_case_summary.asp?cmds=cases,print';	
	show_standard_popup(url, 'active_case_info', 100, 100, 750, 650);
}

function ToggleMode( mode )
{
	if (!this.prev) this.prev = "basic";

	if (prev != mode) {
		var mode_btn = mode + "_btn";
		var prev_btn = prev + "_btn";
		
		//$(prev_btn).src = "/pub/images/icons/inactive/" + prev + ".png";
		//$(mode_btn).src = "/pub/images/icons/active/" + mode + ".png";
		
		$(prev_btn).className = 'cdp_display_mode_inactive';
		$(mode_btn).className = 'cdp_display_mode_active';
		
		ToggleModeMain(prev);
		ToggleModeMain(mode);
		
		this.prev = mode;
	}
	
	CaseDetailsPageDisplayMode(mode);
	
}

function ToggleModeMain( m )
{
	if (m == "basic") 
	{
		if ($('note'))
			LayerUtils.toggle($('note')); 
	}
	else if (m == "image")
	{
		if ($('atth'))
			LayerUtils.toggle($('atth'));
	}
	else if (m == "invoice")
	{
		if ($('invoicing'))
			LayerUtils.toggle($('invoicing'));
		if ($('accountsb'))
			LayerUtils.toggle($('accountsb'));
		if ($('accountmanu'))
			LayerUtils.toggle($('accountmanu'));
	}
	else
	{
		if ($('atth'))
			LayerUtils.toggle($('atth'));
		if ($('note'))
			LayerUtils.toggle($('note')); 
		if ($('event_log'))
			LayerUtils.toggle($('event_log')); 
		if ($('msg_his'))
			LayerUtils.toggle($('msg_his')); 
		if ($('qc_info'))
			LayerUtils.toggle($('qc_info'));
		if ($('shipment_info'))
			LayerUtils.toggle($('shipment_info'));
		if ($('invoicing'))
			LayerUtils.toggle($('invoicing'));
		if ($('accountsb'))
			LayerUtils.toggle($('accountsb'));
		if ($('accountmanu'))
			LayerUtils.toggle($('accountmanu'));
		if ($('linked_cases'))
			LayerUtils.toggle($('linked_cases'));
		if ($('feedback'))
			LayerUtils.toggle($('feedback'));
	}
}

function ToggleImg( img, src1, src2 )
{	
	if ( img.src.indexOf(src1) > 0 ) { img.src = src2 } else { img.src = src1 };
}

// ==============================================================================
// Short Cut Key - listener
// ==============================================================================
function CheckShortCutKey( e )
{	
	var code = EventUtils.getKeyCode(e);
	
	var clicked = false;
	
	//window.status = ' Short Key Pressed : ' +  EventUtils.getCharCode(e) ;	
	//window.status = ' Short Key Code Pressed : ' +  code ;
		
	// Esc is pressed
	if ( code == 27 ) {
		
		// close the pop up search screen		
		if ( window.parent ) 
		{			
			if ( window.parent.name == 'search_win' ) window.parent.close();							
			
			if ( IsIWinLayer() ) {				
				if (  window.parent && window.parent.iwin_def )
					window.parent.HideIWin();	// focus on iwin title bar
				else
					window.HideIWin();	// focus on iwin content
			}
			return false;
		}
		
		CloseMeOrGoBack();				
		return true;
	}

	// S is pressed - Save	
	if ( ( e.ctrlKey == true ) && ( code == 83 ) ) {		
		ClickIfExist( $('dbfrm_update') ); 
		ClickIfExist( $('dbfrm_new') );		
		ClickIfExist( $('create') );
		ClickIfExist( $('new') );
		return;
	}

	// A is pressed - Show all
	if ( ( e.ctrlKey == true ) && ( code == 65 ) ) {		
		ClickIfExist( $('_dbfrm_showall_button') ); 		
		return;
	}

	// Short Cut Key if pressed
	if ( e.shiftKey && e.ctrlKey )
	{	
		//window.status = ' Short Key Code Pressed : ' +  code ;

		// M
		if ( code == 12 ) window.location.reload();		
	}

	return true;

	function ClickIfExist( obj ){
		if ( clicked ) return false;
		if ( obj ) obj.click();
	}
	
}

// A Post Onload function to check short cut key
function PageOnLoadPre()
{
	// Add an listener to the onkeypress event to whole window
	EventUtils.addEvent( window.document, "keydown", CheckShortCutKey );
	
	// Add event to the site search box
	if ( $('__site_search_box') ) EventUtils.addEvent($('__site_search_box'), 'keypress', SiteSearchHandler );	
}


function SiteSearchHandler(e)
{	
	var code				= EventUtils.getKeyCode(e);
	var search_value		= Trim( $('__site_search_box').value );
	var search_cond_type	= "patient"
	
	if ( IsValidCaseRef( search_value ) )
	{
		search_cond_type = "barcode"
	}
	
	
	
	
	
	// Pressed Enter
	if ( code == 13 ) 
	{	
		//alert('SiteSearchHandler');
		
		window.location  = '/pages/forward/view_case.asp?cmd=search' + 
							'&search_cond=' + search_value + '&search_cond_type=' + search_cond_type; 

		if ( CheckSearchStr(search_value, 'c ') ) {
			// for claim ref			
			//window.location = '/pages/claims/Claim.asp?cmd=search&search_sub_ref=' + ExractSearchStr(search_value);	
		}else if ( CheckSearchStr(search_value, 'm ') ) {
			// for member history			
			//window.location = '/pages/search/insuredmember.asp?cmd=search&member_name=' + ExractSearchStr(search_value);	
		}else if ( CheckSearchStr(search_value, 'p ') ) {
			// for plan checking
			//window.location = '/pages/plans/plan.asp?cmd=search&search=' + ExractSearchStr(search_value);	
		}else{
			// for group number
			//window.location = '/pages/policies/Policy.asp?cmd=search&group_no=' + search_value;	
		}
		return false;
	}
	return true;

	function ExractSearchStr(s){return s.substring(2,s.length);}
	function CheckSearchStr(s, pref){ return (s.toLowerCase().indexOf(pref) >= 0 ) }
}


/*
 * Check whether a barcode of a case is valid
 */
function IsValidCaseRef( ref )
{
	// ---------------------------------
	// Check ref format
	// ---------------------------------
	var regex = new RegExp("^S[0-9]{6}-[0-9]{5}$");
	
	if ( regex.exec(ref) == null )
		return false;

	// ---------------------------------
	// Check ref check digit
	// ---------------------------------
	var sum = 0;
	var check_digit = parseInt( ref.charAt(ref.length-1) );
	
	for (var i=0; i<ref.length-1; i++)
	{	
		// Get ASCII of each char, sum up
		sum += ( (i+1) * ref.charCodeAt(i) );
	}
	
	sum += check_digit;
	
	// mod 0 = check digit
	return (sum % 9) == 0;
}


// ================================================
//  A class for creating a dragging panel
// ================================================
/*
this.element		= $(element);
this.menubar	= $(element + '_hdr__' );
this.container.	= $(element + '_container__' );
*/
var MyClass = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}
DragScrollable = MyClass.create();
DragScrollable.prototype = 
{
  initialize: function(element) 
  {
    this.element		= $(element);
    this.menubar		= $(element + '_hdr__' );
    this.container		= $(element + '_container__' );    
    if ( !this.menubar )	this.menubar = this.element;
	if ( !this.container )	this.container = this.element;
    this.active = false;
    this.scrolling = false;
    this.menubar.style.cursor = 'pointer';
    this.eventMouseDown = this.startScroll.bindAsEventListener(this);
    this.eventMouseUp   = this.endScroll.bindAsEventListener(this);
    this.eventMouseMove = this.scroll.bindAsEventListener(this);
    Event.observe(this.menubar, 'mousedown', this.eventMouseDown);
  },
  destroy: function() {
    Event.stopObserving(this.menubar, 'mousedown', this.eventMouseDown);
    Event.stopObserving(document, 'mouseup', this.eventMouseUp);
    Event.stopObserving(document, 'mousemove', this.eventMouseMove);
  },
  startScroll: function(event) {	
  
    this.startX = Event.pointerX(event);
    this.startY = Event.pointerY(event);
    if (Event.isLeftClick(event) && 
		(this.startX < this.container.offsetLeft + this.container.clientWidth) && 
		(this.startY < this.container.offsetTop + this.container.clientHeight)) 
    { 
      this.menubar.style.cursor = 'move';
      Event.observe(document, 'mouseup', this.eventMouseUp);
      Event.observe(document, 'mousemove', this.eventMouseMove);
      this.active = true;
      Event.stop(event);
    }
  },
  endScroll: function(event) {
//	MTG.LayerUtils.setOpacity(  this.container, 100 );
    this.menubar.style.cursor = 'pointer';
    this.active = false;
    Event.stopObserving(document, 'mouseup', this.eventMouseUp);
    Event.stopObserving(document, 'mousemove', this.eventMouseMove);
    Event.stop(event);
  },
  scroll: function(event) {  
    if (this.active) 
    {
      var dx, dy
      dx = Event.pointerX(event) - this.startX ;
      dy = Event.pointerY(event) - this.startY       
      this.container.style.top =  parseFloat( this.container.style.top ||0 ) + dy + 'px' ;
      this.container.style.left = parseFloat( this.container.style.left||0 ) + dx + 'px' ;      
      this.startX = Event.pointerX(event);
      this.startY = Event.pointerY(event);      
  //    MTG.LayerUtils.setOpacity( this.container, 50 );
    }
    Event.stop(event);
  }, 
  
  // set the content of the 
  setTitle: function( s ) 
  {
	this.menubar.innerHTML = '<table cellpadding=0 cellspacing=0 border=0 width=300 >' + 
							'<tr>'+ 		
							'<td align=center ><div class=dragTitle nowrap>' + s + '</div></td>' + 
							'<td width=10 nowrap >' + 
								'<div class=dragTitle></div>' +
							'</td>' + 
							'</tr>' + 
							'</table>';							
		//onclick="LayerUtils.hide(\'' + this.container.id + '\'); "							
  },
  
  // set the content of the 
  setContent: function( s ) 
  {
	this.element.innerHTML = s;
  },
  
  hide : function()
  {
	LayerUtils.hide( this.container );
  }, 
  
  showAtCenter : function()
  {
	LayerUtils.showAtCenter( this.container );	
  }  
}



function CreateDragDiv( divId, title, content )
{
	var containerId, bHeader
	
	bHeader = ( Trim(title).length != 0 )

	// display a header if there is a title
	if ( bHeader ) containerId = divId + '_container__'; else container = divId;
	// dynamically create a div element if no exist
	var oDiv = MyDOMUtils.addDivIfNotExist( containerId );
	Element.setStyle( oDiv, { zIndex:'20' });
	oDiv.innerHTML = '';
	oDiv.className		= 'dragTable';
	
	Position.absolutize( oDiv );
	//MTG.LayerUtils.hide( oDiv );
	var titleDiv, contentDiv 
	if ( bHeader ) 
	{	
		titleDiv					= document.createElement("DIV");
		titleDiv.id					= divId + '_hdr__';
		titleDiv.className			= 'dragTitle';
				
		titleDiv.innerHTML = 			
		'<table cellpadding=0 cellspacing=0 border=1 width=100%  >' + 
		'<tr>'+ 		
		'<td align=center ><div class=dragTitle >' + title + '</div></td>' + 
		'<td width=10 nowrap onclick="LayerUtils.hide(\'' + oDiv.id + '\'); " >' + 
			'<div  class=dragTitle >X&nbsp;</div>' +
		'</td>' + 
		'</tr>' + 
		'</table>'

		contentDiv					= document.createElement("DIV");			
		contentDiv.id				= divId ;			
		contentDiv.innerHTML		= content;
		contentDiv.className		= 'dragContent';

		oDiv.appendChild(titleDiv);
		oDiv.appendChild(contentDiv);

	}else
	{
		oDiv.className = 'dragContent';
	}

	// create a draggable object
	var da = new DragScrollable( divId );		
	return da;
}


MyDOMUtils = new function(){
	
	//dynamiccally create a div, if the div does not already exist
	this.addDivIfNotExist = function(divID, bTail)
	{
		var oDiv = $(divID)
		if(!oDiv)
		{
			oDiv = document.createElement("DIV");
			oDiv.id = divID;				
			if ( document.body ){
				if ( bTail ) document.body.appendChild(oDiv);				
				else document.body.insertBefore(oDiv, document.body.firstChild)
			} else alert('No document.body found ');			
		}

		oDiv.style.position = 'absolute';
		
		return oDiv;
	}
}


function ShowAdminHelp(user_type)
{
	var link = "";
	if (user_type == "ssn")
		//link = '/pub/manual/smartsmile/index.html';
		link = '/pages/manual/smartsmile/index.html';
	else if (user_type == "client")
		link = '/pages/manual/client/index.html';
	else if (user_type == "lab")
		link = '/pages/manual/lab/index.html';
		
	ShowPopUpScreen( link, 850, 800, '_blank' );	
	return false;
}


function ShowPopUpScreen( url, width, height, name )
{	
	//var h=600;
	var h=height
	var w=width;
	//var toppos1=screen.height/2-(h-50)/2;
	var l=screen.width-w-30  ;
	str='scrollbars=1, status=1, resizable=1,top='+0+',left='+l+',width='+w+',height='+h;
	newWindow=window.open( url ,name, str );
	newWindow.focus();
}

function TB(val)
{
	return (val.toLowerCase() == "true")
}

function LdText()
{
	return '<div style="width:100%;" ><img src=/vbinc/images/mtg_loading2.gif > Loading...</div>'
}

function siteCheckPasswordRule(password)
{
	return true;
}


function HightLighthRow( id, color )
{   
	if ( $(id) )
	{
		$(id).style.backgroundColor = color;
	}	
}

function AppendStr( str, s, sep )
{
	if (IsEmptyString(s))
		return str;
	else if (IsEmptyString(str)) 
		return s;
	else
		return str + sep + s;
}

// email - complete text from the address textbox
function EmailAddressValidation(email)
{
	var i;
	var arr = email.split(";");
	var exp_1 = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?";
	var exp_2 = "^[ A-Za-z0-9!#$%&'*+/=?^_`{|}~-]*[ ]*<" + exp_1 + ">$";
	var exp_3 = "^[\"][ \"A-Za-z0-9!#$%&'*+/=?^_`{|}~-]*[\"][ ]*<" + exp_1 + ">$";
	var reg_1 = new RegExp("^" + exp_1 + "$");
	var reg_2 = new RegExp(exp_2);
	var reg_3 = new RegExp(exp_3);
	
	for (i=0; i<arr.length; i++)
	{
		var tmp = Trim(arr[i]);
		//alert(tmp + " - " + reg_1.test(tmp) + " - " + reg_2.test(tmp) + " - " + reg_3.test(tmp));
		//alert(tmp + " - " + tmp.match(reg_1) + " - " + tmp.match(reg_2));
		if (!reg_1.test(tmp) && !reg_2.test(tmp) && !reg_3.test(tmp))
			return false;
	}
	
	return true;
}

function MarkWarningField(field)
{
	if ( field && field.style ) field.style['background'] = '#ffcccc' ;
	focusOnField(field)
}

/*
Exapmple:
<a href="http://www.yahoo.com" 
			onMouseover="ShowToolTip(tobj, 'Hong Kong', 59, 'lightyellow' )"; 
			onMouseout="HidedToolTip(tobj)" 
>Search Engine</a>

<body>
<div id="dhtmltooltip" style=" font-size:10; font-family:Arial; position: absolute; width: 150px; border: 1px solid black; padding: 2px; background-color: lightyellow; visibility: hidden; z-index: 100; " ></div>
</body>

function ShowToolTipDiv( name )
	ShowToolTipDiv =	"<script language=""JavaScript"" src=""/jsinc/tooltip.js""></script>" & _ 
						"<div id=""" & name  & """ style="" font-size:10; font-family:Arial; position: absolute; width: 150px; border: 1px solid black; padding: 2px; background-color: lightyellow; visibility: hidden; z-index: 100; "" ></div>"
end function


if (document.all||(document.getElementById && !document.all)) 
var tobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""
*/


var ToolTipsUtil = new function(){

	this.ietruebody = function()
	{
		return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
	}


	this.ShowToolTip = function( tipobj, thetext, thewidth, thecolor, e)
	{
	
		//Customize x offset of tooltip
		//Customize y offset of tooltip
		this.ShowToolTipEx( tipobj, thetext, thewidth, thecolor, 5, 10, e)
	
	}


	// Javascript to show toop tip text e.g. onMouseover="ShowToolTip(tobj, 'Hong Kong', 59, 'lightyellow' )";
	this.ShowToolTipEx = function( tipobj, thetext, thewidth, thecolor, offsetxpoint, offsetypoint, e)
	{
		
		if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
		if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
		
		tipobj.innerHTML=thetext

		//if (enabletip)
		{
			var curX=((document.getElementById && !document.all))?e.pageX : event.x+this.ietruebody().scrollLeft;
			var curY=((document.getElementById && !document.all))?e.pageY : event.y+this.ietruebody().scrollTop;

			var head_obj = $('ext_head');
			var body_obj = $('ext_body');

			var extra_xoff = 0;
			var xoff = 0;
			var yoff = 0;

			if (head_obj && head_obj.childNodes[0] && head_obj.childNodes[0].childNodes[0])
			{
				extra_xoff  = 12;
			}
			if (body_obj && body_obj.childNodes[0] && body_obj.childNodes[0].childNodes[0])
			{
				xoff =  body_obj.childNodes[0].childNodes[0].scrollTop - extra_xoff;
				yoff = body_obj.childNodes[0].childNodes[0].scrollLeft;
			}

			//Find out how close the mouse is to the corner of the window
			var rightedge=document.all&&!window.opera? this.ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
			var bottomedge=document.all&&!window.opera? this.ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20

			var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000

			//if the horizontal distance isn't enough to accomodate the width of the context menu
			if (rightedge<tipobj.offsetWidth)
			
			//move the horizontal position of the menu to the left by it's width
			tipobj.style.left=document.all? this.ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+yoff+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+yoff+"px"
			else if (curX<leftedge)
			tipobj.style.left=5+yoff+"px"
			else
			
			//position the horizontal position of the menu where the mouse is positioned
			
			
			tipobj.style.left=curX+offsetxpoint+yoff+"px"

			//same concept with the vertical position
			if (bottomedge<tipobj.offsetHeight)
			tipobj.style.top=document.all? this.ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+xoff+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+xoff+"px"
			else
			tipobj.style.top=curY+offsetypoint+xoff+"px"
			tipobj.style.visibility="visible"
		}
	}

	this.HidedToolTip = function(tipobj)
	{
		if ((document.getElementById && !document.all)||document.all){
			tipobj.style.visibility="hidden"
			tipobj.style.left="-1000px"
			tipobj.style.backgroundColor=''
			tipobj.style.width=''
		}
	}
}


/* Event Functions */

// Add an event to the obj given
// event_name refers to the event trigger, without the "on", like click or mouseover
// func_name refers to the function callback when event is triggered
function actbAddEvent(obj,event_name,func_name){
	if (obj.attachEvent){
		obj.attachEvent("on"+event_name, func_name);
	}else if(obj.addEventListener){
		obj.addEventListener(event_name,func_name,true);
	}else{
		obj["on"+event_name] = func_name;
	}
}

// Removes an event from the object
function actbRemoveEvent(obj,event_name,func_name){
	if (obj.detachEvent){
		obj.detachEvent("on"+event_name,func_name);
	}else if(obj.removeEventListener){
		obj.removeEventListener(event_name,func_name,true);
	}else{
		obj["on"+event_name] = null;
	}
}

// Stop an event from bubbling up the event DOM
function actbStopEvent(evt){
	evt || window.event;
	if (evt.stopPropagation){
		evt.stopPropagation();
		evt.preventDefault();
	}else if(typeof evt.cancelBubble != "undefined"){
		evt.cancelBubble = true;
		evt.returnValue = false;
	}
	return false;
}

// Get the obj that starts the event
function actbGetElement(evt){
	if (window.event){
		return window.event.srcElement;
	}else{
		return evt.currentTarget;
	}
}
// Get the obj that triggers off the event
function actbGetTargetElement(evt){
	if (window.event){
		return window.event.srcElement;
	}else{
		return evt.target;
	}
}
// For IE only, stops the obj from being selected
function actbStopSelect(obj){
	if (typeof obj.onselectstart != 'undefined'){
		actbAddEvent(obj,"selectstart",function(){ return false;});
	}
}

/*    Caret Functions     */

// Get the end position of the caret in the object. Note that the obj needs to be in focus first
function actbGetCaretEnd(obj){
	if(typeof obj.selectionEnd != "undefined"){
		return obj.selectionEnd;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		try{
			var Lp = M.duplicate();
			Lp.moveToElementText(obj);
		}catch(e){
			var Lp=obj.createTextRange();
		}
		Lp.setEndPoint("EndToEnd",M);
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;
	}
}
// Get the start position of the caret in the object
function actbGetCaretStart(obj){
	if(typeof obj.selectionStart != "undefined"){
		return obj.selectionStart;
	}else if(document.selection&&document.selection.createRange){
		var M=document.selection.createRange();
		try{
			var Lp = M.duplicate();
			Lp.moveToElementText(obj);
		}catch(e){
			var Lp=obj.createTextRange();
		}
		try{
			Lp.setEndPoint("EndToStart",M);
		}catch(ee){
			return -1;
		}
		var rb=Lp.text.length;
		if(rb>obj.value.length){
			return -1;
		}
		return rb;
	}
}
// sets the caret position to l in the object
function actbSetCaret(obj,l){
	obj.focus();
	if (obj.setSelectionRange){
		obj.setSelectionRange(l,l);
	}else if(obj.createTextRange){
		m = obj.createTextRange();		
		m.moveStart('character',l);
		m.collapse();
		m.select();
	}
}
// sets the caret selection from s to e in the object
function actbSetSelection(obj,s,e){
	obj.focus();
	if (obj.setSelectionRange){
		obj.setSelectionRange(s,e);
	}else if(obj.createTextRange){
		m = obj.createTextRange();		
		m.moveStart('character',s);
		m.moveEnd('character',e);
		m.select();
	}
}

/*    Escape function   */
String.prototype.addslashes = function(){
	return this.replace(/(["\\\.\|\[\]\^\*\+\?\$\(\)])/g, '\\$1');
}
String.prototype.trim = function () {
    return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};
/* --- Escape --- */

/* Offset position from top of the screen */
function actbCurTop(obj){
	toreturn = 0;
	while(obj){
		toreturn += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return toreturn;
}
function actbCurLeft(obj){
	toreturn = 0;
	while(obj){
		toreturn += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return toreturn;
}
/* ------ End of Offset function ------- */

/* Types Function */

// is a given input a number?
function actbIsNumber(a) {
    return typeof a == 'number' && isFinite(a);
}

/* Object Functions */

function actbReplaceHTML(obj,text){
	while(el = obj.childNodes[0]){
		obj.removeChild(el);
	};
	obj.appendChild(document.createTextNode(text));
}

function actb(obj, ca, sql, sql_search_field, auto_complete_fields, warn_div_id){
	/* ---- Public Variables ---- */
	this.actb_timeOut = -1; // Autocomplete Timeout in ms (-1: autocomplete never time out)
	this.actb_lim = 10;    // Number of elements autocomplete can show (-1: no limit)
	this.actb_firstText = false; // should the auto complete be limited to the beginning of keyword?
	this.actb_mouse = true; // Enable Mouse Support
	this.actb_delimiter = new Array();  // Delimiter for multiple autocomplete. Set it to empty array for single autocomplete
	/* this.actb_delimiter = new Array(';',','); */ // Delimiter for multiple autocomplete. Set it to empty array for single autocomplete
	this.actb_startcheck = 1; // Show widget only after this number of characters is typed in.
	/* ---- Public Variables ---- */

	/* --- Styles --- */
	this.actb_bgColor = '#f2f2f2';
	this.actb_textColor = '#222222';
	this.actb_hColor = '#add2ff';
	this.actb_fFamily = 'Verdana';
	this.actb_fSize = '11px';
	this.actb_hStyle = 'text-decoration:underline;font-weight="bold"';
	this.actb_borderStyle = "1px solid #cccccc";
	/* --- Styles --- */

	/* ---- Private Variables ---- */
	var actb_delimwords = new Array();
	var actb_cdelimword = 0;
	var actb_delimchar = new Array();
	var actb_display = false;
	var actb_pos = 0;
	var actb_total = 0;
	var actb_curr = null;
	var actb_rangeu = 0;
	var actb_ranged = 0;
	var actb_bool = new Array();
	var actb_pre = 0;
	var actb_toid;
	var actb_tomake = false;
	var actb_getpre = "";
//	var actb_mouse_on_list = 1;
	var actb_mouse_on_list = 0;
	var actb_kwcount = 0;
	var actb_caretmove = false;
	this.actb_keyword_selected = false;
	this.actb_keywords = new Array();
	/* ---- Private Variables---- */
	
	this.actb_keywords = ca;
	this.actb_asyncLoaded = false;
	this.actb_sql = sql;
	this.actb_sql_search_field = sql_search_field;
	this.actb_auto_complete_fields = auto_complete_fields;
	this.actb_warn_div_id = warn_div_id;


	this.actb_pre_word_insert_custom_func = "";
	this.actb_post_word_insert_custom_func = "";

	this.actb_clear_select = true; // enable/disable blur auto hit enter

	this.actb_pre_select_first_item = true; // enable/disable pre select the first item of the suggested items

	this.actb_force_penter = false; // forcing the enter action even there is no suggestion display

	var actb_self = this;

	actb_curr = obj;
	
	actbAddEvent(actb_curr,"focus",actb_setup);
	//initActb();
	
	
	
	
	function initActb(obj)
	{
		if (!actb_self.actb_asyncLoaded)
		{
			actb_self.actb_asyncLoaded = loadKeywordFromServer();
		}
	}
	
	function actb_setup(){
	
		actbAddEvent(document,"keydown",actb_checkkey);
		actbAddEvent(actb_curr,"blur",actb_clear);
		actbAddEvent(document,"keypress",actb_keypress);
	}

	function actb_clear(evt){
		// press enter to cater for the direct pasting of matched value and textbox blur by clicking other areas
		if (actb_self.actb_clear_select)
			actb_penter();
	
		if (!actb_self.actb_keyword_selected && actb_curr.value != '') addWarnMsg();
			
		if (!evt) evt = event;
		actbRemoveEvent(document,"keydown",actb_checkkey);
		actbRemoveEvent(actb_curr,"blur",actb_clear);
		actbRemoveEvent(document,"keypress",actb_keypress);
		actb_removedisp();				
	}
	function actb_parse(n){
		if (actb_self.actb_delimiter.length > 0){
			var t = actb_delimwords[actb_cdelimword].trim().addslashes();
			var plen = actb_delimwords[actb_cdelimword].trim().length;
		}else{
			var t = actb_curr.value.addslashes();
			var plen = actb_curr.value.length;
		}
		var tobuild = '';
		var i;

		if (actb_self.actb_firstText){
			var re = new RegExp("^" + t, "i");
		}else{
			var re = new RegExp(t, "i");
		}
		var p = n.search(re);
				
		for (i=0;i<p;i++){
			tobuild += n.substr(i,1);
		}
		tobuild += "<font style='"+(actb_self.actb_hStyle)+"'>"
		for (i=p;i<plen+p;i++){
			tobuild += n.substr(i,1);
		}
		tobuild += "</font>";
			for (i=plen+p;i<n.length;i++){
			tobuild += n.substr(i,1);
		}
		return tobuild;
	}
	function actb_generate(){
		
		if (document.getElementById('tat_table')){ actb_display = false;document.body.removeChild(document.getElementById('tat_table')); } 
		if (actb_kwcount == 0){
			actb_display = false;
			return;
		}
		a = document.createElement('table');
		a.cellSpacing='1px';
		a.cellPadding='2px';
		a.style.position='absolute';
		a.style.zIndex='1000';
		a.style.top = eval(actbCurTop(actb_curr) + actb_curr.offsetHeight) + "px";
		a.style.left = actbCurLeft(actb_curr) + "px";
		a.style.backgroundColor=actb_self.actb_bgColor;
		a.style.border=actb_self.actb_borderStyle;
		a.id = 'tat_table';
		document.body.appendChild(a);
		var i;
		var first = true;
		var j = 1;
		if (actb_self.actb_mouse){
			a.onmouseout = actb_table_unfocus;
			a.onmouseover = actb_table_focus;
		}
		var counter = 0;
		var field_index = actb_self.actb_keywords[0].indexOf(actb_self.actb_sql_search_field)
		for (i=1;i<actb_self.actb_keywords.length;i++){
			if (actb_bool[i]){
				counter++;
				r = a.insertRow(-1);
				if (first && !actb_tomake){
					if (actb_self.actb_pre_select_first_item)
					{
						r.style.backgroundColor = actb_self.actb_hColor;
						first = false;
						actb_pos = counter;
					}
					else
					{
						//r.style.backgroundColor = actb_self.actb_hColor;
						first = true;
						actb_pos = 0;
					}
				}else if(actb_pre == i){
					r.style.backgroundColor = actb_self.actb_hColor;
					first = false;
					actb_pos = counter;
				}else{
					r.style.backgroundColor = actb_self.actb_bgColor;
				}
				r.id = 'tat_tr'+(j);
				c = r.insertCell(-1);
				c.style.color = actb_self.actb_textColor;
				c.style.fontFamily = actb_self.actb_fFamily;
				c.style.fontSize = actb_self.actb_fSize;
				c.innerHTML = actb_parse(actb_self.actb_keywords[i][field_index]);
				c.id = 'tat_td'+(j);
				c.setAttribute('pos',j);
				if (actb_self.actb_mouse){
					c.style.cursor = 'pointer';
					c.onclick=actb_mouseclick;
					c.onmouseover = actb_table_highlight;
				}
				j++;
			}
			if (j - 1 == actb_self.actb_lim && j < actb_total){
				r = a.insertRow(-1);
				r.style.backgroundColor = actb_self.actb_bgColor;
				c = r.insertCell(-1);
				c.style.color = actb_self.actb_textColor;
				c.style.fontFamily = 'arial narrow';
				c.style.fontSize = actb_self.actb_fSize;
				c.align='center';
				actbReplaceHTML(c,'\\/');
				if (actb_self.actb_mouse){
					c.style.cursor = 'pointer';
					c.onclick = actb_mouse_down;
				}
				break;
			}
		}
		actb_rangeu = 1;
		actb_ranged = j-1;
		actb_display = true;
		if (actb_pos <= 0) actb_pos = (actb_self.actb_pre_select_first_item)? 1 : 0;
	}
	function actb_remake(){
		document.body.removeChild(document.getElementById('tat_table'));
		a = document.createElement('table');
		a.cellSpacing='1px';
		a.cellPadding='2px';
		a.style.position='absolute';
		a.style.zIndex='1000';
		a.style.top = eval(actbCurTop(actb_curr) + actb_curr.offsetHeight) + "px";
		a.style.left = actbCurLeft(actb_curr) + "px";
		a.style.backgroundColor=actb_self.actb_bgColor;
		a.style.border=actb_self.actb_borderStyle;
		a.id = 'tat_table';
		if (actb_self.actb_mouse){
			a.onmouseout= actb_table_unfocus;
			a.onmouseover=actb_table_focus;
		}
		document.body.appendChild(a);
		var i;
		var first = true;
		var j = 1;
		if (actb_rangeu > 1){
			r = a.insertRow(-1);
			r.style.backgroundColor = actb_self.actb_bgColor;
			c = r.insertCell(-1);
			c.style.color = actb_self.actb_textColor;
			c.style.fontFamily = 'arial narrow';
			c.style.fontSize = actb_self.actb_fSize;
			c.align='center';
			actbReplaceHTML(c,'/\\');
			if (actb_self.actb_mouse){
				c.style.cursor = 'pointer';
				c.onclick = actb_mouse_up;
			}
		}
		var field_index = actb_self.actb_keywords[0].indexOf(actb_self.actb_sql_search_field)
		for (i=1;i<actb_self.actb_keywords.length;i++){
			if (actb_bool[i]){
				if (j >= actb_rangeu && j <= actb_ranged){
					r = a.insertRow(-1);
					r.style.backgroundColor = actb_self.actb_bgColor;
					r.id = 'tat_tr'+(j);
					c = r.insertCell(-1);
					c.style.color = actb_self.actb_textColor;
					c.style.fontFamily = actb_self.actb_fFamily;
					c.style.fontSize = actb_self.actb_fSize;
					c.innerHTML = actb_parse(actb_self.actb_keywords[i][field_index]);
					c.id = 'tat_td'+(j);
					c.setAttribute('pos',j);
					if (actb_self.actb_mouse){
						c.style.cursor = 'pointer';
						c.onclick=actb_mouseclick;
						c.onmouseover = actb_table_highlight;
					}
					j++;
				}else{
					j++;
				}
			}
			if (j > actb_ranged) break;
		}
		if (j-1 < actb_total){
			r = a.insertRow(-1);
			r.style.backgroundColor = actb_self.actb_bgColor;
			c = r.insertCell(-1);
			c.style.color = actb_self.actb_textColor;
			c.style.fontFamily = 'arial narrow';
			c.style.fontSize = actb_self.actb_fSize;
			c.align='center';
			actbReplaceHTML(c,'\\/');
			if (actb_self.actb_mouse){
				c.style.cursor = 'pointer';
				c.onclick = actb_mouse_down;
			}
		}
	}
	function actb_goup(){
		if (!actb_display) return;
		if (actb_pos == 1) return;
		if (document.getElementById('tat_tr'+actb_pos))
			document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_bgColor;
		actb_pos--;
		if (actb_pos < actb_rangeu) actb_moveup();
		if (document.getElementById('tat_tr'+actb_pos))
			document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_hColor;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_self.actb_timeOut);
	}
	function actb_godown(){
		if (!actb_display) return;
		if (actb_pos == actb_total) return;
		if (document.getElementById('tat_tr'+actb_pos))
			document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_bgColor;
		actb_pos++;
		if (actb_pos > actb_ranged) actb_movedown();
		if (document.getElementById('tat_tr'+actb_pos))
			document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_hColor;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_self.actb_timeOut);
	}
	function actb_movedown(){
		actb_rangeu++;
		actb_ranged++;
		actb_remake();
	}
	function actb_moveup(){
		actb_rangeu--;
		actb_ranged--;
		actb_remake();
	}

	/* Mouse */
	function actb_mouse_down(){
		removeWarnMsg();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_bgColor;
		actb_pos++;
		actb_movedown();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_hColor;
		actb_curr.focus();
		actb_mouse_on_list = 0;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_self.actb_timeOut);
	}
	function actb_mouse_up(evt){
		removeWarnMsg();
		if (!evt) evt = event;
		if (evt.stopPropagation){
			evt.stopPropagation();
		}else{
			evt.cancelBubble = true;
		}
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_bgColor;
		actb_pos--;
		actb_moveup();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_hColor;
		actb_curr.focus();
		actb_mouse_on_list = 0;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list=0;actb_removedisp();},actb_self.actb_timeOut);
	}
	function actb_mouseclick(evt){	
		if (!evt) evt = event;
		if (!actb_display) return;
		actb_mouse_on_list = 0;
		actb_pos = this.getAttribute('pos');
		actb_penter();
	}
	function actb_table_focus(){	
		actb_mouse_on_list = 1;
	}
	function actb_table_unfocus(){
		actb_mouse_on_list = 0;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_self.actb_timeOut);
	}
	function actb_table_highlight(){
		actb_mouse_on_list = 1;
		if (document.getElementById('tat_tr'+actb_pos))
			document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_bgColor;
		actb_pos = this.getAttribute('pos');
		while (actb_pos < actb_rangeu) actb_moveup();
		while (actb_pos > actb_ranged) actb_movedown();
		document.getElementById('tat_tr'+actb_pos).style.backgroundColor = actb_self.actb_hColor;
		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_self.actb_timeOut);
	}
	/* ---- */	

	

	function actb_insertword(a){
		if (actb_self.actb_delimiter.length > 0){
			str = '';
			l=0;
			for (i=0;i<actb_delimwords.length;i++){
				if (actb_cdelimword == i){
					prespace = postspace = '';
					gotbreak = false;
					for (j=0;j<actb_delimwords[i].length;++j){
						if (actb_delimwords[i].charAt(j) != ' '){
							gotbreak = true;
							break;
						}
						prespace += ' ';
					}
					for (j=actb_delimwords[i].length-1;j>=0;--j){
						if (actb_delimwords[i].charAt(j) != ' ') break;
						postspace += ' ';
					}
					str += prespace;
					str += a;
					l = str.length;
					if (gotbreak) str += postspace;
				}else{
					str += actb_delimwords[i];
				}
				if (i != actb_delimwords.length - 1){
					str += actb_delimchar[i];
				}
			}		
			actb_curr.value = str;
			actbSetCaret(actb_curr,l);
		}else{		
			actb_curr.value = a;
		}
		actb_mouse_on_list = 0;
	}	
	
	// Set value of the specified field.
	function actb_insertval(field, val){
		if (actb_self.actb_delimiter.length > 0){
			str = '';
			l=0;
			for (i=0;i<actb_delimwords.length;i++){
				if (actb_cdelimword == i){
					prespace = postspace = '';
					gotbreak = false;
					for (j=0;j<actb_delimwords[i].length;++j){
						if (actb_delimwords[i].charAt(j) != ' '){
							gotbreak = true;
							break;
						}
						prespace += ' ';
					}
					for (j=actb_delimwords[i].length-1;j>=0;--j){
						if (actb_delimwords[i].charAt(j) != ' ') break;
						postspace += ' ';
					}
					str += prespace;
					str += val;
					l = str.length;
					if (gotbreak) str += postspace;
				}else{
					str += actb_delimwords[i];
				}
				if (i != actb_delimwords.length - 1){
					str += actb_delimchar[i];
				}
			}		
			field.value = str;
		}else{	
			field.value = val;
		}
	}	
	
	// Unset value of the specified field.
	function actb_removeval(field){
		field.value = "";
	}
	function actb_penter(){	
		if (!actb_display && !actb_self.actb_force_penter) return;	
		actb_display = false;
		actb_self.actb_keyword_selected = true;							
		removeWarnMsg();
		var word = '';
		var c = 0;
		var field_index;
		
		if (actb_self.actb_keywords[0])
		{
			field_index = actb_self.actb_keywords[0].indexOf(actb_self.actb_sql_search_field)
		
			for (var i=1;i<actb_self.actb_keywords.length;i++){
				if (actb_bool[i]) c++;
				if (c == actb_pos){
					word = actb_self.actb_keywords[i][field_index];
					if (actb_self.actb_auto_complete_fields != null){
						var field, index;
						// Set values of auto complete fields, if any.
						for (var j=0;j<actb_self.actb_auto_complete_fields.length;j++){
							field = actb_self.actb_auto_complete_fields[j][0];
							index = actb_self.actb_keywords[0].indexOf(actb_self.actb_auto_complete_fields[j][1]);
							actb_insertval(field, actb_self.actb_keywords[i][index]);
						}
					}
					break;
				}
			}
		}
		var ori_word = word;
		if (actb_self.actb_pre_word_insert_custom_func != "") {
			try {
				word = eval(actb_self.actb_pre_word_insert_custom_func + "(word)");
			}
			catch (e)
			{}
		}
		
		
		if (actb_pos > 0)
			actb_insertword(word);
		actb_removedisp();
		
		if (actb_self.actb_post_word_insert_custom_func != "") {
			try {
				eval(actb_self.actb_post_word_insert_custom_func + "(ori_word, word)");
			}
			catch (e)
			{}
		}
		
		l = actbGetCaretStart(actb_curr);
	}
	function actb_removedisp(){
		if (actb_mouse_on_list==0){
			actb_display = 0;
			if (document.getElementById('tat_table')){ document.body.removeChild(document.getElementById('tat_table')); }
			if (actb_toid) clearTimeout(actb_toid);
		}
	}
	function actb_keypress(e){
		if (actb_caretmove) actbStopEvent(e);
		return !actb_caretmove;
	}
	function actb_checkkey(evt){
	
		if (!evt) evt = event;
		a = evt.keyCode;
		caret_pos_start = actbGetCaretStart(actb_curr);
		actb_caretmove = 0;
		switch (a){
			case 38:
				actb_goup();
				actb_caretmove = 1;
				return false;
				break;
			case 40:
				actb_godown();
				actb_caretmove = 1;
				return false;
				break;
			case 13: case 9:			
				if (actb_self.actb_force_penter || actb_display){
					actb_caretmove = 1;
					actb_penter();
					return false;
				}else{
					return false;
				}
				break;
			default:
				actb_self.actb_keyword_selected = false;	
				removeWarnMsg();
				setTimeout(function(){actb_tocomplete(a)},50);
				break;
		}
	}

	function actb_tocomplete(kc){
		if (kc == 38 || kc == 40 || kc == 13) return;
		
		if (kc != 65535)
		{
			for (var i=0;i<actb_self.actb_auto_complete_fields.length;i++){
				field = actb_self.actb_auto_complete_fields[i][0];
				actb_removeval(field);
			}		
			loadKeywordFromServer();
			return;
		}		
		
		var i;
		
		
		
		if (actb_display){ 
			var word = 0;
			var c = 0;
			for (var i=1;i<=actb_self.actb_keywords.length;i++){
				if (actb_bool[i]) c++;
				if (c == actb_pos && actb_pos > 0){
					word = i;
					break;
				}
			}
			actb_pre = word;
		}else{ actb_pre = -1};
		
		if (actb_curr.value == ''){		
			actb_mouse_on_list = 0;
			actb_removedisp();
			return;
		}
		if (actb_self.actb_delimiter.length > 0){
			caret_pos_start = actbGetCaretStart(actb_curr);
			caret_pos_end = actbGetCaretEnd(actb_curr);
			
			delim_split = '';
			for (i=0;i<actb_self.actb_delimiter.length;i++){
				delim_split += actb_self.actb_delimiter[i];
			}
			delim_split = delim_split.addslashes();
			delim_split_rx = new RegExp("(["+delim_split+"])");
			c = 0;
			actb_delimwords = new Array();
			actb_delimwords[0] = '';
			for (i=0,j=actb_curr.value.length;i<actb_curr.value.length;i++,j--){
				if (actb_curr.value.substr(i,j).search(delim_split_rx) == 0){
					ma = actb_curr.value.substr(i,j).match(delim_split_rx);
					actb_delimchar[c] = ma[1];
					c++;
					actb_delimwords[c] = '';
				}else{
					actb_delimwords[c] += actb_curr.value.charAt(i);
				}
			}

			var l = 0;
			actb_cdelimword = -1;
			for (i=0;i<actb_delimwords.length;i++){
				if (caret_pos_end >= l && caret_pos_end <= l + actb_delimwords[i].length){
					actb_cdelimword = i;
				}
				l+=actb_delimwords[i].length + 1;
			}
			var ot = actb_delimwords[actb_cdelimword].trim(); 
			var t = actb_delimwords[actb_cdelimword].addslashes().trim();
		}else{
			var ot = actb_curr.value;
			var t = actb_curr.value.addslashes();
		}
		if (ot.length == 0){
			actb_mouse_on_list = 0;
			actb_removedisp();
		}
		if (ot.length < actb_self.actb_startcheck) return this;
		if (actb_self.actb_firstText){
			var re = new RegExp("^" + t, "i");
		}else{
			var re = new RegExp(t, "i");
		}

		actb_total = 0;
		actb_tomake = false;
		actb_kwcount = 0;
		var field_index = actb_self.actb_keywords[0].indexOf(actb_self.actb_sql_search_field)
		for (i=1;i<actb_self.actb_keywords.length;i++){
			actb_bool[i] = false;
			if (re.test(actb_self.actb_keywords[i][field_index])){
				actb_total++;
				actb_bool[i] = true;
				actb_kwcount++;
				if (actb_pre == i) actb_tomake = true;
			}
		}

		if (actb_toid) clearTimeout(actb_toid);
		if (actb_self.actb_timeOut > 0) actb_toid = setTimeout(function(){actb_mouse_on_list = 0;actb_removedisp();},actb_self.actb_timeOut);
		actb_generate();
	}
	return this;
	
	function loadKeywordFromServer()
	{
		if (this.actb_sql != "")
		{
			Ext.Ajax.abort();
			Ext.Ajax.request({
				url: '/vbinc/ajax_auto_complete/auto_complete_lookup.asp',
				success: loadKeywordSuccess,
				failure: loadKeywordFailed,
				params: { cmd: 'actb_query', sql: actb_self.actb_sql, search_field: actb_self.actb_sql_search_field, search_value: actb_curr.value }
			});
		}	
		return true;
	}
	
	function loadKeywordSuccess(conn, response, options)
	{
		var data = eval(conn.responseText);
		actb_self.actb_keywords = data;
		try
		{
			actb_tocomplete(65535);
		}catch (e)
		{	
			actb_removedisp();
		}
	}
	
	function loadKeywordFailed(conn, response, options)
	{
		alert("failed");
	}
	
	// Add warning msg to the warning div.
	function addWarnMsg()
	{
		var obj = document.getElementById(actb_self.actb_warn_div_id);
		if (obj) obj.innerHTML = 'No exact matches';				
	}
	
	// Remove warning msg from the warning div.
	function removeWarnMsg()
	{
		var obj = document.getElementById(actb_self.actb_warn_div_id);
		if (obj) obj.innerHTML = '';		
	}
	
}	
	
	
	/*
	
		EXTJS
		
		1) Ext.mtg.Msg.info("test");
		
	*/
	
	
	
	var mtg_msg_show_time = 5;
	Ext.ns("Ext.mtg");
	Ext.mtg.Msg = (function(){
		var msgCt, m;
		
		function createBox(t, s){
			return ['<div class="x-window-dlg">',
					'<h3>', t, '</h3><div class="ext-mb-icon"></div>', s, '<div class="x-clear"></div>',
					'</div>'].join('');
		}
	    
		function getIconEl(){
    		var iconEl = m.select(".ext-mb-icon").first();
       		Ext.each(iconEl.dom.className.split(" "), function(c){
       			iconEl.removeClass(c);
       		});
       		iconEl.addClass("ext-mb-icon");
       		return iconEl;
		}
	    
		var show = function(title, format){
   			if(!msgCt){
				msgCt = Ext.DomHelper.insertFirst(Ext.getBody(), {id:'msg-div'}, true);
			}
			msgCt.alignTo(Ext.getBody(), 't-t');
			var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
			m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
			m = m.boxWrap().addClass("x-box-blue");
			m.slideIn('t').pause(mtg_msg_show_time).ghost("t", {remove:true});
			m.on("click", function(){
				this.syncFx().ghost("t", {remove: false}).stopFx();
			}, m, {single: true});
		}
		
		function msg(){}
		
		Ext.override(msg, {
			show: show,
	        
			// note: here the pos of format and title are diff from that in show()
			info: function(format, title){
        		if(!title) title = "Information";
        		show(title, format);
        		getIconEl().addClass(Ext.Msg.INFO)
			},
	        
			warn: function(format, title){
        		if(!title) title = "Warning";
        		show(title, format);
        		getIconEl().addClass(Ext.Msg.WARNING)
			},
	        
			error: function(format, title){
        		if(!title) title = "Error";
        		show(title, format);
        		getIconEl().addClass(Ext.Msg.ERROR)
			},
	        
			listErrors: function(msg, title){
				if(msg.indexOf("\n") !== -1){
					var list = "";
					Ext.each(msg.split("\n"), function(m, idx){
						if(m == '') return true;
						list = list + (idx + 1) + ". " + m + "<br />";
					});
					msg = list;
				}
        		this.error(msg, title);
			}
		})
		
		return new msg();
	})();

	// message boxes
	Ext.apply(Ext.MessageBox, {

		listErrors: function(msg, title, fn, scope){
			if(msg.indexOf("\n") !== -1){
				var list = "";
				Ext.each(msg.split("\n"), function(m, idx){
					if(m == '') return true;
					list = list + (idx + 1) + ". " + m + "<br />";
				});
				msg = list;
			}
			Ext.MessageBox.error(msg, title, fn, scope);
		},

		error: function(msg, title, fn, scope){
			if(!title) title = "Error";	
			var cfg = {
				title: title,
				msg: msg,
				minWidth: 400,
				buttons: Ext.MessageBox.OK,
				icon: Ext.MessageBox.ERROR
			};
			if(typeof fn == 'function') cfg.fn = fn;
			if(scope) cfg.scope = scope;
			Ext.Msg.show(cfg);
		},
		
		warn: function(msg, title, fn, scope){
			if(!title) title = "Warning";
			var cfg = {
				title: title,
				msg: msg,
				minWidth: 400,
				buttons: Ext.MessageBox.OK,
				icon: Ext.MessageBox.WARNING
			};
			if(typeof fn == 'function') cfg.fn = fn;
			if(scope) cfg.scope = scope;
			Ext.Msg.show(cfg);
		},
		
		info: function(msg, title, fn, scope){
			if(!title) title = "Information";
			var cfg = {
				title: title,
				msg: msg,
				minWidth: 400,
				buttons: Ext.MessageBox.OK,
				icon: Ext.MessageBox.INFO
			};
			if(typeof fn == 'function') cfg.fn = fn;
			if(scope) cfg.scope = scope;
			Ext.Msg.show(cfg);
		}
	});
	Ext.MessageBox.show = (function(){
		loadMask.hide();
	}).createSequence(Ext.MessageBox.show);
	
	function ShowSiteMessagePrompt(msg)
	{
		ShowSiteMessagePromptEx(msg, mtg_msg_show_time);
	}
	
	function ShowSiteMessagePromptEx(msg, time)
	{
		var def = mtg_msg_show_time;
		mtg_msg_show_time = time;
		Ext.mtg.Msg.info(msg);
		mtg_msg_show_time = def;
	}
	
	function CheckMaxLength(obj, limit, txt)
	{
		if($(obj).value.length > limit) {
			alert('\'' + txt + '\' contains too much data. (max: '+limit+' characters)');
			$(obj).value = $(obj).value.substring(0, limit);
			return false;
		}
		return true;
	}
	
	function setScoreRadio(el, oriImg){
		var els = getElementsByName_iefix("span", "case_score_radio");
		var i;		
		for(i=0;i<els.length;i++){
			els[i].childNodes[1].style.color = "#000000"			
			els[i].childNodes[0].src = els[i].childNodes[0].src.replace("_S.png", ".png")			
		}
		el.childNodes[0].src = el.childNodes[0].src.replace(".png", "_S.png")
		el.childNodes[1].style.color = "#FFFFFF"
		el.childNodes[2].childNodes[0].click();
	}
	
	function ajaxCallBackForCaseSearchResult(){		
		var tmp_s = ""
				
		//Handle Quick search
		if(tmp_s == ""){			
			if($('quick_search_type')){
				tmp_s = searchTermsArr[$('quick_search_type').value] ? searchTermsArr[$('quick_search_type').value] : ""
			}
		}
				
		//From calendar view
		if(tmp_s == ""){
			var view_mode = $('view_mode').value
			var view_mode_date = $('view_mode_date').value
			
			if(view_mode_date){
				if(view_mode == "10" ){
					tmp_s = "New Cases Entered On " + view_mode_date
				}else if(view_mode == "20"){					
					tmp_s = "Ship by Date On " + view_mode_date
				}else if(view_mode == "30"){
					tmp_s = "Due Date On " + view_mode_date
				}else if(view_mode == "40"){
					tmp_s = "Arrival On " + view_mode_date
				}else{
					tmp_s = "Due Date On " + view_mode_date
				}				
			}
		}
		
		//Handle basic search
		if(tmp_s == ""){
			var search_master = $('search_master').value
			if(search_master) tmp_s = "(Search) " + search_master
		}
		
		//Handle advanced search				
		if(tmp_s == ""){	
			var field_arr;
			if(isIE()){
				field_arr  =["Case Ref. #", getElementByIdIEFix("search_ref") ? getElementByIdIEFix("search_ref").value : "", 
							"Flag", document.getElementsByName('case_flag_rd') ? getFlagText(getCheckedValues(document.getElementsByName('case_flag_rd'))) : "", 
							"Tooth #", getElementByIdIEFix("search_tooth_no") ? getElementByIdIEFix("search_tooth_no").value : "",
							"# Units",  getElementByIdIEFix("search_no_unit") ? getElementByIdIEFix("search_no_unit").value : "",
							"Patient", getElementByIdIEFix("search_patient") ? getElementByIdIEFix("search_patient").value : "",
							"Patient #", getElementByIdIEFix("search_patient_number") ? getElementByIdIEFix("search_patient_number").value : "",
							"Pan #", getElementByIdIEFix("search_subscriber_pan_number") ? getElementByIdIEFix("search_subscriber_pan_number").value : "",
							"Doctor", getElementByIdIEFix("search_doctor") ? getElementByIdIEFix("search_doctor").value : "",
							"Restoration", getElementByIdIEFix("search_restoration") ? getElementByIdIEFix("search_restoration").value : "",
							"Client Group", getElementByIdIEFix("search_client_group") ? getElementByIdIEFix("search_client_group").value : "",
							"Client Office", getElementByIdIEFix("search_client") ? getElementByIdIEFix("search_client").value : "", 
							"Manufacturer", getElementByIdIEFix("search_vendor") ? getElementByIdIEFix("search_vendor").value : "", 
							"Manufacturer's Barcode #", getElementByIdIEFix("vendor_barcode") ? getElementByIdIEFix("vendor_barcode").value : "",
							"Manufacturer Pan #", getElementByIdIEFix("search_pan_number") ? getElementByIdIEFix("search_pan_number").value : "", 
							"Creation Date From", getElementByIdIEFix("creation_from_dt") ? getElementByIdIEFix("creation_from_dt").value : "",
							"Creation Date To", getElementByIdIEFix("creation_to_dt") ? getElementByIdIEFix("creation_to_dt").value : "",
							"Due Date From", getElementByIdIEFix("due_from_dt") ? getElementByIdIEFix("due_from_dt").value : "",
							"Due Date To", getElementByIdIEFix("due_to_dt") ? getElementByIdIEFix("due_to_dt").value : ""]
			}else{
				field_arr  =["Case Ref. #", $("search_ref") ? $("search_ref").value : "", 
							"Flag", document.getElementsByName('case_flag_rd') ? getFlagText(getCheckedValues(document.getElementsByName('case_flag_rd'))) : "", 
							"Tooth #", $("search_tooth_no") ? $("search_tooth_no").value : "",
							"# Units",  $("search_no_unit") ? $("search_no_unit").value : "",
							"Patient", $("search_patient") ? $("search_patient").value : "",
							"Patient #", $("search_patient_number") ? $("search_patient_number").value : "",
							"Pan #", $("search_subscriber_pan_number") ? $("search_subscriber_pan_number").value : "",
							"Doctor", $("search_doctor") ? $("search_doctor").value : "",
							"Restoration", $("search_restoration") ? $("search_restoration").value : "",
							"Client Group", $("search_client_group") ? $("search_client_group").value : "",
							"Client Office", $("search_client") ? $("search_client").value : "", 
							"Manufacturer", $("search_vendor") ? $("search_vendor").value : "", 
							"Manufacturer's Barcode #", $("vendor_barcode") ? $("vendor_barcode").value : "",
							"Manufacturer Pan #", $("search_pan_number") ? $("search_pan_number").value : "", 
							"Creation Date From", $("creation_from_dt") ? $("creation_from_dt").value : "",
							"Creation Date To", $("creation_to_dt") ? $("creation_to_dt").value : "",
							"Due Date From", $("due_from_dt") ? $("due_from_dt").value : "",
							"Due Date To", $("due_to_dt") ? $("due_to_dt").value : ""]
			}
	
			var i, tmp_arr = []		
					
			for(i=0; i<field_arr.size(); i=i+2){			
				if(field_arr[i+1]) tmp_arr = tmp_arr.concat("(" + field_arr[i] + ") " + field_arr[i+1])				
			}		
			if(tmp_arr.size() != 0) tmp_s = tmp_arr.join(",") + " ";			
		}		
		//Final assignment
		if(tmp_s != "")
			$('searchTermsTitle').innerHTML = "Search Terms: " + tmp_s;
		else
			$('searchTermsTitle').innerHTML = "Search Terms: All Cases";
		
		var search_mode_extra_link;
		if($('case_search_mode').value == 50)
			search_mode_extra_link = "<a href='#' onclick='ShowActiveCaseSearchCases();return false;' class='navigation_control navigation_control_2'>view only active cases for this search</a>";			
		else
			search_mode_extra_link = "<a href='#' onclick='ShowAllCaseSearchCases();return false;' class='navigation_control navigation_control_2'>view all cases for this search</a>";
			
		//For Search Mode
		$('subSearchTypeTitle').innerHTML = (subSearchTypeArr[$('case_search_mode').value] ? "Search Mode: " + subSearchTypeArr[$('case_search_mode').value] : "") +
											", " + search_mode_extra_link
	}	
	
	function getElementByIdIEFix(id){
		return getElementByIdIEFixEX(id, id)
	}
	
	function getElementByIdIEFixEX(name, id){		
		var arr = document.getElementsByName(name)	
		if(arr && arr.length > 0){
			for(var i=0;i<arr.length;i++){			
				if(arr[i].id == id) return arr[i];
			}
		}
	}
	
	function isIE(){
		return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
	}
	
	function getEl(id){
		if(isIE()){
			return getElementByIdIEFix(id)
		}else{
			return $(id)
		}
	}
	
	function getFlagText(val){
		var tmp = [];	
		
		if(val != null && val != ''){
			console.log(val)
			if(val.indexOf('10') >= 0) tmp = tmp.concat('Y');
			if(val.indexOf('20') >= 0) tmp = tmp.concat('G');
			if(val.indexOf('30') >= 0) tmp = tmp.concat('B');
		}
			
		return tmp.join(',');
	}
	
	//Very tricky.... IE can't get the elements by name if the element is created by javascript
	function getElementsByName_iefix(tag, name) {     
		var elem = document.getElementsByTagName(tag);
		var arr = new Array();
		for(i = 0,iarr = 0; i < elem.length; i++) {
			att = elem[i].getAttribute("name");
			if(att == name) {
				arr[iarr] = elem[i];
				iarr++;
			}
		}
		return arr;
	}
	
	//Very tricky.... IE can't get the elements by name if the element is created by javascript
	function getElementsByClassName_iefix(tag, classname) {     
		var elem = document.getElementsByTagName(tag);
		var arr = new Array();
		for(i = 0,iarr = 0; i < elem.length; i++) {
			if (elem[i].className.indexOf(classname) >= 0){	
				arr[iarr] = elem[i];
				iarr++;
			}
		}
		
		return arr;
	}
	
	function cancelBubbleEvent(ev){
		ev = ev || window.event;
		if(ev.preventDefault) {
			if(isIE()) ev.preventDefault(); //it is not working in FF
		} 
		
		if('cancelBubble' in ev) {
			ev.cancelBubble = true;
		}
	}			


// load mask singleton
// 	(if possible, replace it with a better loader later)
var loadMask = new (function(){
	var defaultMsg = "Loading...";
	var mask = new Ext.LoadMask(Ext.getBody(), {msg: defaultMsg});
	
	this.enable = function(){
		mask.enable();
	}
	
	this.disable = function(){
		mask.disable();
	}
	
	this.show = function(msg){
		mask.msg = msg || defaultMsg;
		mask.show();
	}
	
	this.hide = function(){
		mask.hide();
	}
})();


/* Extjs Hacking for FF */
Ext.override(Ext.menu.DateMenu, {  
	render : function() {  
		Ext.menu.DateMenu.superclass.render.call(this);  
		if (Ext.isGecko) {  
			this.picker.el.dom.childNodes[0].style.width = '178px';  
			this.picker.el.dom.style.width = '178px';  
		}  
	}  
});  
