$j.extend(xApp,{
	userPrefDefaults: {
		"showImages": {
			"def": "no",
			"no" : "Display Images",
			"yes": "Hide Images"
		}
	},

	validateIntegerEntry: function(ev){
		log('validate int entry');
		var el=$j(this);
		var val= $j.trim( el.val() );
		var blankOk = ev.data.blankOk;
		var updateTotalCell = ai(ev.data, 'updateTotalCell',false);
		if (!val){ //user entered blank field 
			if (!blankOk){//check if blank is NOT ok
				alert('Invalid Qty value')
				el.val(ev.data.orig); 
			}
			else{
				ev.data.newVal=val;
				ai(ev.data, 'passThruFunction', function(){return true;} )(ev, this);
				return null; 
			}
		}
		if (val.search(/[^0-9]/g) != -1){ 
			el.val(ev.data.orig);  
			alert('Invalid Qty value')
			return null;
		}
		if (updateTotalCell) updateTotalCell(el,val);
		ev.data.newVal=val;
		ai(ev.data, 'passThruFunction', function(){return true;} )(ev, this);
	},

	swapUOM: function(el){
		var swapTo = $j(el).val();
		if ( swapTo == 'consUOM' ){ 
			$j('.baseUOMOnly').hide();
			$j('.consUOMOnly').fadeIn();
		}
		else{ 
			$j('.baseUOMOnly').fadeIn();
			$j('.consUOMOnly').hide();
		}
		$j('.uomSwap').each( function(k,v){
			var value=parseFloat( $j(v).attr('value') );
			if ( swapTo == 'consUOM' ){ 
				//$(v).hide().html( value.toFixed(2) ).fadeIn();
				var changedVal = value.toFixed(2);	
				if (changedVal=='NaN') changedVal=0;
				$j(v).html( changedVal );
			}
			else {
				//convert from consUOM to baseUOM
				var consPerBase=parseInt( $j(v).attr('cons_per_base') );
				var newVal = (value / consPerBase).toFixed(2);	
				if (newVal=='NaN') newVal=0;
				$j(v).html( newVal );
			}	
		});	
	},

	selectAccount :  function(){
		var el=$j(this);
		var custID = $j.trim( el.val() ).toUpperCase();
		log(custID);
		//validate that the val exists in custList
		if (custID.length<3) return null;
		if (custID == xApp.custID ) return null;
		if ( !ai(xApp.custList,custID,false) ) return null;

		//the custID exists, set the global custID
		xApp.custID = custID;

		log('got '+custID);
		//fade out the page body
		//$j('#pageBody.container_16').css('opacity','.30');
		$j('#pageBody.container_16').fadeTo(250,.30);

		var custName = xApp.custList[custID];

		$j('.custMenu').hide();
		$j('#custList').val( custID );
		
		if (custID == xApp.sessionCustID ){
			$j('.pageTitle').hide().html( custName ).fadeIn();
			$j('.custID').hide().html( custID.replace(/\&/,'&amp;') ).fadeIn();
		}
		else{
			$j('.pageTitle').hide().html( custName ).addClass('preSwitch').fadeIn();
			$j('.custID').hide().html( custID.replace(/\&/,'&amp;') ).addClass('preSwitch').fadeIn();
			
			//alert( $j('.custID').hide().html() );
		}
		$j('.custMenu').fadeIn();
		//tie the select element
	},
	revertAccount: function(){
		xApp.custID = xApp.sessionCustID;
		$j('.cancelCustSelectBtn').hide();
		$j('.custSelectBar').hide();
		if (xApp.sessionCustID){
			var pageTitle=xApp.custList[xApp.custID];
			var custID=xApp.sessionCustID;
		}
		else{
			var pageTitle = xApp.pageVars.pageTitle;
			var custID='';
			$j('.custMenu').hide();
		}

		$j('.pageTitle').hide().html( pageTitle  ).removeClass('preSwitch').fadeIn();
		$j('.custID').hide().html( custID.replace(/&/,'&amp;') ).removeClass('preSwitch').fadeIn();

		//$j('#pageBody.container_16').css('opacity','1');
		$j('#pageBody.container_16').fadeTo(250,1);
		$j('.revealCustSelectBarBtn').fadeIn();
	},
	jumpTo: function(){
		waitMsg();
		var file=$j(this).attr('target');
		$j('#overrideCustID').val(xApp.custID);
		$j('#jumpToFrm').attr('action', file ).eq(0).submit();
	},

	jumpSearch: function(){
		var srchTxt= $j.trim( $j('#prodSearch').val() );
		if (!srchTxt) return null;
		waitMsg();
		window.location='search_products.php?searchStr=' + escape(srchTxt) + '&overrideCustID='+escape(xApp.custID);
	},

	jumpByVal: function(){
		waitMsg();
		var val=$j.trim( $j('#'+$j(this).attr('name')).val() );
		if (!val) return null;
		window.location =  $j.trim( $j(this).attr('jump_by_val') ) + val;
	},

	enableTabBtn: function(){
		$j('.' + $j(this).attr('tabs') ).hide();
		$j('#' + $j(this).attr('target') ).fadeIn();
	},

	enablePassVar: function(){
		var val=$j(this).attr('value');
		var trigFunc = $j(this).attr('trigger');
		xApp[trigFunc](val);
	},

	gotoStep: function( stepNum, containerID, func ){
		//visual only
		var scope=$j('#'+containerID);
		$j('.stepContainer',scope).hide();
		$j('.step'+stepNum.toString(),scope).fadeIn();
		$j('.stepTab',scope).removeClass('stepOn').eq(stepNum-1).addClass('stepOn');
		if (func) if (typeof xApp[func]=='function') xApp[func]();
	},

	lastTimer: null,
	lastSearchStr: null,
	lastSearchFunc: null,

	listen: function(e){ 
		xApp.lastE = e;
		var str=$j.trim($j(this).val());
		var searchFunc = $j(this).attr('trigger');
		if (xApp.lastSearchFunc==searchFunc && xApp.lastSearchStr == str) return null;

		clearTimeout(xApp.lastTimer); 
		var delay=50;

		if (str.length){
			//log(str); 
			xApp.lastTimer = setTimeout(
				//searchFunc must be mapped to the desired page specific search function
				function(){ xApp[searchFunc](str) },
				delay
			); 
			xApp.lastSearchFunc = searchFunc;
			xApp.lastSearchStr = str;
		}
	}, 

	//common user management methods:
	listAccountsByPrefix: function(){
		var el=$j(this);	
		var custPrefix = $j.trim( el.val() ).toUpperCase();
		//validate that the val exists in custList
		if (custPrefix.length<3) return null;
		var items={};
		if (custPrefix=='ALL') items=xApp.custList;
		$j.each(xApp.custList, function(k,v){
			if ( k.substr(0, custPrefix.length )==custPrefix ) items[k]=v;
		});
		var pickList=xApp.buildPickList('custPickList',items, xApp.pageVars.selectedAccounts);
	},


	updateCountOfAccounts: function(){
		$j('.countOfSelAccounts').html(getProps(xApp.pageVars.selectedAccounts).length);
	},

	edit: function(scope){
		$j('.'+scope+'.statusMsg').html('');
		$j('.'+scope+' .formSet p span').hide().each(function(k,el){
			$j('.'+scope+' input[forff=' + $j(el).attr('forff') + ']').val( $j(el).text() );
			$j('.'+scope+' textarea[forff=' + $j(el).attr('forff') + ']').val( $j(el).html() );
			$j('.'+scope+' select[forff=' + $j(el).attr('forff') + ']').val( $j(el).text() );
		});
		$j('.'+scope+' .formSet p input,.'+scope+' .formSet p textarea,  .'+scope+' .formSet p select,.'+scope+' .formSet p span.noEdit').fadeIn();
		setTimeout( function(){$j('.'+scope+' .save, .'+scope+' .cancel').fadeIn();}, 300);
		$j('.'+scope+' .edit').hide();
	},
	cancel: function(scope){
		$j('.'+scope+' .formSet p input, .'+scope+' .formSet p select').hide();
		$j('.'+scope+' .formSet p textarea').hide();
		$j('.'+scope+' .formSet p span').fadeIn();
		setTimeout( function(){ $j('.'+scope+' .edit').fadeIn();}, 300);
		$j('.'+scope+' .save, .'+scope+' .cancel').hide();
	},
	save: function(scope, restFile){
		$j('.'+scope+' .formSet').hide();	
		$j('.'+scope+'.statusMsg').hide().html('Please wait...applying your action').show();	
		var params={};
		$j('.'+scope+' .formSet :input').each(function(k,f){
			var name=$j(f).attr('forff');
			params[name]=$j.trim( $j(f).val() );
		})


		$j.ajax({ 
			type:'POST', url:'REST/' + restFile, 
			dataType: 'json', data:{ json: $j.toJSON( params ), nonce: (new Date()).getTime() },
			success: function(json){
				if(json.status){ 
					$j('.'+scope+'.statusMsg').hide().html('Done.').show();	
					$j('.'+scope+'.statusMsg').html(json.msg).fadeIn();
					$j.each(params, function(name, val){
						$j('.'+scope+' .formSet p span[forff=' + name  + ']').text( val );
					});
					xApp.cancel(scope);
				}
				else{ 
					$j('.'+scope+'.statusMsg').html(json.msg);
				}
				$j('.'+scope+' .formSet').fadeIn();	
			}
		});
		return params;
	},
	
	load: function(scope,data){
		$j.each(data, function(k,v){
			$j('.'+scope+' .formSet p span[forff=' + k + ']').text(v);
			//alert(k+' ' +  $j('.'+scope+' .formSet p span[forff=' + k + ']').length );
		});
		$j('.'+scope+'.statusMsg').hide().html('').fadeIn();
		xApp.cancel(scope);
	},



	loadPanel: function(panelName, params){
		var container=$j('#'+panelName);	
		if (params!=undefined) var url='REST/p_' + panelName +  '.php?' + $j.param(params);
		else var url='REST/p_' + panelName +  '.php';

		container.html('Fetching information...').fadeIn();
		$j.ajax({
			type:'GET',
			url:url,
			dataType: 'HTML',
			data: {'nonce': (new Date()).getTime()},
			success: function(html){
				container.hide().html(html).fadeIn();
			},
			error: function(xhr){

			}

		});
		return null;
	},

	refreshPanel: function(){
		xApp.loadPanel( $j(this).attr('for_panel') );
	},

	setupUserPrefBtns: function(){
		$j('.userPrefBtn').each( function(k,v){
			var btn = $j(v);
			var prefName = btn.attr('pref_name');
			var prefRef = xApp.userPrefDefaults[prefName];
			var prefVal = ai( xApp.pageVars.userPref, prefName,  prefRef.def);
log(prefVal);	
			if (prefVal=='no') var newVal='yes';
			else var newVal='no';

			btn.attr('pref_value',newVal).bind('click',xApp.setUserPref)
				.hide().text(prefRef[prefVal]).addClass('btn').addClass('um').fadeIn();
		});
	},

	setUserPref: function(){
		var _this=$j(this).hide();
		var params ={ 
			"prefName": _this.attr('pref_name'), 
			"prefVal": _this.attr('pref_value'),
			"targetID": xApp.actioner 
		}

		var onChange= _this.attr('on_change');
		$j.ajax({ 
			type:'POST', url:'REST/a_setUserPref.php', dataType: 'json', 
			data:{ json: $j.toJSON( params ), nonce: (new Date()).getTime() },
			success: function(json){
				if(json.status){ 
					if (params.prefVal=='yes') var newVal='no';	
					else var newVal='yes';	
					xApp.pageVars.userPref[ params.prefName ] = params.prefVal;
					$j(_this).hide().attr('pref_value', newVal).text( xApp.userPrefDefaults[params.prefName][ params.prefVal ] ).fadeIn();
					if (onChange) xApp[onChange]( params.prefVal );	
				}
				else{ 
					
				}
			}
		});
	},

	openChatWindow: function(){
		if ( !xApp.pageVars.chatHash ) return true;
		var baseURL = 'http://tmchat.twinmed-dev.com';	
		//var baseURL = 'http://chatdev.twinmed-dev.com';	
		//var baseURL = 'http://rienux';
		var url =  baseURL + '/customer.html?hash=' + xApp.pageVars.chatHash;
		log(url);
		window.open( url, 'TwinmedChat');
	},


	displayOrderHelpForm: function(){
		
	},

	v2Landing: function(){
		$j('#custID').unbind('keyup').bind('keyup', xApp.selectAccount);
		$j('#custList').unbind('change').bind('change', function(){
			$j('#custID').val( $j(this).val() ).trigger('keyup');
		});

		$j('.revertBtn').unbind('click').bind('click',xApp.revertAccount);
		$j('.revealCustSelectBarBtn').unbind('click').bind('click',function(){
			$j(this).hide();
			$j('#custID').trigger('keyup');
			$j('.custSelectBar').fadeIn();
			$j('.cancelCustSelectBtn').fadeIn();
		});

		var custName='';

		//case: cust selected, Acct page
		if (xApp.sessionCustID && !ai(xApp.pageVars,'notAcctSpecific',false)){ 
			var custName=xApp.custList[xApp.sessionCustID];
			$j('.custID, .sessionCustID').html( xApp.sessionCustID.replace(/&/,'&amp;') ).show();
			$j('.sessionCust').show();
			$j('.custName').html(  custName );
			$j('.revealCustSelectBarBtn').html('Select a Different Account');

			$j('.notAcctPage').hide();
			$j('.acctPage').show();
			$j('.custMenu').show();

			var pageTitle = custName;
		}

		//case: cust selected, NON Acct page
		if (xApp.sessionCustID && ai(xApp.pageVars,'notAcctSpecific',false)){ 
			var custName=xApp.custList[xApp.sessionCustID];
			$j('.custID, .sessionCustID').html( xApp.sessionCustID.replace(/&/,'&amp') ).show();
			$j('.custName').html(  custName );
			$j('.sessionCust').show();
			$j('.revealCustSelectBarBtn').hide();

			$j('.notAcctPage, #displayAcctBarBtn').show();
			$j('.acctPage').hide();
			var pageTitle = ai(xApp.pageVars,'title','Unittled - Non-Account Specific Page');
		}

		//case: no cust selected -> MUST BE NON Acct Page
		if (!xApp.sessionCustID){
			$j('.notAcctPage').show();
			$j('.acctPage').hide();
			$j('.sessionCust').hide();

			var pageTitle = ai(xApp.pageVars,'title','Unittled - Non-Account Specific Page');
			$j('.revealCustSelectBarBtn').html('Select an Account');
		}

		$j('#displayAcctBarBtn').bind('click', function(){
			$j('.custMenu').fadeIn();
			$j(this).hide().html('[Select a Different Acct]').unbind('click').bind('click', function(){
				$j('.custSelectBar').fadeIn();
			}).fadeIn();
		});


		xApp.pageVars.pageTitle=pageTitle;
		$j('.pageTitle, .landingTitle').html( pageTitle );
			

		$j('.jumpBtn').unbind('click').bind('click', xApp.jumpTo);
		$j('#jumpSearch').bind('click',xApp.jumpSearch);
		$j('#prodSearch').bind('focus', function(){
			$j(this).keypress( function(e){ if (e.which==13) $j('#jumpSearch').trigger('click'); });  
		}).bind('blur', function(){ $j(this).unbind('keypress'); });


		$j('[jump_by_val]').bind('click', xApp.jumpByVal);
		$j('.tabBtn').bind('click',xApp.enableTabBtn);
		$j('.passVar').bind('click',xApp.enablePassVar);


		$j('#wrap, #footer').fadeIn();
		$j('[swap_txt]').live('click',swapDisplay);

		try { xApp.listenOnFocus(); }
		catch(e){ log("Could not listen"); }
		$j('#loginBtn').bind("click", function(){ $j('#frmLogin').get(0).submit(); });
		$j('#loginBtn_route').bind("click", xApp.route_login);


		setTimeout( function(){
			if (!xApp.pageVars.actioner) return true;
			if (xApp.pageVars.custDetails) var custID=xApp.pageVars.custDetails.custID;
			else{ 
				for(var i in xApp.custList){
					var custID=i.substr(0,3);
					break;
				}
			}
			var src="http://image.providesupport.com/js/tmedonline/safe-standard.js?ps_t="+(new Date()).getTime()+"&FACILITY_ID="+custID+"&USER_ID="+xApp.pageVars.actioner.id+"&USER_NAME="+xApp.pageVars.actioner.id;
			
			document.getElementById("ps_tmedonline_scr").src=src;
		},3000);
		xApp.prepInquiryForm();
	},

	toggleOrderHelpFrm: function(){
		$j('#orderHelpFrm').toggle();

	},

	route_login: function(){
		var params={
			userID: $j.trim($j("input#userID").val()),
			pw: $j.trim($j("input#password").val())
		}
		$j.ajax({
			type: 'POST', url: 'REST/a_route_login.php',
			dataType: 'json',
			data: {'json':$j.toJSON(params)},
			success: function(json){
				if (json.status){
					$j('.helpFormStatusMsg').fadeIn();
					window.location = json.data.redirect_to;
				}else{
					log("failed");	
				}
				$j('#submitStatus').hide();
			},
			error: function(xhr){
				//alert("System Error");
			}
		});			

	},


	saveJSON: function(btn){
		$j(btn).hide();
		$j('.inquiryErrMsg').html("").hide();
		$j('#submitStatus').fadeIn();
		var ff={};
		var fail=false;
		$j('label[ff_label]').removeClass('red');
		$j('.ff').each( function(k,v){ 
			var val = $j.trim( $j(v).val() );
			if ( !val ){
				$j('label[ff_label='+ $j(v).attr("id") + ']').addClass('red');
				log("missing " + $j(v).attr("id"));
				fail=true;
			}
			ff[ $j(v).attr('id') ] = val;
		});

		if (fail){
			$j('.inquiryErrMsg').html("Please fill out all required fields").fadeIn();
			$j(btn).fadeIn();
			$j('#submitStatus').hide();
			return true;
		}
		var subject = ff.u_subject;
		delete ff.u_subject;

		$j.ajax({
			type: 'POST', url: 'REST/a_saveJSON.php',
			dataType: 'json',
			data: {'json':$j.toJSON(ff),kind:subject},
			success: function(json){
				if (json.status){
					$j('.helpFormStatusMsg').fadeIn();
				}else{
					alert("SQL Failed");
				}
				$j('#submitStatus').hide();
			},
			error: function(xhr){alert("System Error");}
		});			
	},
	prepInquiryForm: function(){
		$j("#u_subject").unbind("change").bind("change",function(){
			var re_code = $j(this).val();
			$j(".re_note").hide();
			$j(".re_note.re_code_"+re_code).show();
		}).trigger("change");
	}

});





$j(document).ready(function(){
	removeDummyVars(xApp.pageVars);	
	if (xApp.pageVars.actioner)
		if ("6"==xApp.pageVars.actioner.type){
			$j("select#custList").load("all_acct_list.html");
			return $j.getScript("js/all_acct_list.js", xApp.v2Landing );
		}
	xApp.v2Landing();
	//turnon listeners
});

