/*global $: true, _: true, BL: true, CV: true, escape: true, window: true */
/*global $: true, _: true, BL: true, CV: true, escape: true, window: true */
/**
 * bl.js
 *
 * The main JavaScript file for Business List
 * @author Stephen White <aaron@cisdirect.com>
 * @author Aaron King <aaron@cisdirect.com>
 * Aaron wrote the CL frontend and stripped that jquery bl & index and added BL verbaige
 * Stephen wrote the php backend and completed hooking up the conversion to BL- about half 
 * of this code was written by Aaron & the other half by Stephen and all modified by Stephen
 * @version 1.0
 * @package Consumer List
 * @copyright 2009
 
 */
(window.BL = function() {
	var buttons		= {
			
		    //button ID's have _button added to the ie; count_button, cutoff_button, order_button
		    count:			function() {
			   
			   var tmpsel=-1;
			   if (document.getElementById('orders_open_select')){
			      var tmpsel=document.forms['orderManage'].orders_open_select.selectedIndex;
		       }
		       
			   if (tmpsel > -1){
		       		var tmpselected=eval("document.forms['orderManage'].orders_open_select.options["+tmpsel+"].value");
	       	
			   		var trec=tmpselected.split("`");
			   		var theseljob=trec[0];
			   		if (CV.theheader != theseljob){
			   			 blAlert({ title: 'Count Validation', text: 'The selected job is not the active job. The \'Clear\' button will unselect so you can continue to work with the previously selected job or you can click one of the other buttons to perform an action with the selected count. The \'Edit\' button will make the selected count active.' });
				         return null;
		   		    } else {
			   		     getCount();
		   		    }    	
		   		    
		       } else {
			       
			       getCount();
			       
		       }    
			   
			},

			start_over:			function() {
				  		        
		        var theserveradd=document.getElementById('remhost').value;
		        if (theserveradd=='localhost' || theserveradd=='12.46.52.206' || theserveradd=='12.46.52.149'){
			        theserveradd=theserveradd+'/bl';
		        }    
		        
		        if (document.getElementById('isSSL').value=='T'){
			        theserveradd="https://"+theserveradd;
		        } else {
			        theserveradd="http://"+theserveradd;    
		        }  
		        
		        //alert(document.getElementById('isSSL').value);
		                 
		        if( CV.custid=='CI0111'){
   		           showvars();
   		              
		        }  else {
			        
                   window.location =theserveradd+"/index.php?cID="+CV.custid;
		        }     
		        
		        //showvars();
		        		
				//nothing yet;
		    },
				
			segment_delete:	function() {
				
			  strChk = jQuery.trim(CV.theheader);
		      if (strChk.length==0){
			  	 blAlert({ title: 'Error deleting segment: ', text: 'You cannot delete the only segment.' });
			     return null;	
			  }
			  
			  
				 blConfirm({
  				 title:	'Delete Segment', 
				 text:	'Deleting a segment cannot be undone. Click "OK" to permanently delete segment "' + CV.description + '"',
				 callback:	function() {
				   manageSegments('D','');
				 }
				});
			},
					
			segment_new:	function() {
				
			  strChk = jQuery.trim(CV.theheader);
		      if (strChk.length==0){
			  	 blAlert({ title: 'Error adding segment: ', text: 'You cannot add an additional segment to an empty count. Please run a count for the first segment.' });
			     return null;	
			  }
				
				
			   // Set the cutoff(s)
			   $('#segment_name_input').val(' ');
			   
			   $('#segment_dialog').dialog({
					buttons: { 
						"OK": function() { manageSegments('N',$('#segment_name_input').val()); }
					},
					title: 'New Segment Name'
			   })
				

               $('#segment_dialog').dialog({ autoOpen: false })
               $('#segment_dialog').dialog('open')	
				
			
			},
			
			segment_rename:	function() {
				
			   // Set the cutoff(s)
			   $('#segment_name_input').val(CV.description);
			   
			   $('#segment_dialog').dialog({
					buttons: { 
						"OK": function() { manageSegments('R',$('#segment_name_input').val()); }
					},
					title: 'Segment Description'
			   })
				
				
				
               $('#segment_dialog').dialog({ autoOpen: false })
               $('#segment_dialog').dialog('open')	
				
			
			},

			
			cutoff:			function() {
				
			   // Set the cutoff(s)
			   $('#job_cutoff_input').val((CV.job_cutoff) ? CV.job_cutoff : '');
			   
			   $('#cutoff_dialog').dialog({
					buttons: { 
						"OK": function() { savecutoff(); }
					},
					title: 'Limit count to a specified number of records.'
				})
				
				
				
               $('#cutoff_dialog').dialog({ autoOpen: false })
               $('#cutoff_dialog').dialog('open')
			   
			   		
			},	
			
			order:			function() {
			
			   var mcid=CV.custid; 
			   if (mcid=='CI0118'){
			       blAlert({ title: 'Login Check: ', text: 'Please contact us at 1-800-632-1379 to place an order.' });
			       return null;	    
	    	   }  
	    	   
				var checkcnt=CV.numrecords;
				if (checkcnt > 100000){
				   blAlert({ title: 'Order Validation', text: 'There is a 100,000 record limit on the website. To place this order please call 1-800-632-1379.' });
				   return null;
			    } else if(checkcnt =='0'){
				   blAlert({ title: 'Order Validation', text: 'There are no records to order, review your selections and click the \'Update\' button to refresh your count.' });
				   return null;
			    } else if(CV.hasbeenupdated =='N'){
				   blAlert({ title: 'Order Validation', text: 'This count needs to be updated, please click the \'Update\' button to refresh your count.' });
				   return null;
			    }  
			    
			     openOrderInfo();
				 //openSubmitWindow();
			},
			
			open_orders_edit:			function() {
			   manageOrders('E','','open','open');
			},
		    
			open_orders_rename:			function() {
				
			   var tmpsel=document.forms['orderManage'].orders_open_select.selectedIndex;
		       if (tmpsel==-1){
			  	 blAlert({ title: 'Error changing order description: ', text: 'Please select the order you want to rename.' });
			     return null;	
			   }
		       var tmpselected=document.forms['orderManage'].orders_open_select.options[tmpsel].value;
		       
		       
			   var trec=tmpselected.split("`");
			   var torename=trec[3];
			   
				  // Set the cutoff(s)
			   $('#count_description_input_2').val(torename);
			   
			   $('#rename_dialog').dialog({
					buttons: { 
						"OK": function() { manageOrders('R',$('#count_description_input_2').val(),'open','open'); }
					},
					title: 'Rename Order'
			   })
				

               $('#rename_dialog').dialog({ autoOpen: false })
               $('#rename_dialog').dialog('open')	
		
		    },			
			
		    save:			function() {
			    
			   var mcid=CV.custid; 
			   if (mcid=='' || mcid=='CI0115'){
			       blAlert({ title: 'Login Check: ', text: 'You must login before you can save an order, please click on the \'Log In\' menu item at top right part of this screen.' });
			       return null;	    
	    	   }  
			    
			    
			    
			   var checkcnt=$('#count_records').html();
			  
			   //removeed per Mary   
			   //if (document.getElementById('count_records').style.color!="#000000" && checkcnt > 0){ 
				  // blAlert({ title: 'Order Validation', text: 'Please update your count before saving. Click the \"Update\" button to perform this action.' });
				  // return null;
			   //}  
			   
			   // Set the cutoff(s)
			   $('#count_description_save').val(CV['head_descr']);
			   $('#po_save').val(CV['head_po']);
			   
			   
			   
			   
			   $('#savePO_dialog').dialog({
					buttons: { 
						"OK": function() { saveCount($('#count_description_save').val(),$('#po_save').val()); }
					},
					title: 'Save Count'
			   })
				
				
				
               $('#savePO_dialog').dialog({ autoOpen: false })
               $('#savePO_dialog').dialog('open')	
		
		    },			
		    
		    
		    open_orders_clone:			function() {
			   manageOrders('C','','open','open');
			},
		    
		    open_orders_new:			function() {
			    
			   $('#count_description_input_new').val(' ');
			   
			   $('#addnew_dialog').dialog({
					buttons: { 
						"OK": function() { manageOrders('A',$('#count_description_input_new').val(),'open',$('#po_new_input').val() ); }
					},
					title: 'Adding a new order.'
			   })
				
				
				
               $('#addnew_dialog').dialog({ autoOpen: false })
               $('#addnew_dialog').dialog('open')	
			    
			    
			},
		    
			open_orders_clone:			function() {
			    
			   $('#count_description_input_2').val(' ');
			   
			   $('#rename_dialog').dialog({
					buttons: { 
						"OK": function() { manageOrders('C',$('#count_description_input_2').val(),'open','open'); }
					},
					title: 'Cloning an existing order.'
			   })
				
				
				
               $('#rename_dialog').dialog({ autoOpen: false })
               $('#rename_dialog').dialog('open')	
			    
			    
			},
			
			submitted_orders_clone:			function() {
			    
			   $('#count_description_input_3').val(' ');
			   
			   $('#submit_clone_dialog').dialog({
					buttons: { 
						"OK": function() { manageOrders('C',$('#count_description_input_3').val(),'submitted','open'); }
					},
					title: 'Cloning an previous order.'
			   })
				
				
				
               $('#submit_clone_dialog').dialog({ autoOpen: false })
               $('#submit_clone_dialog').dialog('open')	
			    
			    
			},
			
			
		    open_orders_delete:			function() {
			    
			   var tmpsel=document.forms['orderManage'].orders_open_select.selectedIndex;
		       var tmpselected=document.forms['orderManage'].orders_open_select.options[tmpsel].value;
	       	
			   var trec=tmpselected.split("`");
			   var todelete=trec[0];
			    
		
			    blConfirm({
  				 title:	'Delete Count', 
				 text:	'Deleting this job cannot be reversed. Click "OK" to delete order ' + todelete + '.',
				 callback:	function() {
				    manageOrders('D','','open','open');
				 }
				}); 
			    			  
			},
		    
		    address_radius:				function() {
			   getRadius();
			   sidebarSet();
			},
		    
			zip_radius_clear:			function() {
			   clearRadiusInputs();
			},
			
			address_radius_clear:		function() {
			  clearRadiusInputs();
			},
			
			sic_search:					function() {
				
				var thesearch=$('#sic_search_input').val();
				var thetable=$('input:radio[name=rsic]:checked').val();
				getSicSearch('S',thesearch,thetable);
			},
			
			//this was a test one direct out through httpobject
			//sic_search2:				function() {
				//var thesearch=$('#sic_search_input').val();
				//var thetable=$('input:radio[name=rsic]:checked').val();
				//getsic(thesearch,thetable);	
		    //},
		    
			submitted_orders_search:	function() {
				
				searchOrders('S',0);	
				
			},
						
			open_orders_search:			function() {
				
				searchOrders('O',0);	
				
			},
			
			submitted_orders_search_next:	function() {
				
				var startpos=document.forms['orderManage'].orders_submitted_select.selectedIndex;
				
				
				if (startpos > -1) {
			      startpos=(startpos+1);
			    } else {
				  alert('There is no active search to continue.');
				  return null;    
			    }    	
			    	 
				searchOrders('S',startpos);	
				
			},
						
			open_orders_search_next:	function() {
				
				var startpos=document.forms['orderManage'].orders_open_select.selectedIndex;
				if (startpos > -1) {
			      startpos=(startpos+1);
			    } else {
				  alert('There is no active search to continue.');
				  return null;    
			    }  	
				searchOrders('O',startpos);	
				
			},
			
			open_orders_search_reset:	function() {
				$('#open_order_search_query').val('');
				document.forms['orderManage'].orders_open_select.selectedIndex=-1;
			},
			
			submitted_orders_search_reset:	function() {
				document.forms['orderManage'].orders_submitted_select.selectedIndex=-1;
				$('#submitted_order_search_query').val('');
			},
			
		    manual_zip_clear:			function() {
			   $('#zip_textarea').val('');
			},
			
			
			report_email:	function() {
				
				CV['report'] = 'Y';	
				CV['email'] =$('#report_email_input').val();
				
				var err="";
				
				var numberOfReports=0;
				
				if(document.getElementById('rptzip').checked==true){ numberOfReports=1};
				if(document.getElementById('rptcr').checked==true){ numberOfReports=1};
				if(document.getElementById('rptcity').checked==true){ numberOfReports=1};
				if(document.getElementById('rptcnty').checked==true){ numberOfReports=1};
				if(document.getElementById('rptstate').checked==true){ numberOfReports=1};
				if(document.getElementById('rptac').checked==true){ numberOfReports=1};
				if(document.getElementById('rptsic2').checked==true){ numberOfReports=1};
				if(document.getElementById('rptsic4').checked==true){ numberOfReports=1};
				if(document.getElementById('rptsic6').checked==true){ numberOfReports=1};
				if(document.getElementById('rptempl').checked==true){ numberOfReports=1};
				if(document.getElementById('rptsls').checked==true){ numberOfReports=1};
				if(document.getElementById('all_reports_input').checked==true){ numberOfReports=1};
				
				var checkcnt=CV.numrecords;
				if (checkcnt > 400000){
				   err=err+"<br>You cannot send a report when your count is above 400,000.<br>";
				} 
				
				
				if ( numberOfReports==0 ){
					err=err+"<br>Please choose a report to send.";
			    }	
			    
			    if ( $('#report_email_input').val()=="" ){
					err=err+"<br>Please enter an email address.";
			    }
			   
			    if ( err !="" ){
					blAlert({ title: 'Report Error', text: 'Please correct these errors:<br>'+err });
					return null;
			    }
				
				getCount({
					report:	'Y' 
				}, function() {
					blAlert({ title: 'Report Sent', text: 'Report was sent to ' + $('#report_email_input').val() });
				});
			}
		},
		crossImg	= '<img src="img/cross_8.png" alt="Remove" height="8" width="8" class="cross" />',
		geog		= {
			acode:	'Area Code',  //this is the select 'select a city' box under States geo tab
			city:	'City',  //this is the select 'select a city' box under the area code & zip code tabs when you chose a state
			county:	'County', //cannot find this yet 6/1
			crid:	'Carrier Route', //cannot find this yet 6/1
			metro:	'Metro Area', //cannot find this yet 6/1
			zip:	'ZIP Code',   //cannot find this yet 6/1
			states:	'States'
		},
		tabs		= $('#tabs');
		
	// Debug log function - *** remove before production ***
	function log(s) {
		try { console.log(s); } catch (e) { return; }
	}
	
	
	function IsNumeric(input) { 
       return (input - 0) == input && input.length > 0; 
    } 

 
    function saveCount(newname,newpo){
	    $('#savePO_dialog').dialog('close')	;
	     
	    CV['head_descr']=newname;
	    CV['head_po']=newpo;
	    CV['saveonly']='N';
	    
	   	//for jobsubmit
		$('#order_description_input').val(newname);
		$('#order_po_input').val(newpo);
			
	    
	    getCount();
	    
	       
    }    
        
	// Object containing all the variables used to get a count
	function CountVars(o) {
		var defaults = {
			
			thejob:					' ', //***
			theheader:				' ', //***
			reports:				[],
			zip:					[],
			city:					[],
			state:					[],
			crid:					[],
			county:					[],
			sic:					[],
			metro:					[],
			email:					' ',
			radius:					' ',
			radiusCentroid:			' ',
			acode:					[],
			exclude_zip:			[],
			exclude_sic:			[],		
			// Additional criteria
			job_cutoff:				'0',	// number of records to limit to - 0 for all
			start_date:				' ',		// four digit year for first year in business
			employee_low:			'0',	// default 0 
			employee_high:			'0',	// default 0 
			employee_range:			'Z',		// (A-K)
			sales_low:				'0',	// default 0
			sales_high:				'0',	// default 0
			sales_range:			'Z',		// (A-K)
			zip4_only:				'T',	// Include only records with zip4  default "T" T/F
			executive:				'F',	// Include only records with executive contacts contact only default value "F" T/F
			contact_only:			'F',	// Include a record for each contact per company default value "F" T/F
			location_type:			' ',		// Corporate Headquarters/branch/subsidiary ***default space- very important to not have either don't use boolean
			gender:					' ',		// gender of contact M/F ***default space- very important to not have either don't use boolean
			pub_priv:				' ',		// 1 or 0 ***default space- very important to not have either don't use boolean
			jobtitle:				[],		// comma separated named list of value codes
			onetimeuse:				'T',	// default value "T" T/F;
			thepkg:					'B',	// field package default "B" B/F
			// Checkbox field list T/F
		
			recTELEPHONE:			' ',
			recCEO_1ST_NM:			' ',
			recCEO_LST_NM:			' ',
			recDDM_TITLE:			' ',
			recSALES_VOL:			' ',
			recSALES_VOL_CD:		' ',
			recEMPL_TOTAL:			' ',
			recEMPL_TOT_CD:			' ',
			recFRAN_CODE:			' ',
			recCONTACT:				' ',
			recPUB_PRIVATE:			' ',
			recYR_STARTED:			' ',
			recSUBSID_IND:			' ',		//branch/hq
			description:			' ',		//***// user filled out order description  --- these are being changed to global on header file
			special_instructions:	' ',		// user filled out instructions - file goes to Sharon and processed manually 
			file_output:			'CSV File Email',		// get from table and use named list default 'CSV File Email'
			po_number:				' ',		// user filed in PO number
			user_submit:			' ',		// name or initials of user submitting order
			payment_type:           ' ',
			//not used yet
			suppress_counts:		[],		// list of suppress counts
			suppress_orders:		[],		// list of suppress orders
			report:					'N',		// report Y/N
			custid:					' ',
			combineseg:             'N',
			//I added these SCW
			qcrtadd:			' ',
            qcrtcity:			' ',
            qcrtzip:			' ',
            qradlimit:			' ',
            numrecords:			' ', 
            orderrecords:		' ',
            orderprice:			' ', //***
            process_price:		' ',
            orderppt:			' ',
            pkg_ppt:			' ',
            amtdue:		   	    ' ',
			orderdate:          ' ',
			zip4_check:         'T',
			//order submit info for header
			head_descr:          ' ',
            head_submit:         ' ',
            head_po:             ' ',
            head_email:          ' ',
            head_pymt_type:      ' ',
            head_combine:        ' ',
            head_notes:          ' ',
            head_ship_type:      ' ',
            head_segments:       ' ',
			thefirstcount:       'Y',
			hasbeenupdated:      'N',
			saveonly:            'N',
			allCntsValid:		 'N' 
		};
		
		return $.extend(true, {}, defaults, o);
	}
	
	// Object containing data used during session
	function BLdata(o) {
		var defaults = {
			cID:				"",	// customer id
			CISsessionID:		"abc",	// future use for CIS session ID
			okamttobill:		"",	// max amt to bill in 24 hours
			okamttrigger:		"",	// max amount in 24 hours
			okvoltrigger:		"",	// max number of records in 24 hours
			oknumorderstrigger:	"",	// max number of orders 24 hours
			pkg1_single:		"",	// basic per thousand package- single use
			pkg1_yr:			"",	// basic per thousand package with one year multi-use
			pkg2_yr:			"",	// full contact package - one year multi-use part of price
			min_order:			"",	// minimume order charge 
			oneuplblprice:		"",	// one up label charge per thousand
			fouruplblprice:		"",	// four up label charge per thousand
			cdprice:			"",	// price of delivering on CD
			diskprice:			"",	// price of buring to disk
			seq10price:			"",	// per segment price up to 10--- not charging 
			seq11price:			"",	// per segment price for 11+---not charging 
			uspdiskprice:		"",	// handling for USP disk price 
			usplblprice:		"",	// handling for USP label
			itememptotprice:	"",	// extra charge /m for adding employee fields to package
			itemsiteprice:		"",	// extra charge /m for adding site type field to package
			itemfranprice:		"",	// extra charge /m for adding fran code field to package
			itemyrprice:		"",	// extra charge /m for adding year started field to package
			itemsalesprice:		"",	// extra charge /m for adding sales volume fields to package
			itemteleprice:		"",	// extra charge /m for adding telephone field to package
			itemcontactprice:	"",	// extra charge /m for adding contact fields to package
			cheshirelblprice:	"",	// cheshire label charge per thousand
			p1Sd1v:				"",	// pkg 1 single run 1st level record count to qualify for discount
			p1Sd1a:				"",	// price per thousand for this discount
			p1Sd2v:				"",	// pkg 1 single run 2nd level record count to qualify for discount
			p1Sd2a:				"",	// price per thousand for this discount
			p1Yd1v:				"",	// pkg 1 one year use 1st level record count to qualify for discount
			p1Yd1a:				"",	// price per thousand for this discount
			p1Yd2v:				"",	// pkg 1 one year use 2nd level record count to qualify for discount
			p1Yd2a:				"",	// price per thousand for this discount
			p2Yd1v:				"",	// pkg 1 single run 1st level record count to qualify for discount
			p2Yd1a:				"",	// price per thousand for this discount
			p2Yd2v:				"",	// pkg 1 single run 2nd level record count to qualify for discount
			p2Yd2a:				""	// price per thousand for this discount
		};
				
		return $.extend(true, {}, defaults, o);
	}
	
	// Replacement for the native JavaScript alert dialog
	// @param o object (title, text, callback)
	function blAlert(o) {
		var options = $.extend({}, { title: 'Warning' }, o); // Set and extend defaults
		return $('<div id="alert_dialog" title="' + options.title + '">' + options.text + '</div>').dialog({
			autoOpen:	true,
			buttons:	{
				"OK": function() {
					if (options.hasOwnProperty('callback') && _(options.callback).isFunction()) {
						options.callback.call();
					}
					$(this).dialog('close');
				}
			},
			close:		function() { $(this).remove(); }
		});
	}
	
	// Replacement for the native JavaScript confirm dialog
	// @param o object (title, text, callback)
	function blConfirm(o) {
		return $('<div id="confirm_dialog" title="' + o.title + '">' + o.text + '</div>').dialog({
			autoOpen:	true,
			buttons:	{
				"Cancel":	function() {
					$(this).dialog('close');
				},
				"OK":		function() {
					if (o.hasOwnProperty('callback') && _(o.callback).isFunction()) {
						o.callback.call();
					}
					$(this).dialog('close');
				}
			},
			close:		function() { $(this).remove(); }
		});
	}
	
	// Add or modify values in the CV object
	// @param	elem	jQuery, object (with key value pairs to overwrite CV) or string
	// @param	val		string or array
	function cvAddVal(elem, val) {
		

		if (elem instanceof jQuery) {
			elem.each(function() {
				var self	= $(this),
					selfVal	= self.val(),
					cvVal	= self.attr('name') || self.metadata().cv,
					eVal	= (selfVal && selfVal !== 'on') ? self.val() : self.metadata().val;
				
				cvAddVal(cvVal, eVal);
			});
		} else if (typeof(elem) === 'object') { // Overwrite specific CV variables with provided key value pairs in elem object
			_(elem).each(function(v, k) {
				cvAddVal(k, v);
			});
		} else if (_.isString(elem) && CV.hasOwnProperty(elem) && typeof(val) !== 'undefined') { // Add specific named CV variable
			if (_.isArray(CV[elem]) && !_(CV[elem]).include(val)) {
				if (_.isArray(val)) {
					CV[elem] = _(CV[elem].concat(val).sort()).uniq(true);
				} else if (_.isString(val)) {
					CV[elem].push(val);	
				}
			} else if (!_.isArray(val)){
				CV[elem] = val;
			}
			
			log('cvAddVal: ' + (CV[elem] === val || _(CV[elem]).include(val)));
		}
	}
	
	// Add value ranges to the CV object - uses cvAddVal and sidebarAdd internally
	// @param elem jQuery
	function cvAddRange(elem) {
		
		var cv			= elem.attr('name') || elem.attr('id').replace('_textarea', ''),
			elemVal		= elem.val(),
			data		= elemVal ? _($.trim(elem.val().toUpperCase()).split(/[\s,]+/).sort()).uniq(true) : false;
		//alert(cv+" line #415");	
		if (!cv || !data) { // Can't do anything if we don't know what variable to add to or don't have any data
		    //alert('Error adding this variable, leaving bl.js line#417');	
			return;
		}
		
		if (cv === 'zip') { // Calculate ranges for ZIP codes only
			data = _(data).chain()
				.each(function(val, i) {
					if (/^\d{5}-\d{5}$/.test(val)) {
						data[i] = [];
						
						for (var j = Number(val.substring(0, 5)), jl = Number(val.substring(6, 11)) + 1; j < jl; j++) {
							if (jQuery.trim(j).length < 5){
							  j="0"+ j;	
						    }   	
							data[i].push(j + '');
						}
					}
				})
				.flatten()
				.value();
		}
		//alert(cv + ' : ' +data+" line #435");
		
		cvAddVal(cv, data);					// Add to appropriate CV variable
		
		
		//sidebarAdd({ cv: cv, data: data });	// Add to sidebar
		sidebarSet();
		
		$(_(data).map(function(val) { return '#' + cv + '-' + val; }).join(', ')).attr('checked', 'checked'); // Check applicable checkboxes
		elem.val('');
		
		log('cvAddRange: ' + function() {
			for (var i = 0, il = data.length; i < il; i++) {
				if (!_(CV[cv]).include(data[i])) {
					return false;
				}
			}
			return true;
		}());
		
		
	}
	
	// Remove or reset values in the CV object
	// @param	elem	jQuery or string
	// @param	val		string
	function cvRemoveVal(elem, val) {
		var	cvDefaults = new CountVars(),
			cv, multi, toRemove;
		
		if (elem instanceof jQuery) {
			cv			= elem.attr('name') || elem.metadata().cv;
			multi		= $();
			toRemove	= [];
			
			elem.each(function() {
				var self	= $(this),
					eVal	= self.is('input') ? self.val() : self.attr('id').replace('selection-', '') || self.metadata().val;
				
				multi = multi.add('.multiSelect:visible input[value="' + eVal + '"]');
				toRemove.push(eVal);
			});
			
			cvRemoveVal(cv, toRemove);
			multi.removeAttr('checked');	// Uncheck corresponding multiSelect checkboxes
		} else if (_.isString(elem) && CV.hasOwnProperty(elem)) { // Reset specific named CV variables or remove values from CV arrays
			if (val && _.isArray(CV[elem])) {
				if (!_.isArray(val)) {
					val = [val];
				}
				_(val).each(function(v) {
					CV[elem] = _(CV[elem]).without(v);
				});
			} else {
				CV[elem] = cvDefaults[elem];
			}
				
			log('cvRemoveVal: ' + elem);
		}
	}
	
	// Sets the form based on the values in the CV object
	function formSet() {
		// Reset the form
		$('#zip_zip_div, #crid_crid_div, #city_city_div, #county_county_div, #metro_metro_div, #acode_acode_div').empty();
		$('#zip_city_select, #acode_city_select').html('<option value="">&nbsp;</option>');
		$('#zip_textarea, #exclude_zip_textarea, #sic_textarea,#exclude_sic_textarea,#crid_textarea, #crid_zip_input, #state_textarea, #acode_textarea, #job_cutoff_input, #cutoff_input, #radius_zip_input, #radius_distance_input, #radius_address_input, #radius_city_input, #report_email_input').val('');
		tabs.find('select').each(function() { // Reset all select elements to their first value
			$(this)[0].selectedIndex = 0;
		});
		document.getElementById('zipForm').reset();
		document.getElementById('cridForm').reset();
		
		//removed both of these forms from index.php scw 06/04/2010
		//document.getElementById('radiusForm').reset();
		//document.getElementById('orderUploadForm').reset();
		
		// Includes
		$('#options_includes_input_1, #options_includes_input_2, #options_includes_input_3').each(function() {
			$(this).attr('checked', CV[$(this).attr('name')] === 'T' ? 'checked' : '');
		});
		
		
		
		
		$('#start_date_input').val(CV.start_date);
		$('#cutoff_input').val(CV.job_cutoff);
		$('#job_cutoff_input').val(CV.job_cutoff);
	}

	
	
	
	// Returns the count for the current order
	function getCount(o, callback) {
		var count = $.extend(true, {}, CV, o);
		
		//grayOut(true);
		document.getElementById('plswait').style.display = 'block';
	

		if (CV.theheader==''){
		  CV.thefirstcount='Y';
	    } else {
		  CV.thefirstcount='N';  
	    }    	
	    
	    
		if (CV['radiusCentroid'][0]==null){
			CV['radiusCentroid'].push=" ";	
	    }	
		
		$.post('include/php/cnt_process.php', count, function(data) {
			
			var thesegmentCNT=addCommas(data.Count);
			var thecountCNT=addCommas(data.totalrecs);
			
			$('#segment_output').html(thesegmentCNT || 'Error'); 
			$('#segment_name').html(data.Descr || 'Temporary Count');
			//$('#count_amt').html('$'+data.totalamt || '0.00');
            $('#count_records').html(thecountCNT || '0');
            //alert(data.totalrecs+'');
            
            var mincharges=0;
            var minord=$('#min_order').val();
            //var emailchrg=$('#emailFTPprice').val();
            //mincharges=(parseFloat(minord)+parseFloat(emailchrg));
            //took out the email charges
            mincharges=parseFloat(minord);
            
            if (data.totalrecs > 0 && data.totalrecs < 9000000){
            	//alert(mincharges);
  				var thenewtotal=data.totalamt;
  				if (thenewtotal < mincharges){
				  thenewtotal= mincharges;
				}	
				
				var thenewtotalDisp=addCommas(thenewtotal);
				 
            	$('#count_amt').html('$'+thenewtotalDisp || '0.00');
            	
        	} else {
	        	$('#count_amt').html(' ');
            }	
            CV['amtdue']=thenewtotal;
              
            var zcid=CV.custid; 
   		    if (zcid=='CI0118'){
               $('#count_amt').html(' ');
            }
            
            
            $('#count_description').html(data.Descr || 'Error');     
            //$('#order_number').html(data.Headerno || 'Error');   
            
            $('#order_job').html(data.Headerno || 'Error');
            $('#order_quantity').html(data.totalrecs || '0');
            			
						
			//alert(data.Headerno+" line #545");
			cvAddVal('thejob', data.Jobno);	
			cvAddVal('theheader', data.Headerno);
			cvAddVal('numrecords',data.Count);
			cvAddVal('orderrecords',data.totalrecs);
			cvAddVal('orderprice', data.orderprice);
            cvAddVal('process_price', data.process_price);
            cvAddVal('orderppt', data.orderppt);
            cvAddVal('pkg_ppt', data.pkg_ppt);
            cvAddVal('amtdue', data.amtdue);
 			CV['report'] = 'N';	 //reset report
			CV['hasbeenupdated']='Y';
			
			greyoutTotals('F')
			if (document.getElementById('count_records')){
			   document.getElementById('count_records').style.font="bold 20px arial,helvetica";
	           document.getElementById('count_records').style.color="#000000";
	           document.getElementById('count_amt').style.font="bold 20px arial,helvetica";
	           document.getElementById('count_amt').style.color="#000000";
		    }
		    
		    if (CV.thefirstcount=='Y'){
		       //load orders segments
			   options = "";
			   options += '<option value="' + data.Jobno + '">'+data.Descr+'</option>'; 
		 	    
			   $("#segment_select").html(options);
			
	        }
		    
	        
	        //load open orders
			
			openord = data.openorders.split("^");
			
			var options = "";
			for (var i = 0; i < openord.length; i++) {
			  //alert(openord[i]);  
			  mrec=	openord[i].split("`");
			  mrec[0]=jQuery.trim(mrec[0]);
			  mrec[1]=jQuery.trim(mrec[1]);
			  mrec[3]=jQuery.trim(mrec[3]);
			  var mnumrecs=jQuery.trim(mrec[4]);
			  var mpo=jQuery.trim(mrec[2]);
			  
			  var xcnt=0;
			  
			  if (jQuery.trim(mpo) !=''){
				xcnt=mpo.length;
              } else {
	            mpo='NONE';
	            mrec[2]='NONE';
	            xcnt=4; 
              }    
			 
              //need to come back to this, could use ASCII maybe but this works fine- padding not working properly
              while (xcnt < 15){
	              mpo= mpo+'&nbsp;';
	              xcnt=xcnt+1;
              }  

              var xcnt=0;
			  
			  if (jQuery.trim(mnumrecs) !=''){
				xcnt=mnumrecs.length;
              } else {
	            mnumrecs='0';
	            mrec[4]='0';
	            xcnt=1; 
              }    
			 
              //need to come back to this, could use ASCII maybe but this works fine- padding not working properly
              while (xcnt < 10){
	              mnumrecs= '&nbsp;'+mnumrecs;
	              xcnt=xcnt+1;
              }  
              
              var mvalue=jQuery.trim(mrec[0])+'`'+jQuery.trim(mrec[1])+'`'+jQuery.trim(mrec[2])+'`'+jQuery.trim(mrec[3]);
			  var newoption=mrec[0]+'&nbsp;&nbsp;&nbsp;'+mrec[1]+'&nbsp;&nbsp;'+mnumrecs+'&nbsp;&nbsp;'+mpo+'&nbsp;&nbsp;&nbsp;'+mrec[3];
			  if (	jQuery.trim(openord[i]) !=''){
				 options += '<option value="' + mvalue + '">'+newoption+'</option>'; 
			  }  
				
			 
			  
			 			      
			}      
			$("#orders_open_select").html(options);
			//alert(data.openorders+" line #1263");
	        
	        
	        //test for existance of the document object---not active in initial state b4 login
			var productElement =  document.getElementById('orderManage');
            if (productElement != null){

				var thecnt=document.forms['orderManage'].orders_open_select.options.length-1;
			           
				//lets mark the select boxes
				for (i=0; i <= thecnt; i++){
            	    var tmpstr=document.forms['orderManage'].orders_open_select.options[i].value;
                
            	    mrec=tmpstr.split("`");
		    	    mrec[0]=jQuery.trim(mrec[0]);               
		    	    data.ordernum=jQuery.trim(data.Headerno);
					if (mrec[0]===data.ordernum){  
					   document.forms['orderManage'].orders_open_select.selectedIndex=i;
   		    	       break;
            	    }   
				
            	}
            } //end of check for object
	        
	        
	        
		    CV['thefirstcount']='N';
		    
            if (CV.thefirstcount=='Z'){
 				var id=CV.custid;
		   	 	var conm=document.getElementById('companylogged').value;
		    	var jbno=data.Jobno;
		    	var header=data.Headerno;
		    	
		    	if (id !='CIS001'){
		    	   var loginhtml = "<span><a href=\"http://www.compactlists.com?business\">Home</a> | <a href=\"http://www.residentlists.com\">Resident Lists</a> | <a href=\"https://www.consumerlists.com\">Consumer Lists</a> | <span class=\"topElement\" id=\"logoutElement\"> Logged in asz <strong>" + data.company + "</strong> | <a class=\"contact_us\" href=\"#\">Contact Us</a> | <a href=\"#\" id=\"logout_link\">Log out</a></span>";
	    		} else {
		    	   var loginhtml = "<span><a href=\"http://www.compactlists.com?business\">Home</a> | <a href=\"http://www.residentlists.com\">Resident Lists</a> | <a href=\"https://www.consumerlists.com\">Consumer Lists</a> | <a href=\"http://12.46.52.149/blphp/indexadmin.php\">Admin</a> | <a class=\"contact_us\" href=\"#\">Contact Us</a> | <a href=\"#\" id=\"logout_link\">Log out</a></span>";
	    	    }	
	    	   	 
	    	    //loginhtml = "<span><a href=\"http://www.compactlists.com?business\">Home</a> | <a href=\"http://www.residentlists.com\">Resident Lists</a> | <a href=\"https://www.consumerlists.com\">Consumer Lists</a> | <a href=\"http://12.46.52.149/blphp/indexadmin.php\">Admin</a> | <a class=\"contact_us\" href=\"#\">Contact Us</a> | <a href=\"#\" id=\"logout_link\">Log outx</a></span>";
	    	  
			   	$('#aNav').html(loginhtml);
			   
			    var theserveradd=document.getElementById('remhost').value;
		        if (theserveradd=='localhost' || theserveradd=='12.46.52.206' || theserveradd=='12.46.52.149'){
			        theserveradd=theserveradd+'/bl';
		        } 
		        
		        if (document.getElementById('isSSL').value==='T'){
			        theserveradd="https://"+theserveradd;
		        } else {
			        theserveradd="http://"+theserveradd;    
		        }          
		       	   			   
			   	window.location =theserveradd+"/index.php?theid="+id+"&conm="+conm+"&jbno="+jbno+"&header="+header;

			} else {
				
				//grayOut(false);
			    document.getElementById('plswait').style.display = 'none';
				
		    } //END OF CHECK FOR NEW COUNT	
 			
		    		    
		    if (CV.saveonly !="N"){
			    blAlert({ title: 'Operation Complete: ', text: 'Count #'+data.Headerno+' has been saved.' });
		    }    
		    
		    CV['saveonly']='N'; 
		    
		    
		    

 			if (callback && _.isFunction(callback)) {
				callback.call();
			}
				
		}, 'json');
	}
	
	
	function sendFeedback() {
			
		$('#feedback_dialog').dialog('close');

		//grayOut(true);
		document.getElementById('plswait').style.display = 'block';
		
		fInfo	= {
		  theconame: $('#feedback-company_name').val(),
   		  thename: $('#feedback-name').val(),
   		  thefeedback: $('#feedback-feedback').val()      	 
		},
	   	
	    
		$.post('include/php/send_feedback.php', fInfo, function(data) {
				
			//grayOut(false);
			document.getElementById('plswait').style.display = 'none';
			
			retMsg = data.retmessage;
		
		    if (retMsg !=''){
			   blAlert({ title: 'Feedback response: ', text: retMsg });
			   return null;
		    }	    	
			
		
				
		}, 'json');
		
			
	}
	
	
	// Returns geography from the specified region and populates the target element
	// @param o object (data, target)
	function getGeography(o) {
		//grayOut(true);
		document.getElementById('plswait').style.display = 'block';
		var lookup		= {
				api:	{
					url:	'include/php/getlookup.php',
					types:	['metro', 'city', 'county']
				},
				geo:	{
					url:	'include/php/getgeo.php',
					types:	['zip', 'crid', 'acode']
				}
			},
			isSelect	= o.target.is('select');
		
		$.post(_(lookup).detect(function(val) { return _(val.types).include(o.data.geo); }).url, o.data, function(data) {
			
			//grayOut(false);
			document.getElementById('plswait').style.display = 'none';
			
			
			var output,
				oheader	= isSelect ? '<option value="">Select a ' + geog[o.data.geo] + '</option>' : '',
				i= 0;
			
			if (_(lookup.geo.types).include(o.data.geo)) { // ZIP, CRID, area code
			    
				if (isSelect) {
					output = _(data).map(function(val) { return '<option value="' + val.Value + '">' + val.Value + '</option>\n'; });
				} else {
					output = _(data).map(function(val) {
						i++;
						return '<label' + ((i % 2 === 1) ? ' class="odd"' : '') + '><input type="checkbox" name="' + o.data.geo + '" value="' + val.theval + '" id="' + o.data.geo + '-' + val.theval + '" class="' + o.data.geo + '_input">' + val.theval + '</label>\n';	
					});
				}
			} else if (_(lookup.api.types).include(o.data.geo)) { // metro, city, county
			    //alert(o.data.geo);
			    
            	if (o.data.geo=='county' || o.data.geo=='metro'){
	            	
					
		    	    if (isSelect) {
					
						output = _(data).map(function(val) { return '<option value="' + val.Value + '">' + val.Description + '</option>\n'; });
									
					} else {
					
						output = _(data).map(function(val) {
							i++;
							return '<label' + ((i % 2 === 1) ? ' class="odd"' : '') + '><input type="checkbox" name="' + o.data.geo + '" value="' + val.Value +'" id="' + o.data.geo + '-' + val.Value + '" class="' + o.data.geo + '_input" label="'+ val.Description +'">' + val.Description + '</label>\n';
						});
					}
					
			    } else if (o.data.geo=='city'){
	            	
		    	    if (isSelect) {
					
						output = _(data).map(function(val) { return '<option value="' + val.Value + '">' + val.Description + '</option>\n'; });
									
					} else {
					
						output = _(data).map(function(val) {
							i++;
							return '<label' + ((i % 2 === 1) ? ' class="odd"' : '') + '><input type="checkbox" name="' + o.data.geo + '" value="' + val.Value +'" id="' + o.data.geo + '-' + val.Value + '" class="' + o.data.geo + '_input" label="'+ val.Description +'">' + val.Description + '</label>\n';
						});
					}
					
			    } else {
			
					if (isSelect) {
					
						output = _(data.GetLookupValuesResult.LookupValueSelection.Selection).map(function(val) { return '<option value="' + val.Value + '">' + val.Description + '</option>\n'; });
									
					} else {
					
						output = _(data.GetLookupValuesResult.LookupValueSelection.Selection).map(function(val) {
							i++;
							return '<label' + ((i % 2 === 1) ? ' class="odd"' : '') + '><input type="checkbox" name="' + o.data.geo + '" value="' + val.Value+'" id="' + o.data.geo + '-' + val.Value + '" class="' + o.data.geo + '_input">' + val.Description + '</label>\n';
						});
					}
					
			    } //end of test for city return	
			}
			
			o.target.html(oheader + output.join('')).scrollTop(0);
		}, 'json');
	}
	
	
	function getSicSearch(whichbutton,msearch,mtable) {
		
		var errMsg="";	
		
		if (whichbutton=='S'){
		 //nothing yet  
	    } else {
		  //nothing yet
	    }
      
		msearch = jQuery.trim(msearch);
		if (msearch==''){
	      	  errMsg=errMsg+"<BR>Type in key terms or 2, 4, 6 digit SICs to search on.";
   		}
             
		// send meassage
		errMsg = jQuery.trim(errMsg);
		
		if (errMsg !=''){
			blAlert({ title: 'Business Type Lookup: ', text: errMsg });
			return null;
		}	    
    	      
		//grayOut(true);
        document.getElementById('plswait').style.display = 'block';      
	    params = {
	   	  thesearch: msearch,
		  thetable: mtable    	 
		},		
		
		lInfo	= {
		  thesearch: msearch,
   		  thetable: mtable      	 
		},
		
	  
		$.post('include/php/getsic.php', lInfo, function(data) { 
			
		returnArray = new Array();
		   
		//grayOut(false);
		document.getElementById('plswait').style.display = 'none';
		
		   if (data[0].typeMatch=="None"){
			   blAlert({ title: 'SIC Code Lookup: ', text: "There were no matches found." });
		       return null;
	       }	 
	        
		        if (data[0].typeMatch=="Exact" || data[0].typeMatch=="Code"){
			      returnArray[1] = "<p><br><B>Exact Matches</B><br><br></p>";  
    			  returnArray[1] = returnArray[1]+"<div id='sicHead'><table>";  
                }
                var theretcount=1;
    			var mnum=0;
 
    			var mexact=0;
    			var mrelated=0;
			    for (x in data) {
      
     				mnum=x;
         			if (data[x].sicCode != undefined){
	         		  //data[x].sicName=data[x].sicName.replace(",",";"); 
	         		  data[x].sicName=data[x].sicName.replace(/,/g,";")
	                  if (jQuery.trim(data[x].typeMatch)=='Exact'){
		                //alert(data[x].sicCode.substring(0,6)+" line #679");   
		                var thenum=mexact+"";  
				        returnArray[1] = returnArray[1]+"<tr width='570px' style='zIndex:13;'>";
				        returnArray[1] = returnArray[1]+"<td><input type=\"checkbox\" value=\""+data[x].sicCode.substring(0,6)+" "+data[x].sicName+" {0_"+data[x].sicCode+"}\" id=\"sic_exact"+data[x].sicCode.substring(0,6)+" "+data[x].sicName+" {0_"+data[x].sicCode+"}\" name=\"sic_exact"+thenum+"\" /> <label>&nbsp;"+data[x].sicCode.substring(0,6)+" "+data[x].sicName+" {0_"+data[x].sicCode+"}</label><td/>";
						returnArray[1] = returnArray[1]+"</tr>";
						theretcount=(theretcount+x);
						mexact=(mexact+1);
  	                  } else if (jQuery.trim(data[x].typeMatch)=='Code'){
		                //alert(data[x].sicCode.substring(0,6)+" line #687");   
		                var thenum=mexact+"";   
				        returnArray[1] = returnArray[1]+"<tr width='570px' style='zIndex:13;'>";
				        returnArray[1] = returnArray[1]+"<td><input type=\"checkbox\" value=\""+data[x].sicName+"\" id=\"sic_exact"+data[x].sicName+"\" name=\"sic_exact"+thenum+"\" /> <label>&nbsp;"+data[x].sicName+"</label><td/>";
						returnArray[1] = returnArray[1]+"</tr>";
						theretcount=(theretcount+x);
						mexact=(mexact+1);
  	                  }
  	                  
  	                  
	            
         			} // end of defined condition
                    if (data[x].typeMatch=="Related"){
	                    break;
                    }    
     			} // end of loop
  
                if (theretcount < 1){
	              returnArray[1] = "<p><br><br>No Exact matches found.<br><br></p>";  
    			  returnArray[1] = returnArray[1]+"<div id='sicHead'><table>";  
                }    
                
     			returnArray[1] = returnArray[1]+"</table>";
                //document.getElementById('siccodereturn').innerHTML= returnArray[1]; 
     			

     			//now related
     			if (data[0].typeMatch=="Exact" || data[0].typeMatch=="Code"){ 
                  returnArray[2] = "<p><br><B>Related Matches</B><br><br></p>";  
    			  returnArray[2] = returnArray[2]+"<table>";  
                }
                var theretcount=0;
    			var mnum2=mnum;
			    for (x in data) {
      
     				mnum2=(mnum2+x);
         			if (data[x] != undefined){
	                  if (jQuery.trim(data[x].typeMatch)=='Related'){ 
		                var thenum=mrelated+"";    
				        returnArray[2] = returnArray[2]+"<tr width='570px' style='zIndex:13;'>";
				        returnArray[2] = returnArray[2]+"<td><input value=\""+data[x].sicCode.substring(0,6)+" "+data[x].sicName+" {0_"+data[x].sicCode+"}\" type=\"checkbox\" id=\"sic_related"+data[x].sicCode.substring(0,6)+" "+data[x].sicName+" {0_"+data[x].sicCode+"}\" name=\"sic_related"+thenum+"\" /> <label>"+data[x].sicCode.substring(0,6)+" "+data[x].sicName+" {0_"+data[x].sicCode+"}</label><td/>";
						returnArray[2] = returnArray[2]+"</tr>";
	  	                theretcount=(theretcount+x);
	  	                mrelated=(mrelated+1);
                      }
         			} // end of defined condition
         
     			} // end of loop
  
                if (theretcount < 1){
	              returnArray[2] = "<p><br><br>No related matches found.<br><br></p>";  
    			  returnArray[2] = returnArray[2]+"<div id='sicHead'><table>";  
                }    
     			returnArray[2] = returnArray[2]+"</table></div>";
     
     			returnArray[1] ="<input type=\"checkbox\" onclick=\"selectallsic('E');\" id=\"selectallexact\" name=\"selectallexact\" /> <label>Select All Exact Matches</label>&nbsp;&nbsp;&nbsp;&nbsp;<input type=\"checkbox\" onclick=\"selectallsic('R');\" id=\"selectallrelated\" name=\"selectallrelated\" /> <label>Select All Related Matches</label><br /> <INPUT TYPE=\"hidden\" name=\"howmanyexact\" id=\"howmanyexact\" value=\""+mexact+"\"><INPUT TYPE=\"hidden\" name=\"howmanyrelated\" id=\"howmanyrelated\" value=\""+mrelated+"\"><p><br></p>"+returnArray[1];
     			document.getElementById('siccodereturn').innerHTML=returnArray[1]+returnArray[2];  
              
     			
     			
  			
                   	      //alert(data[x].sicCode+"   "+data[x].sicName+"   "+data[x].typeMatch+" line #748");			
         
 		     
		    		
		}, 'json');
		
		
		
    }//end of function 
    
    

	function getRadius() {
		
		var errMsg="";	
		var msearch=""; //this is actuall sent, the rest are validation
		var thezip="";
		var theadd="";
		var thedistance="";
		
		
        var thezip=$('#radius_zip_input').val();
		var theadd=$('#radius_address_input').val();
        var thedistance=$('#radius_distance_input').val();
		
 
        //check zip for entry  
		thezip = jQuery.trim(thezip);
		if (thezip==''){
      	  errMsg=errMsg+"<BR><BR>You must enter a zip code to run a radius.";
        }
         
        //check distance for entry  
		thedistance = jQuery.trim(thedistance);
		
		if (thedistance==''){
			errMsg=errMsg+"<BR><BR>You must enter either a distance for the radius.";
        }
        
        if (parseInt(thedistance) > 150){
			errMsg=errMsg+"<BR><BR>150 Miles is the maximum distance.";
        }
        
 		// send meassage
		errMsg = jQuery.trim(errMsg);
		
		if (errMsg !=''){
			blAlert({ title: 'Radius Lookup: ', text: errMsg });
		    return null;
	    }	    
			    	    
	    //create search string
	    msearch=$('#radius_address_input').val()+"^"+$('#radius_zip_input').val()+"^"+$('#radius_distance_input').val(); 
	   	    
		//grayOut(true);
        document.getElementById('plswait').style.display = 'block'; 
        
               
     	//msearch="42806 169th ST SE^98251^2";
        params = {
   		    search: msearch,
		    geo:  "radius"        	 
		},		
	   				
		$.post('include/php/getlookup.php', params, function(data) { // @todo finish this
			
		
		    //data.GetAddressForRadiusResult.ErrorCode":0,"AddressSelection":{"Selection":{"Value":"047676693-122122565-5.0","Description":"5.0 MILE(S) FROM CENTROID OF 98052 IN REDMOND, WA"}}}} 
		    //grayOut(false);
		    document.getElementById('plswait').style.display = 'none';
		    if (data.GetAddressForRadiusResult.ErrorCode !=0){
			    //uncomment for error code in testing but error code in general means no address returned but query was sucessfull
		        //alert("Error getting radius starting point CODE: "+data.GetAddressForRadiusResult.ErrorCode+" line #852");
		        blAlert({ title: 'Radius Lookup: ', text: 'The address you entered has not returned a starting point for your count, please check the address for accuracy. Not 100% of USPS addresses are mapped and you may need to try another address close by.' });
			    return null;	    
            } else {
	        	        
		    	var records = data.GetAddressForRadiusResult.AddressSelection.Selection;
            	
            	
            	var howmany=records.length+" ";
            	if(records){
	            	              
                   if (!records.length){
		        	    // we want to add the radius to the count array and fire off a count update
		    	   		
		    	   		var theradstr=trim(records.Description);
		    	   		theradstr=theradstr.replace(/,/g," ")
		    	   		
		    	   		theradstr=trim(theradstr);
		    	   		theradVal='('+records.Value+')';
		    	   		
		    	   		//CV['radius'].push(theradstr);
	                    CV['radius']=theradstr;
	                    CV['radiusCentroid']=theradVal;
      
	                    CV['qcrtadd']=$('#radius_address_input').val();
				        CV['qcrtcity']=$('#radius_city_input').val(); 
				        CV['qcrtstate']=$('#radius_state_select').val(); 
				        CV['qcrtzip']=$('#radius_zip_input').val(); 
				        CV['qradlimit']=$('#radius_distance_input').val(); 
	                    
	                    
		    	   		//clearRadiusInputs();				            
	        	   } else {     
	        	        var strDesc="";
	        	        var strVal="";
	        	  		// this one is for testing--->loop over and add to a select box and then display that box   
	        	  		//for(var i = 0; i < records.length; i++){
	        	    		 //str += records[i]['Value'] + " --" + records[i]['Description'] + "\n";      
            	  		//}
            	  		
            	  		var options = "";
						for (var i = 0; i < records.length; i++) {
							
						strDesc=records[i]['Description'];
		    	   		strDesc=strDesc.replace(/,/g," ")
		    	   		
		    	   		strVal=records[i]['Value'];
		    	   									
							options += '<option value="' + strVal + '">'+strDesc+'</option>'; 
			 			     
						}      
						$("#radius_option_select").html(options);
						
              
               			   
			   $('#radiusOptions_dialog').dialog({
					buttons: { 
						"Cancel": function() { cancelRadOpt(); },
						"Select": function() { setRadiusSelect();}
					},
					
					title: 'Multiple Starting Points',
					//position: ['center'], 
					autoOpen: false, 
					height: 400, 
					width: 450, 
					modal: true 
			   })
				
				
			   
			   
			   
			   
				
               $('#radiusOptions_dialog').dialog({ autoOpen: false })
               $('#radiusOptions_dialog').dialog('open')	
		
            	  		
            	  		
            	  		
            	  		//testing---->alert(str+howmany+" line #917");
            	  		
                   } //end of test for more than one centroid ID 
                   
                   //this has got to be here- frustrating to get in place.              
                   sidebarSet();
                } else {  // end of test for record return
                   //leave this as an alert for total failure 
                   alert("Error getting radius information, please contact customer support if this problem persist at 1-800-632-1379");
                }

	        }
	        
	      
		    		
		}, 'json');
		
		
		
	}
	
	function cancelRadOpt(){
		//need to empty box
		$("#radius_option_select").html("<option value=\" \"> </option>");
		$('#radiusOptions_dialog').dialog('close');
    }	
	    
    
    function closefeedback(){
	    $('#feedback_dialog').dialog('close');
    }   
    
    
    function setRadiusSelect(){
		//need to empty box
		//clearRadiusInputs();
		CV['radius'].push=" ";
		CV['radiusCentroid'].push=" ";
		
		var thesel=document.forms['radiusoptionsForm'].radius_option_select.selectedIndex;
		var theDesc=document.forms['radiusoptionsForm'].radius_option_select.options[thesel].text;
		
		//alert(theDesc);
		var theID = "^("+$("#radius_option_select").val()+")";	

		CV['radius']=theDesc;
	    CV['radiusCentroid']=theID;
	    
	    
	    
		CV['qcrtadd']=$('#radius_address_input').val();
		CV['qcrtcity']=$('#radius_city_input').val(); 
		CV['qcrtstate']=$('#radius_state_select').val(); 
		CV['qcrtzip']=$('#radius_zip_input').val(); 
		CV['qradlimit']=$('#radius_distance_input').val(); 
		    
        sidebarSet();
				
		//$("#radius_option_select").html("<option value=\" \"> </option>");
		$('#radiusOptions_dialog').dialog('close');
		
    }	
    
    function clearRadiusInputs(){
	    
       $('#radius_zip_input').val('');   
	   $('#radius_zip_2_input').val('');
	   $('#radius_distance_input').val('');
	   $('#radius_address_input').val('')
	   $('#radius_city_input').val('')
	   $('#radius_option_select').attr('selected', false);
	   document.getElementById('radius_state_select').selectedIndex=0;
    }
    
	function loginSubmit() {
		$('#login_dialog').dialog('close');
		getCustInfo();
		//return;
	}
	
	function savecutoff(o){
		
	   //this is joined with quanity value in radius and visa versa	
   	   $('#cutoff_dialog').dialog('close');
   	   var mcutoff=$('#job_cutoff_input').val();
   	   
   	   mcutoff = jQuery.trim(mcutoff);
		
	   if (mcutoff==''){
   	      mcutoff=0;
       }
       $('#cutoff_input').val(mcutoff);	   
	   cvAddVal('job_cutoff', mcutoff);
	   //add it to radius input
	   	      
	   $('#job_cutoff_input').val(mcutoff);	 
    }		
	
	function showvars(o){
		
		var varblock="<table>";
		
		$.each(CV, function(key, value) {
		    varblock=varblock+'<tr><td width="25%">'+key+'</td><td width="75%">'+value+'</td></tr>';
	    });
		
        varblock=varblock+"<table>";
        $('#display_vars').html(varblock || 'no vars'); 
        
        $('#display_vars').dialog({
					buttons: { 
						"Close": function() { $('#display_vars').dialog('close'); }
					},
					title: 'The currently definned count varibles that will be sent to server.'
	    })
		
        $('#display_vars').dialog({ autoOpen: false })
        $('#display_vars').dialog('open') 

   	    $('#display_vars').dialog('show')
   	   
    }		
    
	function orderInfo() {
		//leave this as is, sets up the page and I build another function --loadCount()--to load ajax return into CV object and sidebar using the two funtions Aaron built
		//aaron--->AJAX call to get current order info, callback creates BL object extending BLdata @todo: finish this
		formSet();	
		sidebarSet();
		window.BL = new BLdata();
		return;
	}
	
	
	function manageSegments(maction,mvar,o){
		
	    if (maction=='N' || maction=='R'){
			var strErr=mvar;
			strErr = jQuery.trim(strErr);
		    if (maction=="N"){ var thetitle="Error adding new segment." } else { var thetitle="Error changing segment name." };
			if (strErr==''){
			    blAlert({ title: 'Error adding/changing segment: ', text: 'You must enter a valid segment name.' });
			    return null;	    
	    	} else {
		
			    $('#segment_dialog').dialog('close');
				
	        }
		} else {
		
			$('#segment_dialog').dialog('close');
				
	    }	
		
	    
	    if (mvar===CV.description){
		    return null;
	    }    
	    

		//if a count has not been saved then just use the name of the current empty count
		strChk = jQuery.trim(CV.theheader);
		if (strChk.length==0){
			
			CV['description']=mvar;
			
			var moptions='<option value="">'+CV.description+'</option>'; 
			$("#segment_select").html(moptions);
	
			
	    	return null;
    	           
	    }
		

		//grayOut(true);
		document.getElementById('plswait').style.display = 'block';
		cInfo	= {
			theaction: maction,
			cID: CV.custid,
			newjob: $("#segment_select").val(),  
		    theheader: CV.theheader,  
		    countname: mvar      	            
		},
                	
		$.post('include/php/manageSegments.php', cInfo, function(data) {
				
			//grayOut(false);
			//document.getElementById('plswait').style.display = 'none';
			var strErr=data.theErr;
		    strErr = jQuery.trim(strErr);
		
		    if (strErr !=''){
			    //grayOut(false);
			    document.getElementById('plswait').style.display = 'none';
			    blAlert({ title: 'Error managing segments: ', text: strErr });
		    } else {
			    
			    CV['thejob']=data.Countnum;
			    CV['theheader']=data.Headerno;
			    
			    
			   //had to remove because sessions from page to page did not work in production server --cannot just run loadcount() until I write the code to clear entire form.
			   var  id=CV['custid'];
		       var conm=document.getElementById('companylogged').value;
		       var jbno=data.Countnum;
		       var header=data.Headerno;
		
		  
			    var theserveradd=document.getElementById('remhost').value;
		        if (theserveradd=='localhost' || theserveradd=='12.46.52.206' || theserveradd=='12.46.52.149'){
			        theserveradd=theserveradd+'/bl';
		        }    	   
			   	
		        if (document.getElementById('isSSL').value==='T'){
			        theserveradd="https://"+theserveradd;
		        } else {
			        theserveradd="http://"+theserveradd;    
		        }  
		        		   		   
               window.location =theserveradd+"/index.php?theid="+id+"&conm="+conm+"&jbno="+jbno+"&header="+header;
  
			   //location.reload();
		    } 
		    
		    
		}, 'json');
		
    }	
    
    //orders_open_select
    function manageOrders(maction,mvar,whichone,mpo){
	    

	   if (maction=='A' || maction=='R' || maction=='C' || maction=='S'){
			var strErr=mvar;
			strErr = jQuery.trim(strErr);
		    if (maction=="A"){ var thetitle="Error adding new order." } else if (maction=="C"){ var thetitle="Error cloning an existing order." } else if (maction=="S"){ var thetitle="Error saving order." } else { var thetitle="Error changing order name." };
			if (strErr==''){
			    blAlert({ title: thetitle, text: 'You must enter a valid order name.' });
			    return null;	    
	    	} else {
		    	//alert(mvar); 
	   			if (maction=='R'){
	   			   $('#rename_dialog').dialog('close') 
       			} else if (maction=='C'){
	   			   $('#submit_clone_dialog').dialog('close') 
       			} else if (maction=='S'){
	   			   $('#savePO_dialog').dialog('close') 
       			}  else if (maction=='A'){
	   			   $('#addnew_dialog').dialog('close') 
       			} 
		    	
	        }	
		    	
		} else {  
	     
	   		//alert(mvar); 
	   		if (maction=='R'){
	   		   $('#rename_dialog').dialog('close') 
       		} else if (maction=='C'){
	   		   $('#submit_clone_dialog').dialog('close') 
       		} else if (maction=='S'){
	   		   $('#savePO_dialog').dialog('close') 
       		}  else if (maction=='A'){
	   		   $('#addnew_dialog').dialog('close') 
       		} 
       }

		var theSelectedHdtmp="";
		var theSelectedHd="none";
		var thesel=0;	
	      	
		//if its a rename or clone		    
	    if (maction=='R' || maction=='C' || maction=='E' || maction=='D'){
		   
		    if (whichone=='open'){
		      thesel=document.forms['orderManage'].orders_open_select.selectedIndex;
		      theSelectedHdtmp=document.forms['orderManage'].orders_open_select.options[thesel].value;
	        } else {
		     
		      thesel=document.forms['orderManage'].orders_submitted_select.selectedIndex; 
		      theSelectedHdtmp=document.forms['orderManage'].orders_submitted_select.options[thesel].value;
	        }   
		    
	       
	        if (theSelectedHdtmp=="" || theSelectedHdtmp==null ){
		        blAlert({ title: "Error: Order Management", text: 'You must select an order to work with.' });
			    return null;	 
	        } 
	        
	        //alert(theSelectedHdtmp);
			//the entire record is pumped into the value to make sorts ect easy to re-arrange the select box		
			mrec=theSelectedHdtmp.split("`");
			theSelectedHd=mrec[0];
			
			
	    } 
	    
	    //if its a save
	    if (maction=='S'){
		   
			theSelectedHd=CV['theheader'];
		
	    } 
	    
		//alert(whichone);	
	    //alert(theSelectedHd);
	    //return null;
	    		
		lInfo	= {
   		  cID: CV.custid ,
		  selHeader:  theSelectedHd,
		  theaction: maction,
		  seljob: $("#segment_select").val(),
		  countname: mvar, 
		  theoldheader: CV.theheader,
		  theoldjobnum: CV.thejob,
		  thedata:whichone,
		  theponum: mpo     	 
		},
		
        //grayOut(true);
	    document.getElementById('plswait').style.display = 'block';
		  
		//alert(  lInfo.selHeader +" line #1091");   	
		$.post('include/php/manageOrders.php', lInfo, function(data) {
				
			//grayOut(false);
			//document.getElementById('plswait').style.display = 'none';
			
			var strErr=data.theErr;
		    strErr = jQuery.trim(strErr);
		
		    if (strErr !=''){
			   
			   //grayOut(false);
			   document.getElementById('plswait').style.display = 'none'; 
			    
			   blAlert({ title: 'Error opening the order: ', text: strErr });
		    } else {
			    
			    
			    if (maction !='S'){
			    	CV['thejob']=data.Jobno;
			    	CV['theheader']=data.Headerno;
		        }
			    
			    //had to remove because sessions from page to page did not work in production server --cannot just run loadcount() until I write the code to clear entire form.
			    //loadCount();  
			   
			    if (maction=='S'){
			    
			        blAlert({ title: 'Operation Complete: ', text: 'Count #'+CV.theheader+' has been saved.' });
			    
		        }
			    
			    
			    var  id=CV['custid'];
		        var conm=document.getElementById('companylogged').value;
		        var jbno=data.Jobno;
		        var header=data.Headerno;
				  
		 	    var theserveradd=document.getElementById('remhost').value;
		        if (theserveradd=='localhost' || theserveradd=='12.46.52.206' || theserveradd=='12.46.52.149'){
			        theserveradd=theserveradd+'/bl';
		        }    		   
			   		
		        if (document.getElementById('isSSL').value==='T'){
			        theserveradd="https://"+theserveradd;
		        } else {
			        theserveradd="http://"+theserveradd;    
		        }
		           
                window.location =theserveradd+"/index.php?theid="+id+"&conm="+conm+"&jbno="+CV['thejob']+"&header="+CV['theheader'];
			   	    
			    //had to remove because sessions from page to page did not work in production server 
			    //location.reload();
			    
		    } 
		    
		    
		}, 'json');
		
    }	
    
   
    		
	function loadCount(o, callback){
		var count = $.extend(true, {}, CV, o);
				
		//alert(CV.thejob+" line #1113");
		//if CV.thejob & CV.theheader do not match data.ordernum & data.countnum throw error
		
		
		$.post('include/php/loadCnt_process.php', count, function(data) {
			CV['radiusCentroid'].push=" ";
			
			//only exist if logged in
			if (document.getElementById('count-info')){
				if (data.numberofsegments > 1){
				   document.getElementById('count-info').style.display = 'block'; 
		    	} else {
				   document.getElementById('count-info').style.display = 'none'; 
		    	}   
	        }    
			//these are not used
			//load the html page with values
			//$('#order_number').html(data.ordernum || 'None');
			//$('#segment_amt').html(data.orderprice || '0.00');
			//$('#count_description').html(data.description || 'Temporary Count');
			var thesegmentCNT=addCommas(data.numrecords);
			var thecountCNT=addCommas(data.totalrecs);
			
			$('#report_email_input').val(data.email);
            
			$('#segment_output').html(thesegmentCNT || '0'); 
			$('#segment_name').html(data.description || 'Temporary count');
			//$('#count_amt').html('$'+data.totalamt || '0.00');
            $('#count_records').html(thecountCNT || '0');
			
			var mincharges=0;
            var minord=$('#min_order').val();
            //var emailchrg=$('#emailFTPprice').val();
            //mincharges=(parseFloat(minord)+parseFloat(emailchrg));
            //took out the email charges
            mincharges=parseFloat(minord);
            
            if (data.totalrecs > 0){
            	//alert(mincharges);
	  			var thenewtotal=data.totalamt;
	  			if (thenewtotal < mincharges){
				  thenewtotal= mincharges;
				}	
				
				var thenewtotalDisp=addCommas(thenewtotal);
				  
	            $('#count_amt').html('$'+thenewtotalDisp || '0.00');
            } else {
	        	$('#count_amt').html(' ');
            }			
            CV['amtdue']=thenewtotal;
            
            var zcid=CV.custid; 
   		    if (zcid=='CI0118'){
               $('#count_amt').html(' ');
            }
            
			//for jobsubmit
			$('#order_description_input').val(data.head_descr);
			$('#order_po_input').val(data.head_po);
			$('#order_submitter_input').val(data.head_submit);
			$('#order_job').html(data.ordernum || 'Error');
            $('#order_quantity').html(data.totalrecs || '0');
			$('#order_emailto_input').val(data.head_email || 'Email Address');
            $('#order_instructions_textarea').val(data.head_notes || ' ');
 
                        
            //cutoff value
            var thecutoff=jQuery.trim(data.job_cutoff);
            if (thecutoff !=''){
                  
               $('#job_cutoff_input').val(data.job_cutoff);
               $('#cutoff_input').val(data.job_cutoff);
            }
            
            
            //lets mark the additional inputs
            
            var theemplow=jQuery.trim(data.employee_low);
            if (theemplow !=''){
             $('#employee_low_input').val(data.employee_low) ;  
            }
            
            var theemphigh=jQuery.trim(data.employee_high);
            if (theemphigh !=''){
             $('#employee_high_input').val(data.employee_high);   
            }
            
            var theslslow=jQuery.trim(data.sales_low);
            if (theslslow !=''){
             $('#sales_low_input').val(data.sales_low); 
            }
            
            var theslshigh=jQuery.trim(data.sales_high);
            if (theslshigh !=''){
             $('#sales_high_input').val(data.sales_high);  
            }
            
            //set addtional selects
            $('#employee_range_select').val(data.employee_range);
            $('#sales_range_select').val(data.sales_range);
            $('#location_type_select').val(data.location_type);
            $('#gender_select').val(data.gender);
            $('#pub_priv_select').val(data.pub_priv);
             
            $('#radius_address_input').val(data.qcrtadd);
		    $('#radius_city_input').val(data.qcrtcity); 
		    $('#radius_zip_input').val(data.qcrtzip); 
		    $('#radius_distance_input').val(data.qradlimit); 
            
  
		    //document.getElementById('radius_state_select').selectedIndex=0;
            //var cntx=0;
		    //while (cntx <= 50){
  		    //CV['data.qcrtstate']=$('#radius_state_select').val(data.qcrtstate); 
            
 
            //'head_pymt_type' ----not set yet
            if(data.head_pymt_type=="CREDIT CARD"){
               document.getElementById('payment_type_input_3').checked = true;
            } else if (data.head_pymt_type=="FAX BY CHECK"){  
	           document.getElementById('payment_type_input_2').checked = true; 
            } else {     
	          document.getElementById('payment_type_input_1').checked = true;    
            }  
              
	        toggleCC();
	           
            if(data.head_combine=="Y"){
              document.getElementById('order_combine_segments').checked= true;
	        } else {
	          document.getElementById('order_combine_segments').checked= false; 
            }                   
            
                    
 			//head_ship_type
            var theoutput=data.head_ship_type;   		
            
			if (theoutput.indexOf("CD") > -1) {
				//alert("CD");
		    	document.getElementById('order_shiptype_1').checked= true;
         		document.getElementById('order_output_type_1').checked= true;
         		if (theoutput.indexOf("CSV") > -1) {
				   document.getElementById('order_data_file_1').checked = true;
	        	} else if(theoutput.indexOf("Delimited") > -1) {
	     		   document.getElementById('order_data_file_2').checked = true;
	        	} else {
	        	   document.getElementById('order_data_file_3').checked = true;
	        	} 

        	} else if (theoutput.indexOf("Email") > -1) {	
	        	//alert("email");
        	    document.getElementById('order_output_type_2').checked= true;
            	document.getElementById('order_shiptype_3').checked= true;
            	if (theoutput.indexOf("CSV") > -1) {
				   document.getElementById('order_data_file_1').checked = true;
	        	} else if(theoutput.indexOf("Delimited") > -1) {
	     		   document.getElementById('order_data_file_2').checked = true;
	        	} else {
	        	   document.getElementById('order_data_file_3').checked = true;
	        	} 
            
        	} else {
	        	//alert("label");
            	document.getElementById('order_shiptype_1').checked= true;
            	document.getElementById('order_output_type_3').checked= true;
            	
            	
            	if (theoutput.indexOf("Cheshire") > -1) {
		   		   document.getElementById('order_label_type_1').checked = true; 
	        	} else if(theoutput.indexOf("4-Up PS") > -1){
	     		   document.getElementById('order_label_type_2').checked = true; 
	        	} else {
	     		   document.getElementById('order_label_type_3').checked = true; 
	        	} 
            
        	}	 
            	
        	var shipChk=data.head_notes;
        	if(shipChk.indexOf("Shipping Info") > -1){
	        	
        	    document.getElementById('order_ship_line1_input').value=" ";
        	    document.getElementById('order_ship_line2_input').value=" ";
			    document.getElementById('order_ship_line3_input').value=" ";
			    document.getElementById('order_ship_line4_input').value=" ";        	
        	
    	    }
    	    
    	 			
            cvAddVal('orderrecords',data.totalrecs);
			
			//load open orders
			
			openord = data.openorders.split("^");
			
			var options = "";
			for (var i = 0; i < openord.length; i++) {
			  //alert(openord[i]);  
			  mrec=	openord[i].split("`");
			  mrec[0]=jQuery.trim(mrec[0]);
			  mrec[1]=jQuery.trim(mrec[1]);
			  mrec[3]=jQuery.trim(mrec[3]);
			  var mnumrecs=jQuery.trim(mrec[4]);
			  var mpo=jQuery.trim(mrec[2]);
			  
			  var xcnt=0;
			  
			  if (jQuery.trim(mpo) !=''){
				xcnt=mpo.length;
              } else {
	            mpo='NONE';
	            mrec[2]='NONE';
	            xcnt=4; 
              }    
			 
              //need to come back to this, could use ASCII maybe but this works fine- padding not working properly
              while (xcnt < 15){
	              mpo= mpo+'&nbsp;';
	              xcnt=xcnt+1;
              }  

              var xcnt=0;
			  
			  if (jQuery.trim(mnumrecs) !=''){
				xcnt=mnumrecs.length;
              } else {
	            mnumrecs='0';
	            mrec[4]='0';
	            xcnt=1; 
              }    
			 
              //need to come back to this, could use ASCII maybe but this works fine- padding not working properly
              while (xcnt < 10){
	              mnumrecs= '&nbsp;'+mnumrecs;
	              xcnt=xcnt+1;
              }  
              
              var mvalue=jQuery.trim(mrec[0])+'`'+jQuery.trim(mrec[1])+'`'+jQuery.trim(mrec[2])+'`'+jQuery.trim(mrec[3]);
			  var newoption=mrec[0]+'&nbsp;&nbsp;&nbsp;'+mrec[1]+'&nbsp;&nbsp;'+mnumrecs+'&nbsp;&nbsp;'+mpo+'&nbsp;&nbsp;&nbsp;'+mrec[3];
			  if (	jQuery.trim(openord[i]) !=''){
				 options += '<option value="' + mvalue + '">'+newoption+'</option>'; 
			  }  
				
			 
			  
			 			      
			}      
			$("#orders_open_select").html(options);
			//alert(data.openorders+" line #1263");
			
			
			//load previous orders
			porders = data.prevorders.split("^");
			options = "";
			
				
			for (var i = 0; i < porders.length; i++) {
				
			  mrec=	porders[i].split("`");
			  mrec[0]=jQuery.trim(mrec[0]);
			  mrec[1]=jQuery.trim(mrec[1]);
			  mrec[3]=jQuery.trim(mrec[3]);
			  var mnumrecs=jQuery.trim(mrec[4]);
			  var mpo=jQuery.trim(mrec[2]);
			  
			  var xcnt=0;
			  
			  if (jQuery.trim(mpo) !=''){
				xcnt=mpo.length;
              } else {
	            mpo='NONE';
	            mrec[2]='NONE';
	            xcnt=4;   
              }    
			 
              //need to come back to this, could use ASCII maybe but this works fine- padding not working properly
              while (xcnt < 15){
	              mpo= mpo+'&nbsp;';
	              xcnt=xcnt+1;
              }  
 
              var xcnt=0;
			  
			  if (jQuery.trim(mnumrecs) !=''){
				xcnt=mnumrecs.length;
              } else {
	            mnumrecs='0';
	            mrec[4]='0';
	            xcnt=1; 
              }    
			 
              //need to come back to this, could use ASCII maybe but this works fine- padding not working properly
              while (xcnt < 10){
	              mnumrecs='&nbsp;'+mnumrecs;
	              xcnt=xcnt+1;
              }  
              
              
              
              var mvalue2=jQuery.trim(mrec[0])+'`'+jQuery.trim(mrec[1])+'`'+jQuery.trim(mrec[2])+'`'+jQuery.trim(mrec[3]);
			  var newoption=mrec[0]+'&nbsp;&nbsp;&nbsp;'+mrec[1]+'&nbsp;&nbsp;'+mnumrecs+'&nbsp;&nbsp;'+mpo+'&nbsp;&nbsp;&nbsp;'+mrec[3];
			  if (	jQuery.trim(porders[i]) !=''){
			     options += '<option value="' + mvalue2 + '">'+newoption+'</option>'; 
		 	  }		      
			}      
			$("#orders_submitted_select").html(options);
			
			//load orders segments
			var thesegments=jQuery.trim(data.segmentselect);
			options = "";
			if (thesegments.length ==0){
				options += '<option value="">Temporary Count</option>'; 
			} else {
			      
		        msegments = data.segmentselect.split("^");
				for (var i = 0; i < msegments.length; i++) {
					 if (	jQuery.trim(msegments[i]) !=''){
				         options += '<option value="' + msegments[i].substring(0,6) + '">'+msegments[i].substring(7)+'</option>'; 
		 		     }		      
				} 
				
			}     
			$("#segment_select").html(options);
		   
				
			//test for existance of the document object---not active in initial state b4 login
			var productElement =  document.getElementById('accordion-segments');
            if (productElement != null){

				var thecnt=document.forms['segmentsForm'].segment_select.options.length-1;
			           
				//lets mark the select boxes
				for (i=0; i <= thecnt; i++){
            	    var tmpstr=document.forms['segmentsForm'].segment_select.options[i].value;
                
            	    mrec=tmpstr.split("|");
		    	    mrec[0]=jQuery.trim(mrec[0]);               
		    	    data.countnum=jQuery.trim(data.countnum);
					if (mrec[0]===data.countnum){  
					   document.forms['segmentsForm'].segment_select.selectedIndex=i;
   		    	       break;
            	    }   
				
            	}
            } //end of check for object
            
           		
			//test for existance of the document object---not active in initial state b4 login
			var productElement =  document.getElementById('orderManage');
            if (productElement != null){

				var thecnt=document.forms['orderManage'].orders_open_select.options.length-1;
			           
				//lets mark the select boxes
				for (i=0; i <= thecnt; i++){
            	    var tmpstr=document.forms['orderManage'].orders_open_select.options[i].value;
                
            	    mrec=tmpstr.split("`");
		    	    mrec[0]=jQuery.trim(mrec[0]);               
		    	    data.ordernum=jQuery.trim(data.ordernum);
					if (mrec[0]===data.ordernum){  
					   document.forms['orderManage'].orders_open_select.selectedIndex=i;
   		    	       break;
            	    }   
				
            	}
            } //end of check for object
			
			
			
			
			
			
			//mark extra fields			
			var extrafld = ['recYR_STARTED','recSUBSID_IND','recPUB_PRIVATE','recSALES_VOL','recEMPL_TOTAL','recTELEPHONE','recCONTACT','recFRAN_CODE']; 
 
						//all extra fields are empty on startup so just add ones that are checked
						$.each(extrafld, function(key, value) {
							
							var theval=eval('data.'+value);
							
							if (theval==="T"){															
							    //this takes into account grouping- could put on back end but did not want to bury values
								if (value=='recCONTACT'){
 									CV['recCEO_1ST_NM'] = 'T';
                            		CV['recCEO_LST_NM'] = 'T';
			                		CV['recDDM_TITLE'] = 'T';     
		                    	} else if (value=='recSALES_VOL'){
			                		CV['recSALES_VOL'] = 'T';
			                		CV['recSALES_VOL_CD'] = 'T';
			                	} else if (value=='recEMPL_TOTAL'){
			                		CV['recEMPL_TOTAL'] = 'T';
			                		CV['recEMPL_TOT_CD'] = 'T';
						    	} else {
									CV[value] = 'T';
				    			}
				    		 	 
				    			eval("sidebarAdd({ cv: '"+value+"', group: $('#selection-fields'), text: $('input[id=\""+value+"_input\"]').next('label').text() })");		 
				               	eval('$(\'input[id="'+value+'_input"]\').attr(\'checked\', true)');
                            }     
                                               
                        });
			
			//pump value into the count variable CV and check the appropriate boxes             
			$.each(data, function(key, value) { 
				    			  
		           //switch out if array for special handling 
				   varLoadArray=0;
				   
                    switch (key) {
                    
                                           
					  case 'reports':
				     	//varLoadArray=1;	//do not load reports
				     	//check the report boxes last saved
				     	//if (data.whichreports[0]=="Y"){ $('input[id="rptzip"]').attr('checked', true)}; 
                        //if (data.whichreports[1]=="Y"){ $('input[id="rptcr"]').attr('checked', true)}; 
                        //if (data.whichreports[2]=="Y"){ $('input[id="rptcity"]').attr('checked', true)}; 
                        //if (data.whichreports[3]=="Y"){ $('input[id="rptcnty"]').attr('checked', true)};  
                        //if (data.whichreports[4]=="Y"){ $('input[id="rptstate"]').attr('checked', true)}; 
                        //if (data.whichreports[5]=="Y"){ $('input[id="rptac"]').attr('checked', true)}; 
                        //if (data.whichreports[6]=="Y"){ $('input[id="rptsic2"]').attr('checked', true)};  
                        //if (data.whichreports[7]=="Y"){ $('input[id="rptsic4"]').attr('checked', true)};     
                        //if (data.whichreports[8]=="Y"){ $('input[id="rptsic6"]').attr('checked', true)};
                        //if (data.whichreports[9]=="Y"){ $('input[id="rptempl"]').attr('checked', true)};
                        //if (data.whichreports[10]=="Y"){ $('input[id="rptsls"]').attr('checked', true)};
				     	break
				     	
					  case 'zip':
						varLoadArray=1;
						break
					  case 'amtdue':
						//loaded above with min charges
						break	
					  case 'city':
						varLoadArray=1;
						break
					  case 'state':
				     	varLoadArray=1;	
				     	break
					  case 'crid':
						varLoadArray=1;
						break
					  case 'county':
						varLoadArray=1;
						break
					  case 'sic':
				     	varLoadArray=1;	
				     	break
					  case 'metro':
						varLoadArray=1;
						break
					  case 'acode':
						varLoadArray=1;
						break
					  case 'exclude_zip':
				     	varLoadArray=1;	
				     	break
					  case 'exclude_sic':
						varLoadArray=1;
						break
					  case 'jobtitle':
						varLoadArray=1;
						break
					  case 'suppress_counts':
				     	varLoadArray=1;	
				     	break
					  case 'suppress_orders':
						varLoadArray=1;
						break
					  case 'no_dups':
					  if (data.no_dups=='T'){
			   			 CV['contact_only']='F';
		              } else {
					     CV['contact_only']='T';
			          }	  
						break
					  default:
		
						cvAddVal(key, value);
						
					}//end of switch statement
				 
					//load the arrays
					if (varLoadArray==1){
					
				   		var str=eval("data."+key); 
	            		var arrayStr = str.split(",");
                
	            		for (x in arrayStr) {
		            		
		            	  arrayStr[x]=jQuery.trim(arrayStr[x]);
		            		
		            	  if (arrayStr[x] !=''){
			            	  
			            	  var checkdup=jQuery.inArray(arrayStr[x], CV[key] );
                                if (checkdup==-1){
								    cvAddVal(key, arrayStr[x]);	
							    }  
			            	  
			            	  
			            	  
           				    //cvAddVal(key, arrayStr[x]);
       					  
           				    
           				    
           				    
           				    
           				    
           				    
           				  }    		  
       					  
       					  //if job title loop over checkboxes  
       					  if (key=='jobtitle'){
	       					var y=1;  
       					    while (y < 36) {
	       					         					      
       					      var firstString = new String(eval("$(\"#jobtitle_input_"+y+"\").val()"));
                              var secondString = new String(arrayStr[x]);

							  var firstUpperString = firstString.toUpperCase();
							  firstUpperString = firstUpperString.replace(/ /g,'');

    						  var secondUpperString = secondString.toUpperCase();
    						  secondUpperString = secondUpperString.replace(/ /g,'');
    						  
    						  
							  if (y==29){  
	       					   //alert("input"+y+": "+firstUpperString+"  compared to "+secondUpperString);
       					      } 
       					      
	       					  if (firstUpperString==secondUpperString){ 
       					         eval("document.getElementById('jobtitle_input_"+y+"').checked = true");
   					          }
       					      y=(y+1);
   					        } //end of for loop
   					      } //end of jb check
       					  
       					  
	        			} //end of loop  
	        			
            		}
                
            		
            		
            		
            		
            	//sidebarSet();	
            		
               //}//end of check for value
                
             });
                          
		     
			sidebarSet();
			
			//do these after sidebarset() is fired
			if (data.thepkg=='B'){
			   $('input[id="thepkg_input_1"]').attr('checked', true);
			   $('#prices_basicrecord_items').show();
			   sidebarAdd({ cv: 'thepkg', group: $('#selection-package'), text: $('input[id="thepkg_input_1"]').next('label').text() });
			   
			   if (data.onetimeuse=='T'){
				   $('input[id="onetimeuse_input_1"]').attr('checked', true); 
				   sidebarAdd({ cv: 'onetimeuse', group: $('#selection-use'), text: $('input[id="onetimeuse_input_1"]').next('label').text() });		 
			  		   
			   } else {
			       $('input[id="onetimeuse_input_2"]').attr('checked', true); 
				   sidebarAdd({ cv: 'onetimeuse', group: $('#selection-use'), text: $('input[id="onetimeuse_input_2"]').next('label').text() });		 
			   }
			    	 
			} else {
			   $('input[id="thepkg_input_2"]').attr('checked', true);
			   $('#prices_basicrecord_items').hide();
			   sidebarAdd({ cv: 'thepkg', group: $('#selection-package'), text: $('input[id="thepkg_input_2"]').next('label').text() });
			   $('input[id="onetimeuse_input_1').attr('checked', false); 
			   $('input[id="onetimeuse_input_2').attr('checked', false); 	 
			}    
				
			if (data.zip4only !='F'){
			   $('input[id="options_includes_input_1"]').attr('checked', true);
		    }    
		    
			if (data.executive=='T'){
			   $('input[id="options_includes_input_2"]').attr('checked', true);
			  
		    } else {
			   $('input[id="options_includes_input_2"]').attr('checked', false); 
		    }    		
			
		    if (data.no_dups=='T'){
			   $('input[id="options_includes_input_3"]').attr('checked', false);
			   CV['contact_only']='F';
		    } else {
			   $('input[id="options_includes_input_3"]').attr('checked', true); 
			   CV['contact_only']='T';
		    }    
		    
			//add side panel for extra fields
			$.each(extrafld, function(key, value) {
				var theval=eval('data.'+value);
				if (theval==="T"){																 
			  	  eval("sidebarAdd({ cv: '"+value+"', group: $('#selection-fields'), text: $('input[id=\""+value+"_input\"]').next('label').text() })");		 
				}     
            });
			
			if (callback && _.isFunction(callback)) {
				callback.call();
			}
			
		}, 'json');
		
		//grayOut(false);
		//document.getElementById('plswait').style.display = 'none';
			
		sidebarSet();
		return;
    }
    
    $.strPad = function(i,l,s) {
	var o = i.toString();
	if (!s) { s = '0'; }
	while (o.length < l) {
		o = s + o;
	}
	return o;
    };
	
    function postInvoice(){
	    	
  	var theremaddr=$("#remaddr").val();
  	var theremhost=$("#remhost").val(); 
  	var thehttphost=$("#remhttp").val();
  	
  	var theRefnum = CV.theheader+"-BL";
 
//visa/master not used right now
//$('#cc_type_select').val()
	
  	var cc_Fname = $('#cc_first_name_input').val();
  	var cc_Lname = $('#cc_last_name_input').val();
  	var cc_ADD = $('#cc_address_input').val();
  	var cc_City = $('#cc_city_input').val();
  	var cc_State = $('#cc_state_input').val();
  	var cc_Zip = $('#cc_zip_input').val();
  	var cc_email = $('#cc_email_input').val();
  	var cc_ph = ' ';
  
  	var cc_cvv= $('#cc_cvv_input').val();
  	var cc_card = $('#cc_number_input').val();
  	var cc_expireMonth = $('#cc_month_input').val();
  	var cc_expireYear = $('#cc_year_input').val();
  	
  	//SELECT PAYMENT TYPE
  	var thePymt="";
	if(document.getElementById('payment_type_input_1').checked == true ){    
        thePymt="BILL ACCOUNT";
    } else if(document.getElementById('payment_type_input_2').checked == true ){ 
	    thePymt="FAX BY CHECK";
 	} else {
	    thePymt="CREDIT CARD";
 	}  
  	  	
  	if (thePymt=="CREDIT CARD"){
  	
  	   var isValidCard=checkCCinfo(cc_card, $('#cc_type_select').val(),cc_cvv,cc_expireYear,cc_expireMonth);
  	   isValidCard=jQuery.trim(isValidCard);
  	   
  	   if (isValidCard.length !=0){
  	      //alert(isValidCard);
	  	  blAlert({ title: 'Credit card input validation.', text: isValidCard }); 		 
  	      return null;
 	   }
 	   
    } 
    	 
    //return null;
  
	closeCheckout();
	var theoutput='';	
	if(document.getElementById('order_output_type_2').checked == true ){
		theoutput='EMAIL';		
    }		
	  
	    iInfo	= {
			cID: CV.custid,
			job: CV.theheader,
			description: CV.description,		//***// user filled out order description  --- these are being changed to global on header file
			special_instructions: CV.special_instructions,		// user filled out instructions - file goes to Sharon and processed manually 
			file_output: CV.file_output,		// get from table and use named list default 'CSV File Email'
			po_number:	CV.po_number,		// user filed in PO number
			user_submit: CV.user_submit,		// name or initials of user submitting order
			table: "NOT USED",
			payment_type: thePymt,
			totalamtdue: CV.amtdue,
			totalrecords: CV.numrecords,
		    combinesegs: CV.combineseg,
		    theoutputtype: theoutput,
		    theemailcharge: $('#emailFTPprice').val(),
		    theemail: $('#order_emailto_input').val(),
		    thecompany: $('#companylogged').val(),
            thepromocode:$('#order_promo_input').val(),
            remoteaddr: theremaddr,
  	        remotehost: theremhost,
  	        remotehttp: thehttphost,
  	        ccRefnum: theRefnum,
            ccFname: cc_Fname,
  	        ccLname: cc_Lname,
  	        ccAddr: cc_ADD,
  	        ccCity: cc_City,
  	        ccState: cc_State,
  	        ccZip: cc_Zip,
  	        ccEmail: cc_email,
  	        ccPh: cc_ph,
        	ccCVV: cc_cvv,
  	        ccCard: cc_card,
  	        ccExpMth: cc_expireMonth,
  	        ccExpYr: cc_expireYear
		    		         	            
		},
             
		//grayOut(true);  
	    document.getElementById('plswait').style.display = 'block';  
		
		  	
		$.post('include/php/postInvoice.php', iInfo, function(data) {
				
			//grayOut(false);
			document.getElementById('plswait').style.display = 'none';
			document.getElementById('plswaitSubmit').style.display = 'none';
			
			var strErr=data.theErr;
		    strErr = jQuery.trim(strErr);
		
		    //alert(strErr+"  :Line 2580 bl.js");
			//return null;
		    
			
			if (strErr !=''){
			 			  
			    blAlert({
  				 title:	'There was an error placing your order:<br>', 
				 text:	strErr,
				 callback:	function() {
				    
					//location.reload();
			   		var theserveradd=document.getElementById('remhost').value;
		        	
			   		if (theserveradd=='localhost' || theserveradd=='12.46.52.206' || theserveradd=='12.46.52.149'){
			        	theserveradd=theserveradd+'/bl';
		        	}     			   
			  		   
		        	if (document.getElementById('isSSL').value==='T'){
			        	theserveradd="https://"+theserveradd;
		        	} else {
			        	theserveradd="http://"+theserveradd;    
		        	}  
		        	
		        	window.location =theserveradd+"/index.php?theid="+CV.custid+"&conm="+$('#companylogged').val()+"&jbno="+CV.thejob+"&header="+CV.theheader;   		   
               		//window.location =theserveradd+"/index.php?cID="+CV['custid'];
				 }
			   });
			  
		    } else {
			  //blAlert({ title: 'Thank you!', text: 'Order number ' + data.thenewnumber + ' has been submitted for processing.\n\nIf you have any problems please contact Customer Service at 800-632-1379.\n\nThank you for your order!' }); 
			  
			  
			    blAlert({
  				 title:	'Thank you!', 
				 text:	'Order number ' + data.thenewnumber + ' has been submitted for processing.\n\nIf you have any problems please contact Customer Service at 800-632-1379.\n\nThank you for your order!',
				 callback:	function() {
				    
					//location.reload();
			   		var theserveradd=document.getElementById('remhost').value;
		        	
			   		if (theserveradd=='localhost' || theserveradd=='12.46.52.206' || theserveradd=='12.46.52.149'){
			        	theserveradd=theserveradd+'/bl';
		        	}     			   
			  		   
		        	if (document.getElementById('isSSL').value==='T'){
			        	theserveradd="https://"+theserveradd;
		        	} else {
			        	theserveradd="http://"+theserveradd;    
		        	}  
		        	
		        	    		   
               		window.location =theserveradd+"/index.php?cID="+CV['custid'];
				 }
				 
				});
			  
		    } 
		    
		    
		}, 'json');

    }    
    
    function procYear(theDate){
	  x = theDate.getYear();
	  var y = x % 100;
	  y += (y < 38) ? 2000 : 1900;
	  return y;
    }
    
    function checkCCinfo(cardNumber, cardType, cvvNumber, expYear, expMonth){

  		var isValid = false;
		var ccCheckRegExp = /[^\d ]/;
		
		var cvvlen = cvvNumber.length;
		
		
		var errorSTR="";
		
		//we currently on take MC and Visa and those numbers are 3 digits, if we start taking amex then we need to expand this logic to include amex 4 digit codes
		if (cvvlen !=3){
			errorSTR=errorSTR+'<br>This is not a valid credit card verification number.';
	    }	
			
		var theexpyear=parseInt(expYear);
		var theexpmonth=parseInt(expMonth);
		var today = new Date();
	    var theCurYear = procYear(today); //takeyear() is in the function.js file
	    var theCurMonth = today.getMonth();
        theCurMonth=parseInt(theCurMonth)+1;
        
        var fnm = $('#cc_first_name_input').val();
        fnm=jQuery.trim(fnm);
        if (fnm.length==0){ errorSTR=errorSTR+'<br>First name cannot be empty.' };
        
  	    var lnm = $('#cc_last_name_input').val();
  	    lnm=jQuery.trim(lnm);
  	    if (lnm.length==0){ errorSTR=errorSTR+'<br>Last name cannot be empty.' };
  	    
  	    var add = $('#cc_address_input').val();
  	    add=jQuery.trim(add);
  	    if (add.length==0){ errorSTR=errorSTR+'<br>Address cannot be empty.' };
  	    
  	    var cty = $('#cc_city_input').val();
  	    cty=jQuery.trim(cty);
  	    if (cty.length==0){ errorSTR=errorSTR+'<br>City name cannot be empty.' };
  	    
  	    var st = $('#cc_state_input').val();
  	    st=jQuery.trim(st);
  	    if (st.length==0){ errorSTR=errorSTR+'<br>State cannot be empty.' };
  	   
  	    var zip = $('#cc_zip_input').val();
  	    zip=jQuery.trim(zip);
        if (zip.length==0){ errorSTR=errorSTR+'<br>Zip code name cannot be empty.' };
        
	    if (theexpyear <  theCurYear){
			errorSTR=errorSTR+'<br>The is is not a valid expiration date.';
	    }			
		
	    if ((theexpmonth <  theCurMonth) && (theexpyear==theCurYear)){
			errorSTR=errorSTR+'<br>The is is not a valid expiration date.';
	    }	
	    
		isValid = !ccCheckRegExp.test(cardNumber);

		if (isValid){
		    var cardNumbersOnly = cardNumber.replace(/ /g,"");
		    var cardNumberLength = cardNumbersOnly.length;
		    var lengthIsValid = false;
		    var prefixIsValid = false;
		    var prefixRegExp;

		    switch(cardType){
	
		    	case "Mastercard":
			        lengthIsValid = (cardNumberLength == 16);
			        prefixRegExp = /^5[1-5]/;
			        break;
			    case "Visa":
        			lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
        			prefixRegExp = /^4/;
        			break;

      			case "amex":
        			lengthIsValid = (cardNumberLength == 15);
        			prefixRegExp = /^3(4|7)/;
        			break;

      			default:
        			prefixRegExp = /^$/;
        			alert("Card type not found");
    		}

    	  prefixIsValid = prefixRegExp.test(cardNumbersOnly);
    	  isValid = prefixIsValid && lengthIsValid;
    
  		}

		if (isValid){
    		//nothing
    	} else {
  			errorSTR=errorSTR+'<br>The is is not a valid credit card number.';
  		}

	  return errorSTR;
  		
    } //end of function
    
   
    function openCheckoutWindow(){
	      
	       
		var theSelectedHd=$("#orders_open_select").val();
		
		lInfo = {
			
		  cID: CV.custid,
		  headjb:CV.theheader
		     	 
		},
           
		//alert(  jobno.selHeader +" line #1841");  
		//grayOut(true);
		document.getElementById('plswaitSubmit').style.display = 'block';
	    document.getElementById('invbld').style.display = 'block';
	  	
	    var x=0;
	    while (x < 1000000){
		    x=x+1;
	    }    
		$.post('include/php/tempInvoice.php', lInfo, function(data) {
				
			//grayOut(false);
			document.getElementById('plswaitSubmit').style.display = 'none';
			
			document.getElementById('invbld').style.display = 'none';
			var strErr=data.theErr;
		    strErr = jQuery.trim(strErr);
		
		    if (strErr !=''){
			   blAlert({ title: 'Error validating the counts: ', text: strErr });
			   closeCheckout();
  
		    } else {
			              
			    var linecolor='ccc'; 
  
    
    			r1= new Array();
    
    			//screen header
    			reportArray = new Array();
    			reportArray[0] = "Not used right now";
    			reportArray[1] = "<p><br><B>Temporary Invoice # "+data[0]+"</B><br><br></p>";  
    			reportArray[1] = reportArray[1]+"<div id='rptcoHead'><table>";  
                
    			linecolor='ccc';
			    
    			reportArray[1] = reportArray[1]+"<tr width='570px' style='background:#"+linecolor+"'>";
			    reportArray[1] = reportArray[1]+"<td id='labelclass' width='500px' align='left' >Description</td>";
	            reportArray[1] = reportArray[1]+"<td id='labelclass' width='70px' align='right' >Price</td></tr>";
	 	   
    			linecolor='CCFFCC';
     
    			var haslabels=0;
    			var isDigitalShipping=0;
    			
			    for (x in data) {
				    
				    if (data[x].indexOf("LABELS") > -1){
					   haslabels= haslabels+1; 
				    } 
				       
				    if (data[x].indexOf("E-MAIL") > -1 || data[x].indexOf("FTP") > -1){
					   isDigitalShipping=1;
				    } 
				    
				    
     				r1 = data[x].split("|");
       				mnum=x;
         			if (r1[1] != undefined){
	        
				        reportArray[1] = reportArray[1]+"<tr width='570px' style='zIndex:13;background:#"+linecolor+";'>";
	       				reportArray[1] = reportArray[1]+"<td width='500px' align='left' style=\"border:0px;background:#"+linecolor+";\" >"+r1[0]+"</td>";
	       				reportArray[1] = reportArray[1]+"<td width='70px' align='right' style=\"border:0px;background:#"+linecolor+";\" >"+r1[1]+"</td>";
           				reportArray[1] = reportArray[1]+"</tr>";
	  	 
	       					if (linecolor=="ccc"){
		      					linecolor='CCFFCC';
	       					} else{
		      					linecolor='ccc';
	       					}
	            
         			} // end of defined condition
         
     			} // end of loop
  
     
     			reportArray[1] = reportArray[1]+"</table></div>";
     
     			
     			document.getElementById('order_invoice_table').innerHTML= reportArray[1];  
     			//This is not your actual invoice. Once your order has been finalized and all charges added you will be sent your actual invoice
     			
     			var checkTerms=$('#terms').val();
     			
     			if (checkTerms.indexOf("COD") > -1 && haslabels < 1) {
                    document.getElementById('payment_type_1').style.display = 'none'; 
                    document.getElementById('payment_type_2').style.display = 'block'; 
                    document.getElementById('payment_type_3').style.display = 'block'; 
	                document.getElementById('payment_type_input_3').checked = true; 
                    document.getElementById('invoice_cc_div').style.display = 'block'; 
                }  else if (haslabels > 0 || isDigitalShipping==0) {
	                document.getElementById('payment_type_1').style.display = 'none'; 
	                document.getElementById('payment_type_2').style.display = 'none';
	                document.getElementById('payment_type_3').style.display = 'none'; 
                    document.getElementById('payment_type_input_3').checked = false; 
                    document.getElementById('invoice_cc_div').style.display = 'none';
                    document.getElementById('not_final_div').style.display = 'block'; 
                     
                } else {
	                
	                document.getElementById('payment_type_1').style.display = 'block'; 
	                document.getElementById('payment_type_2').style.display = 'block';
	                document.getElementById('payment_type_3').style.display = 'block'; 
                    document.getElementById('payment_type_input_3').checked = false;
                    document.getElementById('payment_type_input_1').checked = true; 
                    document.getElementById('invoice_cc_div').style.display = 'none';
                    document.getElementById('not_final_div').style.display = 'none'; 
	                
                }    
                
                
                
                document.getElementById('invbldprn').style.display = 'block';
			
		    } 
		    
		    
		}, 'json');
	    
	    
	    $('#order_invoice_dialog').dialog({
			buttons: {
			  "Cancel": function() { closeCheckout(); },
		   	  "Checkout": function() { postInvoice(); },
		   	  "Back": function() {openSubmitWindow() }		   	  
		    },
			
		    title: 'Submit Order',
			//position: ['center'],
			autoOpen: false, 
			height: 600, 
			width: 650, 
			modal: true 					
		});
					
		//jQuery("#order_invoice_dialog").dialog('option', 'position', [this.x,40]); 
        $('#order_invoice_dialog').dialog({ autoOpen: false });
        $('#order_invoice_dialog').dialog('open');
	    $('#order_invoice_dialog').dialog('option', 'position', 'center'); 
	    
    }    
    
    function openOrderInfo(){
	   
	    //$('#po_ord').val(CV.head_po);
  	    $('#count_description_ord').val(CV.head_descr);
			   
			   $('#OrderCntInfo_dialog').dialog({
					buttons: { 
						"OK": function() { openSubmitWindow($('#count_description_ord').val()); }
					},
					title: 'Rename Count'
			   })
		
		if (CV['head_descr']=="Temporary Count"){
          $('#OrderCntInfo_dialog').dialog({ autoOpen: false })
          $('#OrderCntInfo_dialog').dialog('open')	
        } else {
	      openSubmitWindow(CV.head_descr);  
        }    
        
        
    }    
    
    function openSubmitWindow(preordname){
	    
	    closeOrdInfo();
	    closeCheckout();
	   
	    mname=jQuery.trim(preordname);
    	if (mname.length > 0){
	        CV['head_descr']=preordname;
        }
        
        
	    $('#order_description_input').val(CV['head_descr']);
		$('#order_po_input').val(CV['head_po']);
	    
	    
	    var mcid=CV.custid;
				if (mcid=='' || mcid=='CI0115'){
			       blAlert({ title: 'Login Check: ', text: 'You must login before you can place an order, please click on the \'Log In\' menu item at top right part of this screen.' });
			       return null;	    
	    	    } 
	    	    
	    	    var mCount=CV.orderrecords;
	    	    
	    	    //this is for testing    	    
				//if (mCount > 25){
					
				   // blAlert({ title: 'Order Testing: ', text: 'We are limited on test orders to 25 records or less. You will need to change the filter to something that returns less than 25 records.' });
			       // return null;	    
	    	       
    	        //} 
    	        
    	        //hide show the selected formats or the default email layers
    	        var theoutput2=CV.head_ship_type;   		
             	if (theoutput2.indexOf("CD") > -1) {
				    document.getElementById('order_shiptype_3').checked=true;
		      		document.getElementById('labeltype_div').style.display = 'none';
                	document.getElementById('data_div').style.display = 'block'; 

        		} else if (theoutput2.indexOf("Label") > -1) {	
	        	    document.getElementById('order_shiptype_3').checked=true;
        	    	document.getElementById('labeltype_div').style.display = 'block';
                	document.getElementById('data_div').style.display = 'none';
                 
        		} else {
   	        	    document.getElementById('order_shiptype_3').checked=true;	
            		document.getElementById('labeltype_div').style.display = 'none';
            		document.getElementById('data_div').style.display = 'block'; 
        		}	 
    	        
    	        toggleOrderradio();
    	        
			    $('#order_submit_dialog').dialog({
					buttons: {
						"Cancel": function() { cancelSubmit(); },
						"Submit": function() { submitOrderPref(); }
					},
					title: 'Submit Order',
					//position: ['center'], 
					autoOpen: false, 
					height: 600, 
					width: 650, 
					modal: true 					
				})
				
				//fix FF abnomality
				if ($('#order_description_input').val()=="Temporary orderTemporary order"){
    	   			$('#order_description_input').val('Temporary order');
        		}	
        		
        		//alert(this.x + ', ' + this.y); 
                //jQuery("#order_submit_dialog").dialog('option', 'position', [this.x,116]); 

                $('#order_submit_dialog').dialog({ autoOpen: false });
                $('#order_submit_dialog').dialog('open');
				
	    
    }    
    
	function submitOrderPref() {

		     
		//validation
		var mcid2=CV.custid;
		var mjobnum=CV.theheader;
		var mnumrec=CV.orderrecords;
		var mname=$('#order_description_input').val();
		var mponum=$('#order_po_input').val();
		var msubmit=$('#order_submitter_input').val();
		var memail=$('#order_emailto_input').val();
		
		//fix FF abnomality
		if (mname=="Temporary orderTemporary order"){
    	   $('#order_description_input').val('Temporary order');
	       mname="Temporary order";
        }	
        
		var errmsg="";
		
		
		if (mcid2==''){
		    errmsg=errmsg+'<br><br><tab>You must login before you can place an order, please click on the \'Log In\' menu item at top right part of this screen.';    
	    }
	     	    
	    if (mnumrec < 1){
		    errmsg=errmsg+'<br><br><tab>There are no records identified, please change your criteria and click update.';        
    	} 
    	
		mjobnum=jQuery.trim(mjobnum);
    	if (mjobnum.length < 6){
		    errmsg=errmsg+'<br><br><tab>This is not a valid order number, please contact us to correct problem at 1-800-632-1379.';
     	} 
    	
    	mname=jQuery.trim(mname);
    	if (mname=="Temporary orderTemporary order"){
    	   $('#order_description_input').val('Temporary order');
	       mname="Temporary order";
        }	
        
    	if (mname.length < 1){
		    errmsg=errmsg+'<br><br><tab>Order description cannot be blank.';
		    document.getElementById('order_description_input').style.color='red';
     	} else {
	     	document.getElementById('order_description_input').style.color='black';
        } 	
    	
    	mname=jQuery.trim(mname);
    	if ( mname=="Temporary order" ){
		    errmsg=errmsg+'<br><br><tab>This is not a valid order description.';
		    document.getElementById('order_description_input').style.color='red';
    	}  else {
	     	document.getElementById('order_description_input').style.color='black';
        } 
    	
    	msubmit=jQuery.trim(msubmit);
    	if (msubmit.length < 1){
		    errmsg=errmsg+'<br><br><tab>Please enter your name for person submitting order.';
		    document.getElementById('order_submitter_input').style.color='red';
     	}  else {
	     	document.getElementById('order_submitter_input').style.color='black';
        } 
    	
          var emailchk=checkemail('order_emailto_input');
    
    	   
    	   if (jQuery.trim(emailchk) != "Correct") {
	    	   
	    	  if(document.getElementById('order_shiptype_3').checked == true ){
    	           errmsg=errmsg+'<br><br><tab>' +emailchk;
              } else {
	               errmsg=errmsg+'<br><br>Please provide a valid email for notification purposes.<br><br><tab>' +emailchk;
	              
              }           
              
	       }  
	       

        //check shipping info if 'ship to' selected 
        if(document.getElementById('order_shiptype_1').checked == true ){
	        
			 if(trim(document.getElementById('order_ship_line1_input').value)=="Attn"){errmsg=errmsg+'<br><br><tab>The ship to attention line needs the name order should be directed to.'};
			 if(trim(document.getElementById('order_ship_line2_input').value)=="Company"){errmsg=errmsg+'<br><br><tab>The ship to company line needs the company name that should be used for shipping.'};
			 if(trim(document.getElementById('order_ship_line3_input').value)=="Street address"){errmsg=errmsg+'<br><br><tab>The ship to street line needs the street address for shipping.'};
			 if(trim(document.getElementById('order_ship_line4_input').value)=="City, State, ZIP"){errmsg=errmsg+'<br><br><tab>The ship to city/st/zip line needs to be replaced with the shipping city/state and zip.'};
	      
        }
        
		
		if (trim(errmsg) != "") {
			
			errmsg="<b>The following problems exist with your instructions:</b>"+errmsg+'<br><br><B>Please correct these issues and then click the submit button.</B>';
            blAlert({ title: 'Order Validation: ', text: errmsg });
		    return null;
	    } 
	    
	   	    
	    cvAddVal('email', $('#order_emailto_input').val());
		cvAddVal('head_email', $('#order_emailto_input').val());
		
		var addToInstr="N";
		
		if(document.getElementById('order_output_type_1').checked == true ){
		  
		  //cd data
		  if(document.getElementById('order_data_file_1').checked == true ){
			cvAddVal('file_output', "CSV File CD");
			
	      } else if(document.getElementById('order_data_file_2').checked == true ){
	     	cvAddVal('file_output', "Text Delimited CD");
	      } else {
	     	cvAddVal('file_output', "Tab Format CD");
	      } 
	      
	      addToInstr="Y";
	      //we do not have dbf right now
	       
        } else if(document.getElementById('order_output_type_2').checked == true ){
		 
		  //cd data
		  if(document.getElementById('order_data_file_1').checked == true ){
			cvAddVal('file_output', "CSV File Email");
	      } else if(document.getElementById('order_data_file_2').checked == true ){
	     	cvAddVal('file_output', "Text Delimited Email");
	      } else {
	     	cvAddVal('file_output', "Tab Format Email");
	      } 
	      
	      //we do not have dbf right now
		 
     	} else {
	        //labels
	        if(document.getElementById('order_label_type_1').checked == true ){
		   	  cvAddVal('file_output', "Cheshire Labels 4up");
	        } else if(document.getElementById('order_label_type_2').checked == true ){
	          cvAddVal('file_output', "4-Up PS Labels");
	        } else {
	     	  cvAddVal('file_output', "1-Up PS Labels");	
	        } 
	        addToInstr="Y";
        } 
	     
        //make the job the same
        cvAddVal('head_ship_type', CV.file_output);
        
    
        
		cvAddVal('po_number', $('#order_po_input').val());
		cvAddVal('description', $('#order_description_input').val());
		cvAddVal('user_submit', $('#order_submitter_input').val());
		
		//job ones as well
		cvAddVal('head_po', $('#order_po_input').val());
		cvAddVal('head_descr', $('#order_description_input').val());
		cvAddVal('head_submit', $('#order_submitter_input').val());
		
		
		
		var minstr=$('#order_instructions_textarea').val();
		
		if (addToInstr=="Y"){
			
			if(document.getElementById('order_shiptype_1').checked == true ){
			
			   minstr=minstr + "Customer Ordered "+ CV.file_output + "\n\n";
			   minstr=minstr + "Shipping Information entered by customer:"+ "\n";
			   minstr=minstr + "\n" +$('#order_ship_line1_input').val(); 
			   minstr=minstr + "\n" +$('#order_ship_line2_input').val(); 
			   minstr=minstr + "\n" +$('#order_ship_line3_input').val(); 
			   minstr=minstr + "\n" +$('#order_ship_line4_input').val(); 
		    
			} else {
			   minstr=minstr + "Customer Ordered "+ CV.file_output + "\n\n"; 
			   minstr=minstr + "***Customer will pickup order at CIS\n\n"; 
			        
		    }    
		
	    }
		
		cvAddVal('special_instructions', minstr);
		cvAddVal('head_notes', minstr);
		
		
		var mcombine = "N";
	    if (document.getElementById("order_combine_segments").checked){
		  mcombine = "Y";
        }
        		
		cvAddVal('combineseg', mcombine);       
		cvAddVal('head_combine', mcombine); 
		
		
		
		//grayOut(true);  
	    document.getElementById('plswaitSubmit').style.display = 'block';
	    iInfo	= {
			cID: CV.custid,
			job: CV.theheader,
			description:$('#order_description_input').val(),		
			special_instructions: minstr,		
			file_output: CV.file_output,		
			po_number:	$('#order_po_input').val(),		
			user_submit: CV.user_submit,	
			table: "NOT USED",
			payment_type: "BILL ACCOUNT",
		    combinesegs: mcombine,
		    theemail: $('#order_emailto_input').val(),
		    thecompany: $('#companylogged').val()     	            
		},
               	
		$.post('include/php/postSubmitInfo.php', iInfo, function(data) {
				
			//grayOut(false);
			document.getElementById('plswaitSubmit').style.display = 'none';
			var strErr=data.theErr;
		    strErr = jQuery.trim(strErr);
		
		    if (strErr !=''){
			  blAlert({ title: 'Error ordering the job: ', text: strErr });
		    } else {
			    //blAlert({ title: 'Thank you!', text: 'The job # ' + CV.theheader + ' has been ordered.' }); 
		  	    $('#order_submit_dialog').dialog('close');
		  	    
		  	    //add data.return to final dialog
		  	    //hide all of these and then show relevent ones after inv calc
		  	    document.getElementById('payment_type_1').style.display = 'none'; 
	            document.getElementById('payment_type_2').style.display = 'none';
	            document.getElementById('payment_type_3').style.display = 'none'; 
                document.getElementById('payment_type_input_3').checked = false; 
                document.getElementById('invoice_cc_div').style.display = 'none';
                document.getElementById('not_final_div').style.display = 'none'; 
		  	    
		  	    
		  	    openCheckoutWindow();
		  	    
		  	    
		    } 
		    
		    
		}, 'json');
		
				
		
		
	    	
	}
	
	
	function cancelSubmit() {
	
		$('#order_submit_dialog').dialog('close');
		
    }	
		
    function closeOrdInfo() {
	
		$('#OrderCntInfo_dialog').dialog('close');
		
    }	
    
    
    function closeCheckout() {
	
		$('#order_invoice_dialog').dialog('close');
		
    }	
    
	// Add items to the sidebar
	// @param	elem	jQuery or object (cv, data, text, group)
	function vIE(){return (navigator.appName=='Microsoft Internet Explorer')?parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]):'Nav';}

	function greyoutTotals(toggle){
		
	//clear the totals so they have to update count
	var thebrowser=vIE();
	  //CV.hasbeenupdated='N';
	  if (document.getElementById('count_records')){
		  if (toggle=='T'){
		      document.getElementById('count_records').style.font="bold 20px arial,helvetica";
		      
		     
		      if (thebrowser ==8){
		        document.getElementById('count_records').style.color="grey";
	          } else {
		        obj = document.getElementById("count_records");
                obj.style.backgroundColor = "#ffffff";
                obj.style.color = "#eee";
  
	          }     
		      document.getElementById('count_amt').style.font="bold 20px arial,helvetica";
		      if (thebrowser ==8){
		        document.getElementById('count_amt').style.color="grey";
	          } else {
		        obj = document.getElementById("count_amt");
                obj.style.backgroundColor = "#ffffff";
                obj.style.color = "#eee";
  
	          }     
	      } else {
		      document.getElementById('count_records').style.font="bold 20px arial,helvetica";
		      if (thebrowser ==8){
		        document.getElementById('count_records').style.color="black";
	          } else {
		        obj = document.getElementById("count_records");
                obj.style.backgroundColor = "#ffffff";
                obj.style.color = "#eee";
  
	          }     
		      document.getElementById('count_amt').style.font="bold 20px arial,helvetica";
		      if (thebrowser ==8){
		        document.getElementById('count_amt').style.color="black";
	          } else {
		        obj = document.getElementById("count_amt");
                obj.style.backgroundColor = "#ffffff";
                obj.style.color = "#eee";
  
	          }     
	      }       
      }
		
		
    }
	
	function sidebarAdd(elem) {
		var group, text, elemArr = [];
		greyoutTotals('T')
		
		function constructLI(val) {
			text = elem.text || val;
			return $('#selection-' + val).length ? '' : '<li data-cv="\'' + elem.cv + '\'" class="selection" data-text="\'' + elem.text + '\'" id="selection-' + val + '">' + crossImg + '<span>' + text + '</span></li>'; // Don't add duplicates
		}
		
		function constructLInoX(val) {
			text = elem.text || val;
			return $('#selection-' + val).length ? '' : '<li data-cv="\'' + elem.cv + '\'" class="selection" id="selection-' + val + '"><span>' + text + '</span></li>'; // Don't add duplicates
		}
		
		if (elem instanceof jQuery) {
			
			elem.each(function() {
				
				var	self	= $(this),
					val		= self.is('input') ? self.val() : self.attr('id'),
					cv		= self.attr('name') || self.metadata().cv;
				
				function text() {
					switch (cv) {
						case 'city':
							return val.substring(2) + ', ' + val.substring(0, 2);
						case 'county':
						case 'metro':
							return self.parent().text();
						default:
							return val;
					}
				}
					
				group	= $('#selection-' + cv).find('ul');
			
				if (self.is('.multiSelect input') && $('#selection-' + val).length === 0) {
					elemArr.push('<li data-cv="\'' + cv + '\'" class="selection" id="selection-' + val + '">' + crossImg + '<span>' + text() + '</span></li>');
				} 	
				
			});
			
			group.append(elemArr.join('')).find('li').tsort();
			
		} else if (typeof(elem) === 'object') {
			
			if (elem.cv=='city'){
		      //alert(elem.text+" 2410")
	        }		
	        
	        	
			//scw added check for not add the x for removing the item - these should be checked and unchecked under tab not removed from CV object
			var fieldchk=elem.cv.substring(0,3); //will catch all extra fields
			
			//took out the 'fieldchk=="rec"' so x would appear
			if (elem.cv=="thepkg" || elem.cv=="onetimeuse" || elem.cv=="Zzip4_only" || elem.cv=="Zexecutive" || elem.cv=="Zcontact_only"){	
			  group = elem.group || $('#selection-' + elem.cv);
			  group.find('ul').append(elem.hasOwnProperty('data') ? _(elem.data).map(constructLInoX).join('') : constructLInoX(elem.cv));
		  	  //added this for the additional criteria with no x
		    } else if (elem.cv=="Zjob_cutoff" || elem.cv=="Zemployee_low" || elem.cv=="Zemployee_high" || elem.cv=="Zemployee_range" || elem.cv=="Zsales_low" || elem.cv=="Zsales_high" || elem.cv=="Zsales_range" || elem.cv=="Zlocation_type" || elem.cv=="Zgender" || elem.cv=="Zpub_priv" ){
			  group = elem.group || $('#selection-' + elem.cv);
			  group.find('ul').append(elem.hasOwnProperty('data') ? _(elem.data).map(constructLInoX).join('') : constructLInoX(elem.cv));

		    } else if (elem.cv=="radius" ){
			  
			  strChk = jQuery.trim(elem.text);
		
		      if (strChk !=''){
			     group = $('#selection-radius');
			     group.find('ul').append(constructLI(elem));
		      }
		      
  		    } else if (elem.cv=="city" ){
			  //alert(elem.text);
			  strChk = jQuery.trim(elem.text);
		      strChk=strChk.substring(2)+' '+strChk.substring(0,1);
		      if (strChk !=''){
			     group = $('#selection-city');
			     group.find('ul').append(constructLI(elem));
		      }
		      
  		    } else {
			    
			  group = elem.group || $('#selection-' + elem.cv);
			  group.find('ul').append(elem.hasOwnProperty('data') ? _(elem.data).map(constructLI).join('') : constructLI(elem.cv));
		     			  
		    }
		}
	}
	
	// Remove items from the sidebar
	// @param	elem	jQuery
	function sidebarRemove(elem) {
		greyoutTotals('T')
		//alert(elem.attr('data-cv')+" line #3262 bl.js");
		
		
		elem.each(function() {
			var self = $(this);
					
			if (self.is('.selectionGroup li')) {
				
				var thetitle=self.attr('id');
			    var stgpos=thetitle.indexOf('-', 0)+1;
			    thetitle=thetitle.substring(stgpos);
			    
			    //alert(thetitle.substring(0,3));
			    if (elem.attr('data-cv')=="'radius'"){
				   CV['radiusCentroid']=" ";
				   CV['qcrtadd']=" "; 
				   CV['qcrtcity']=" "; 
				   CV['qcrtzip']=" "; 
				   CV['qradlimit']=" "; 
  
				   clearRadiusInputs();	      
			    } 
			      
			     //alert(thetitle.substring(0,3));
			    if (elem.attr('data-cv')=="'county'"){
				    
				   var lbltoremove= elem.attr('data-txt');	
 
				   lbltoremove =self.attr('id');
				   lbltoremove = lbltoremove.replace(/,/g,";");
				   lbltoremove = lbltoremove.replace(/selection-/g," ");
				   
				   			   
                   for ( var i=0, len=CV['county'].length; i < len; ++i ){
	                    
					  if (jQuery.trim(CV['county'][i]) === jQuery.trim(lbltoremove)){ 
						  
                           var thepos=i;		  
					  }
					  
			       }
			       
			       //alert(thepos+"");	  
			       
			       CV['county'].splice(thepos,1);
			      
			       
			       var chkboxtouncheck =jQuery.trim(lbltoremove);
			       
			       var chkElement = document.getElementById('county-'+chkboxtouncheck);
			       
                   if (chkElement != null) {
                 	   eval("document.getElementById('county-"+chkboxtouncheck+"').checked = false");      
                   }	
                   
                      
			    }   
			   
			      //alert(thetitle.substring(0,3));
			    if (elem.attr('data-cv')=="'metro'"){
				    
				   var lbltoremove= elem.attr('data-txt');	

				   lbltoremove =self.attr('id');
				   lbltoremove = lbltoremove.replace(/,/g,";");
				   lbltoremove = lbltoremove.replace(/selection-/g," ");
				   
				   			   
                   for ( var i=0, len=CV['metro'].length; i < len; ++i ){
	                    
					  if (jQuery.trim(CV['metro'][i]) === jQuery.trim(lbltoremove)){ 
						  
                           var thepos=i;		  
					  }
					  
			       }
			       
			       //alert(thepos+"");	  
			       
			       CV['metro'].splice(thepos,1);
			      
			       
			      var chkboxtouncheck =jQuery.trim(lbltoremove);
			       
			       var chkElement = document.getElementById('metro-'+chkboxtouncheck);
			       
                   if (chkElement != null) {
                 	   eval("document.getElementById('metro-"+chkboxtouncheck+"').checked = false");      
                   }	
                   
                      
			    }   
			    
			    if (elem.attr('data-cv')=="'zip4_only'"){
			        document.getElementById('options_includes_input_1').checked = false;
			        cvAddVal('zip4_check', 'F'); 
			        //something is blocking this toggleing the array value off-- no time to fools with tacked in a secondary value and moved on- if its set to F the php file will toggle the zip4 off
			        CV.zip4_only='F';
		        } 
		        
		        if (elem.attr('data-cv')=="'executive'"){
			        document.getElementById('options_includes_input_2').checked = false;
			        CV['executive']='F';
		        }
		        
		        if (elem.attr('data-cv')=="'contact_only'"){
			        document.getElementById('options_includes_input_3').checked = false;
			        CV['contact_only']='F';
		        }
		        
			    if (elem.attr('data-cv')=="'job_cutoff'"){
			        $('#cutoff_input').val('0');
			        CV['job_cutoff']='0';
		        }
		        
		        if (elem.attr('data-cv')=="'employee_low'"){
			        $('#employee_low_input').val('0');
			        CV['employee_low']='0';
		        }
		        
		        if (elem.attr('data-cv')=="'employee_high'"){
			        $('#employee_high_input').val('0');
			        CV['employee_high']='0';
		        }
		       
		         if (elem.attr('data-cv')=="'employee_range'"){
			        document.getElementById('employee_range_select').selectedIndex=0;
			        CV['employee_range']='Z';
		        }
		        
		        if (elem.attr('data-cv')=="'sales_low'"){
			        $('#sales_low_input').val('0');
			        CV['sales_low']='0';
		        }
		        
		        if (elem.attr('data-cv')=="'sales_high'"){
			        $('#sales_high_input').val('0');
			        CV['sales_high']='0';
		        }
		       
		        if (elem.attr('data-cv')=="'sales_range'"){
			        document.getElementById('sales_range_select').selectedIndex=0;
			        CV['sales_range']='Z';
		        }
		        
		        if (elem.attr('data-cv')=="'location_type'"){
			        document.getElementById('location_type_select').selectedIndex=0;
			        CV['location_type']=' ';
		        }
		        
		        if (elem.attr('data-cv')=="'gender'"){
			        document.getElementById('gender_select').selectedIndex=0;
			        CV['gender']=' ';
		        }
		        
		        if (elem.attr('data-cv')=="'pub_priv'"){
			        document.getElementById('pub_priv_select').selectedIndex=0;
			        CV['pub_pri']=' ';
		        }
		        		        
		        
			    if (elem.attr('data-cv')=="'sic'"){
				   // alert(self.attr('id'));
				   var lbltoremove= elem.attr('data-txt');	

				   lbltoremove =self.attr('id');
				   lbltoremove = lbltoremove.replace(/,/g,";");
				   lbltoremove = lbltoremove.replace(/selection-/g," ");
				   
				   			   
                   for ( var i=0, len=CV['metro'].length; i < len; ++i ){
	                    
					  if (jQuery.trim(CV['metro'][i]) === jQuery.trim(lbltoremove)){ 
						  
                           var thepos=i;		  
					  }
					  
			       }
			       
			       //alert(thepos+"");	  
			       
			       CV['metro'].splice(thepos,1);
			      
			       
			      var chkboxtouncheck =jQuery.trim(lbltoremove);
			      
			      
			      //uncheck 2 digit boxes 
			      var chkElement = document.getElementById('sic_tree'+chkboxtouncheck+'_input');
			      if (chkElement != null) {
                 	   eval("document.getElementById('sic_tree"+chkboxtouncheck+"_input').checked = false");      
                  }
                   
                   //uncheck 4 digit boxes 
			      var chkElement = document.getElementById('sic_4tree'+chkboxtouncheck+'_input');
			      if (chkElement != null) {
                 	   eval("document.getElementById('sic_4tree"+chkboxtouncheck+"_input').checked = false");      
                  } 
                    
			      var chkElement = document.getElementById('sic_6tree'+chkboxtouncheck+'_input');
			      if (chkElement != null) {
                 	   eval("document.getElementById('sic_6tree"+chkboxtouncheck+"_input').checked = false");      
                  }  
			      
             
                  //the exact & related boxes
                   //uncheck 2 digit boxes 
			      var chkElement = document.getElementById('sic_exact'+chkboxtouncheck);
			      if (chkElement != null) {
                 	   eval("document.getElementById('sic_exact"+chkboxtouncheck+"').checked = false");      
                  }
                   
                  
			      var chkElement = document.getElementById('sic_related'+chkboxtouncheck);
			      if (chkElement != null) {
                 	   eval("document.getElementById('sic_related"+chkboxtouncheck+"').checked = false");      
                  } 

                      
			    }   
			    
			    if (elem.attr('data-cv')=="'city'"){
				    
				   var lbltoremove= elem.attr('data-text');
				   var mlen=lbltoremove.length;
				    
				   lbltoremove = lbltoremove.substring(1,(mlen-1));
				   mlen=lbltoremove.length;
				   lbltoremove = lbltoremove.substring((mlen-2))+lbltoremove.substring(0,(mlen-5));
				   
				   //alert(lbltoremove);
				  
                   for ( var i=0, len= CV['city'].length; i < len; ++i ){
					  if (CV['city'][i] == lbltoremove){ 
                           var thepos=i;		  
					  }
			       }
			       
			       //alert(thepos+"");	  
			       
			       CV['city'].splice(thepos,1);
			       
			       var chkElement = document.getElementById('city-'+lbltoremove);
                   if (chkElement != null) {
                 	   eval("document.getElementById('city-"+lbltoremove+"').checked = false");      
                   }	   
			    }   
			    
			    
			    
		        
			    var fieldchk=thetitle.substring(0,3);
			    if (fieldchk=="rec"){
				 //alert(thetitle);
				 CV[thetitle] = 'F';
				 eval("document.getElementById('"+thetitle+"_input').checked = false");
				 
				   if (thetitle=='recCONTACT'){
					  CV['recCEO_1ST_NM']="F" 
					  CV['recCEO_LST_NM']="F"; 
					  CV['recDDM_TITLE']="F"; 
					  CV['recCONTACT']="F";
			       }
			       
			       if (thetitle=='recSALES_VOL'){
				      CV['recSALES_VOL']="F";  
                      CV['recSALES_VOL_CD']="F"; 
			       }    
				       
				   if (thetitle=='recEMPL_TOTAL'){
				       CV['recEMPL_TOTAL']="F";  
					   CV['recEMPL_TOT_CD']="F"; 
                   }   
                   			       	 
			    }    
			    
			    
			         
			         //loop over jobtitle checkboxes  
       				 var y=1;  
       				  while (y < 36) {
	       			     if (eval("$(\"#jobtitle_input_"+y+"\").val()")==thetitle){ 
       				       eval("document.getElementById('jobtitle_input_"+y+"').checked = false");
   					     }
       				     y=(y+1);
   					  } //end of for loop
   					 				
				
				self.remove();
				$('.multiSelect:visible', document.getElementById('accordion-1')).find('input[value="' + elem.attr('id') + '"]').removeAttr('checked');
			} else if (self.is('.multiSelect input')) {
				
				$('#selection-' + self.val()).remove();
			} else {
				
				$('#selection-' + self.attr('name')).remove();
			}
		});
	}
	
	// Set sidebar items based on the values in the CV object
	function sidebarSet() {
		var selArr = [];
		
		$('ul', document.getElementById('accordion-sidebar')).empty(); // Reset sidebar
		
		_(CV).each(function(val, key) {
			//alert(val+"  "+key+" line #2114--- this will pop up 84 times");
			switch(key) {
				
				case 'exclude_sic': case 'exclude_zip':
				    //alert(val+"  "+key+" line #2118");
					if (val.length) {
						selArr.push({
							container:	$('#selection-' + key),
							selections:	_(val).map(function(val1) { return { cv: key, id: val1, img: true, txt: val1 }; })
						});	
					}
					break
				
				
				case 'onetimeuse':
				  if (CV['thepkg'] !='F') {
				
					  if (val === 'T') {
				         eval("sidebarAdd({ cv: 'onetimeuse', group: $('#selection-use'), text: $('input[id=\"onetimeuse_input_1\"]').next('label').text() })");
			          } else {
				         eval("sidebarAdd({ cv: 'onetimeuse', group: $('#selection-use'), text: $('input[id=\"onetimeuse_input_2\"]').next('label').text() })");
			          }    
			      }
					break
				
				//scw added these for field checkboxes
				case 'thepkg':  
				   //alert(val+"  "+key+" line #2140");
				   if (val === 'B') {
					 eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-package'), text: $('input[id=\""+key+"_input_1\"]').next('label').text() })");
				   }
				   
				   if (val === 'F') {
					 eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-package'), text: $('input[id=\""+key+"_input_2\"]').next('label').text() })");					 
				   }
				   
				   
				   break;	
								
				case 'recYR_STARTED': case 'recSUBSID_IND': case 'recPUB_PRIVATE': case 'recSALES_VOL': case 'recEMPL_TOTAL': case 'recCONTACT': case 'recTELEPHONE': case 'recFRAN_CODE':
				   
				   if (val === 'T') {
					 eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-fields'), text: $('input[id=\""+key+"_input\"]').next('label').text() })");
				   }
				   
				   break;	
				case 'radiusCentroid':
				   break;
				   
				case 'radius':
				  //alert(CV['radius']);
				  //alert(val);
				  
				  var newval=val;
				  
				  var aPosition = newval.indexOf('CENTROID OF');

		        
				  if (aPosition > -1){
					newval=$('#radius_distance_input').val()+' MILE RADIUS AROUND '+$('#radius_zip_input').val();
   		          }   else {			  
				    newval=newval.replace('MILE(S) FROM','MILE RADIUS AROUND<table><tr><td></td></tr></table>');
				    newval=newval.replace('ZIP','<table><tr><td></td></tr></table>'+$('#radius_city_input').val().toUpperCase()+','+$('#radius_state_select').val().toUpperCase());
			      }
				  
			      //catch all if input left out				  
				  newval=newval.replace('MILE(S) FROM CENTROID OF','MILE RADIUS AROUND');
				  //alert(newval);
				  eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-radius'), text: '"+newval+"' })")
				  break;
				  	
				case 'city':
				
				    for ( var i=0, len= val.length; i < len; ++i ){
					   //alert(val[i]); 
                       eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-city'), text: '"+val[i].substring(2)+', '+val[i].substring(0,2)+"' })")
                    }
				
				   
					break;  
				  
				case 'zip': case 'crid': case 'county': case 'metro': case 'state': case 'acode': case 'sic': case 'jobtitle': 
					if (val.length) {
						selArr.push({
							container:	$('#selection-' + key),
							selections:	_(val).map(function(val1) { if (key=='county' || key=='metro'){val1=val1.replace(/;/g,",")}; return { cv: key, id: val1, img: true, txt: val1 }; })
						});	
					}
					break;
				
				case 'zip4_only': 
			
					if (val === 'T') {
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'Include only records with zip+4' })");
					}
					break;
				case 'executive': 
				
					if (val === 'T') {
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'Include only records with contacts' })");
						
					}
					break;
				case 'contact_only': 
				
					if (val === 'T') {
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'Include a record for each contact at the company' })");
					} 
					break;
					//add in the addtional ones that do not have an x or directly correlated to cv object text
				case 'job_cutoff':
					if (val > 0) {
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'Count restricted to "+val+" records or less' })");			
					}
					break;
				case 'employee_low':
					if (val > 0) {
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'More than "+val+" employees' })");
					}
					break;
				case 'employee_high':
					if (val > 0) {
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'Less than "+val+" employees' })");
					}
					break;
					
				case 'employee_range':
				   
                    var rangeTitle="";  
					if (val=="A"){ rangeTitle ='1 - 4' }; 
					if (val=="B"){ rangeTitle ='5 - 9' }; 
					if (val=="C"){ rangeTitle ='10 - 19' };  
					if (val=="D"){ rangeTitle ='20 - 49' }; 
					if (val=="E"){ rangeTitle ='50 - 99' }; 
					if (val=="F"){ rangeTitle ='100 - 249' }; 
					if (val=="G"){ rangeTitle ='250 - 499' }; 
					if (val=="H"){ rangeTitle ='500 - 999' }; 
					if (val=="I"){ rangeTitle ='1000 - 4999' }; 
					if (val=="J"){ rangeTitle ='5000 - 9999' }; 
					if (val=="K"){ rangeTitle ='10000 and up' }; 

				
					if (rangeTitle != "") {
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'Employees "+rangeTitle+"' })");
					}
					
					break;
				case 'sales_low':
					if (val > 0) {
						var mconv=parseInt(val*1000);
						mconv=addCommas(mconv);
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'Sales over $"+mconv+"' })");
					}
					break;
				case 'sales_high':
					if (val > 0) {
						var mconv=parseInt(val*1000);
						mconv=addCommas(mconv);
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'Sales less than $"+mconv+"' })");
					}
					break;
				case 'sales_range':
				    var rangeTitle=""; 
					if (val=="A"){ rangeTitle ='Less than $500,000' };
					if (val=="B"){ rangeTitle ='$500,00 - $1 million' };
					if (val=="C"){ rangeTitle ='$1 - $2.5 million' };
					if (val=="D"){ rangeTitle ='$2.5 - $5 million' };
					if (val=="E"){ rangeTitle ='$5 - $10 million' };
					if (val=="F"){ rangeTitle ='$10 - $20 million' };
					if (val=="G"){ rangeTitle ='$20 - $50 million' };
					if (val=="H"){ rangeTitle ='$50 - $100 million' };
					if (val=="I"){ rangeTitle ='$100 - $500 million' };
					if (val=="J"){ rangeTitle ='$500 million - $1 billion' };
					if (val=="K"){ rangeTitle ='$1 billion and up' };

					if (rangeTitle != "") {
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'Sales "+rangeTitle+"' })");
					}
					break;
				case 'location_type':
				
				    var selTitle=""; 
					if (val=="1"){ selTitle ='Corporate HQ' };
					if (val=="2"){ selTitle ='Branch Location' };
					if (val=="3"){ selTitle ='Subsidiary of HQ' };		  
											
					if (selTitle != "") {
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'Location Type: "+selTitle+"' })");
					}
					break;
				case 'gender':
					var selTitle=""; 
					if (val=="M"){ selTitle ='Male' };
					if (val=="F"){ selTitle ='Female' };
									
					if (selTitle != "") {
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'Contact Gender: "+selTitle+"' })");
					}
					break;
				case 'pub_priv':	
				    var selTitle=""; 
					if (val=="1"){ selTitle ='Public' };
					if (val=="0"){ selTitle ='Private' };
									
					if (selTitle != "") {
						eval("sidebarAdd({ cv: '"+key+"', group: $('#selection-additional'), text: 'Corp Status : "+selTitle+"' })");
					}
					break;			
										
					
			}
		});
		
	    
		// Add elements to sidebar
		_(selArr).each(function(val) {
			//alert('in here');
			val.container.find('ul').html(_(val.selections).map(function(val1) {
				return '<li data-cv="\'' + val1.cv + '\'" class="selection" id="selection-' + val1.id + '">' + (val1.img ? crossImg : '') + '<span>' + val1.txt + '</span></li>';
			}).join(''));
		});
		
		 
		
	}
	
	// Returns the customer info for the login
	function getCustInfo(o) {
			
    // the login is using this function to go to CC and logging in the customer and setting the ID, name and session & reloading the page
    // then on reload index.php is checking to see if session is in place and if it is using the API to get the prices & placing them in hidden inputs
    // page load is then using the hidden inputs to define the BL object as well as the page price labels and avoids having the prices 
    //in global session vars or cookies- these are just for reference and the order is actually priced from data- no worries about injection etc...
	  
	  
  	  //grayOut(true);
	  document.getElementById('plswait').style.display = 'block';
  	  	cInfo	= {
			cID:	'', 
			lName:	$('#username_input').val(),  
			pWord:	$('#password_input').val(),
			remaddr: $('#remaddr').val(),
	        remhost: $('#remhost').val(), 
	        remhttp: $('#remhttp').val(),
	        rembrow: $('#rembrow').val(),
	        thejob: CV.thejob, 
		    theheader: CV.theheader        	            
		},
        
        		
		$.post('include/php/loginOnlyAPI.php', cInfo, function(data) {
					
			//grayOut(false);
			document.getElementById('plswait').style.display = 'none';
									
			var strErr=data.strErr;
		    strErr = jQuery.trim(strErr);
		    
		    var id=data.cID;
		    var conm=data.company;
		    var jbno=data.Jobno;
		    var header=data.Headerno;
		
		    if (strErr !=''){
			   blAlert({ title: 'Error logging in: ', text: strErr });
		    } else {
			   
			   if (id !='CIS001'){
		    	   var loginhtml = "<span><a href=\"http://www.compactlists.com?business\">Home</a> | <a href=\"http://www.residentlists.com\">Resident Lists</a> | <a href=\"https://www.consumerlists.com\">Consumer Lists</a> | <span class=\"topElement\" id=\"logoutElement\"> Logged in as <strong>" + data.company + "</strong> | <a class=\"contact_us\" href=\"#\">Contact Us</a> | <a href=\"#\" id=\"logout_link\">Log out</a></span>";
	    	   } else {
		    	   var loginhtml = "<span><a href=\"http://www.compactlists.com?business\">Home</a> | <a href=\"http://www.residentlists.com\">Resident Lists</a> | <a href=\"https://www.consumerlists.com\">Consumer Lists</a> | <a href=\"http://12.46.52.149/blphp/indexadmin.php\">Admin</a> | <a class=\"contact_us\" href=\"#\">Contact Us</a> | <a href=\"#\" id=\"logout_link\">Log out</a></span>";
	    	   }	  
			 
	    	 
			     //var loginhtml = "<span><a href=\"http://www.compactlists.com?business\">Home</a> | <a href=\"http://www.residentlists.com\">Resident Listsxxxx</a> | <a href=\"https://www.consumerlists.com\">Consumer Lists</a> | <span class=\"topElement\" id=\"logoutElement\"> Logged in asz <strong>" + data.company + "</strong> | <a class=\"contact_us\" href=\"#\">Contact Us</a> | <a href=\"#\" id=\"logout_link\">Log out</a></span>";
			   $('#aNav').html(loginhtml);
			   //location.reload();
			   //alert(document.getElementById('serveradd').value);
			   //alert(document.getElementById('apacheadd').value);
			    var theserveradd=document.getElementById('remhost').value;
		        if (theserveradd=='localhost' || theserveradd=='12.46.52.206' || theserveradd=='12.46.52.149'){
			        theserveradd=theserveradd+'/bl';
		        }    		   
			   	
		        if (document.getElementById('isSSL').value==='T'){
			        theserveradd="https://"+theserveradd;
		        } else {
			        theserveradd="http://"+theserveradd;    
		        }  
		        
		        	   
               window.location =theserveradd+"/index.php?theid="+id+"&conm="+conm+"&jbno="+jbno+"&header="+header;

		    } 
		    
		    
		}, 'json');
	}
	
	
	function loadbldef(o){
		
	    // the login is going to CC and loging in the customer and setting the ID, name and session & reloading
	    // the index.php is checking to see if session is in place and if it is using the API to get the prices & placing them in hidden inputs
	    // page load is then using the hidden inputs to define the BL object
	   
	    // this makes the page price labels work well and avoids having the prices in global session vars or cookies
	    //THIS IS THE COMPLETE BL PRICING ALTHOUGH ONLY A DOZEN ARE USED- REVIEW DROPPING REST	 
		blAddVal('cID', $('#companyID').val());		// customer id
		cvAddVal('custid', $('#companyID').val());
		cvAddVal('thejob', $('#thejob').val());
		cvAddVal('theheader', $('#theheader').val());
		blAddVal('CISsessionID', $('#CISsessionID').val());	// future use for CIS session ID
		blAddVal('okamttobill', $('#okamttobill').val());	// max amt to bill in 24 hours
		blAddVal('okamttrigger', $('#okamttrigger').val()); // max amount in 24 hours
		blAddVal('okvoltrigger', $('#okvoltrigger').val());  // max number of records in 24 hours
		blAddVal('oknumorderstrigger', $('#oknumorderstrigger').val());	// max number of orders 24 hours
		blAddVal('pkg1_single', $('#pkg1_single').val());	// basic per thousand package- single use
		blAddVal('pkg1_yr', $('#pkg1_yr').val());	// basic per thousand package with one year multi-use
		blAddVal('pkg2_yr', $('#pkg2_yr').val());	// full contact package - one year multi-use part of price
		blAddVal('min_order', $('#min_order').val());	// minimume order charge 
		blAddVal('oneuplblprice', $('#oneuplblprice').val());	// one up label charge per thousand
		blAddVal('fouruplblprice', $('#fouruplblprice').val());	// four up label charge per thousand
		blAddVal('cdprice', $('#cdprice').val());			// price of delivering on CD
		blAddVal('diskprice', $('#diskprice').val());			// price of buring to disk
		blAddVal('seq10price', $('#seq10price').val());		// per segment price up to 10--- not charging 
		blAddVal('seq11price', $('#seq11price').val());		// per segment price for 11+---not charging 
		blAddVal('uspdiskprice', $('#uspdiskprice').val());	// handling for USP disk price 
		blAddVal('usplblprice', $('#usplblprice').val());	// handling for USP label
		blAddVal('itememptotprice', $('#itememptotprice').val());	 // extra charge /m for adding employee fields to package
		blAddVal('itemsiteprice', $('#itemsiteprice').val());		 // extra charge /m for adding site type field to package
		blAddVal('itemfranprice', $('#itemfranprice').val());		 // extra charge /m for adding fran code field to package
		blAddVal('itemyrprice', $('#itemyrprice').val());		     // extra charge /m for adding year started field to package
		blAddVal('itemsalesprice', $('#itemsalesprice').val());	 // extra charge /m for adding sales volume fields to package
		blAddVal('itemteleprice', $('#itemteleprice').val());		 // extra charge /m for adding telephone field to package
		blAddVal('itemcontactprice', $('#itemcontactprice').val()); // extra charge /m for adding contact fields to package
		blAddVal('itempubprivateprice', $('#itempubprivateprice').val()); // extra charge /m for adding PUB/PRIVATE field to package
		blAddVal('cheshirelblprice', $('#cheshirelblprice').val()); // cheshire label charge per thousand
		blAddVal('p1Sd1v', $('#p1Sd1v').val()); // pkg 1 single run 1st level record count to qualify for discount
		blAddVal('p1Sd1a', $('#p1Sd1a').val()); // price per thousand for this discount
		blAddVal('p1Sd2v', $('#p1Sd2v').val()); // pkg 1 single run 2nd level record count to qualify for discount
		blAddVal('p1Sd2a', $('#p1Sd2a').val()); // price per thousand for this discount
		blAddVal('p1Yd1v', $('#p1Yd1v').val()); // pkg 1 one year use 1st level record count to qualify for discount
		blAddVal('p1Yd1a', $('#p1Yd1a').val()); // price per thousand for this discount
		blAddVal('p1Yd2v', $('#p1Yd2v').val()); // pkg 1 one year use 2nd level record count to qualify for discount
		blAddVal('p1Yd2a', $('#p1Yd2a').val()); // price per thousand for this discount
		blAddVal('p2Yd1v', $('#p2Yd1v').val()); // pkg 1 single run 1st level record count to qualify for discount
		blAddVal('p2Yd1a', $('#p2Yd1a').val()); // price per thousand for this discount
		blAddVal('p2Yd2v', $('#p2Yd2v').val()); // pkg 1 single run 2nd level record count to qualify for discount
		blAddVal('p2Yd2a', $('#p2Yd2a').val()); // price per thousand for this discount
	 
	  return;
	 
	
    }
	
	// added this funtion to update customer info 
	function blAddVal(elem, val) {
		
		if (elem instanceof jQuery) {
			elem.each(function() {
				var self	= $(this),
					selfVal	= self.val(),
					blVal	= self.attr('name') || self.metadata().bl,
					eVal	= (selfVal && selfVal !== 'on') ? self.val() : self.metadata().val;
				
				blAddVal(blVal, eVal);
			});
		} else if (typeof(elem) === 'object') { // Overwrite specific bl variables with provided key value pairs in elem object
			_(elem).each(function(v, k) {
				blAddVal(k, v);
			});
		} else if (_.isString(elem) && BL.hasOwnProperty(elem) && typeof(val) !== 'undefined') { // Add specific named bl variable
			if (_.isArray(BL[elem]) && !_(BL[elem]).include(val)) {
				if (_.isArray(val)) {
					BL[elem] = _(BL[elem].concat(val).sort()).uniq(true);
				} else if (_.isString(val)) {
					BL[elem].push(val);	
				}
			} else if (!_.isArray(val)){
				BL[elem] = val;
			}
			
			log('blAddVal: ' + (BL[elem] === val || _(BL[elem]).include(val)));
		}
	}//this is the function to add to custinfo
		
	function sortOpenOrders(){
	
	//This was a single function for open and submitted/ fired wrong and blank po #'s caused this sort to break and drop the records with the blanks
	//need to research but we are posting soon so hacked it together with a value 'none' for empty ones and split it oput to two functions.
	 
	//the number of submitted orders
	var subSize=0;
	var sortby=0;
	var Desc_ASC=-1;
	
	    
    subSize=document.forms['orderManage'].orders_open_select.options.length; 
    sortby=$("#sort_orders_select").val();
    Desc_ASC=$("#sort_orders_dir").val();
    
    var submitOrders = new Array(subSize);
	for (var i = 0; i < subSize; i++) {
		//load the option value into string
		var tmpstr="";
   	    tmpstr=document.forms['orderManage'].orders_open_select.options[i].value;  
	   
		mrec=tmpstr.split("`");
		//load the option elements into an array
		submitOrders[i] = new Array(4);
		submitOrders[i][0]=jQuery.trim(mrec[0]);
		submitOrders[i][1]=jQuery.trim(mrec[1]);
		submitOrders[i][2]=jQuery.trim(mrec[2]);
		submitOrders[i][3]=jQuery.trim(mrec[3]);
		
	}
	    
	//now the whole thing is in an assoc multi-deminsional array
	
	//sort by 2nd element in descending order:
	//submitOrders.sort(by(2,-1)); // Z-A sorted array---- change the -1 to positive 1 for accending	
	submitOrders.sort(by(sortby,Desc_ASC)); 

	//alert(submitOrders[1][3]);
    //alert('here 2756');
	//return null; 
	
    //load back into the right one
	options = "";
			
			//porders.length
			
			for (i=0; i < subSize; i++){

			  var mval=	submitOrders[i][0]+'`'+submitOrders[i][1]+'`'+submitOrders[i][2]+'`'+submitOrders[i][3];
			  mrec = new Array();
			 
			  mrec[0]=jQuery.trim(submitOrders[i][0]);
			  mrec[1]=jQuery.trim(submitOrders[i][1]);
			  mrec[3]=jQuery.trim(submitOrders[i][3]);
			  var mpo=jQuery.trim(submitOrders[i][2]);
			  
			  var xcnt=0;
			  
			  if (jQuery.trim(mpo) !=''){
				xcnt=mpo.length;
              } else {
	            break   
              }    
			 
              //need to come back to this, could use ASCII maybe but this works fine- padding not working properly
              while (xcnt < 15){
	              mpo= mpo+'&nbsp;';
	              xcnt=xcnt+1;
              }  

			  var newoption=mrec[0]+'&nbsp;&nbsp;&nbsp;'+mrec[1]+'&nbsp;&nbsp;&nbsp;'+mpo+'&nbsp;&nbsp;&nbsp;'+mrec[3];
			  if (	jQuery.trim(mval) !=''){
			     options += '<option value="' + mval + '">'+newoption+'</option>'; 
		 	  }		      
				
			
			 			      
			}   
			
	
		 $("#orders_open_select").html(options);   
		
		    	

    }	
	
    
 function sortSubmittedOrders(){
	
	//first load the entire submitted order
			
	//the number of submitted orders
	var subSize=0;
	var sortby=0;
	var Desc_ASC=-1;
	
    subSize=document.forms['orderManage'].orders_submitted_select.options.length;
    sortby=$("#sort_orders_select_2").val();
    Desc_ASC=$("#sort_orders_dir_2").val();
    
    var submitOrders = new Array(subSize);
	for (var i = 0; i < subSize; i++) {
		//load the option value into string
		var tmpstr="";
   	    tmpstr=document.forms['orderManage'].orders_submitted_select.options[i].value;
	   
		mrec=tmpstr.split("`");
		//load the option elements into an array
		submitOrders[i] = new Array(4);
		submitOrders[i][0]=jQuery.trim(mrec[0]);
		submitOrders[i][1]=jQuery.trim(mrec[1]);
		submitOrders[i][2]=jQuery.trim(mrec[2]);
		submitOrders[i][3]=jQuery.trim(mrec[3]);
		
	}
	
    
	//now the whole thing is in an assoc multi-deminsional array
	
	//sort by 2nd element in descending order:
	//submitOrders.sort(by(2,-1)); // Z-A sorted array---- change the -1 to positive 1 for accending	
	submitOrders.sort(by(sortby,Desc_ASC)); 

	//alert(submitOrders[1][3]);
    //alert('here 2756');
	//return null; 
	
    //load back into the right one
	options = "";
			
			//porders.length
			
			for (i=0; i < subSize; i++){

			  var mval=	submitOrders[i][0]+'`'+submitOrders[i][1]+'`'+submitOrders[i][2]+'`'+submitOrders[i][3];
			  mrec = new Array();
			 
			  mrec[0]=jQuery.trim(submitOrders[i][0]);
			  mrec[1]=jQuery.trim(submitOrders[i][1]);
			  mrec[3]=jQuery.trim(submitOrders[i][3]);
			  var mpo=jQuery.trim(submitOrders[i][2]);
			  
			  var xcnt=0;
			  
			  if (jQuery.trim(mpo) !=''){
				xcnt=mpo.length;
              } else {
	            break   
              }    
			 
              //need to come back to this, could use ASCII maybe but this works fine- padding not working properly
              while (xcnt < 15){
	              mpo= mpo+'&nbsp;';
	              xcnt=xcnt+1;
              }  

			  var newoption=mrec[0]+'&nbsp;&nbsp;&nbsp;'+mrec[1]+'&nbsp;&nbsp;&nbsp;'+mpo+'&nbsp;&nbsp;&nbsp;'+mrec[3];
			  if (	jQuery.trim(mval) !=''){
			     options += '<option value="' + mval + '">'+newoption+'</option>'; 
		 	  }		      
				
			
			 			      
			}   
			
		$("#orders_submitted_select").html(options);
		
		    	

    }	   
    
    	
//companion function to above for multi-dem sort    
function by(i,dir) {
return function(a,b){a = a[i];b = b[i];return a.toLowerCase() == b.toLowerCase() ? 0 : (a.toLowerCase() < b.toLowerCase() ? -1*dir : dir)}
}
    

     function searchOrders(whichone,startPos){
	        
	    var subSize=0;
	    var searchStr="";
	    var searchFld=0;
	
	    if (whichone=='S'){
	   	
		    subSize=document.forms['orderManage'].orders_submitted_select.options.length;
	   		searchStr=$("#submitted_order_search_query").val();
	   		searchFld=$("#submitted_order_search_area").val();
    
		} else if (whichone=='O'){
	    
	   		subSize=document.forms['orderManage'].orders_open_select.options.length; 
	   		searchStr=$("#open_order_search_query").val();
	   		searchFld=$("#open_order_search_area").val();
    
		} else {
	 
	    	alert('Error opening select for search, line #2644');   
	    	return null; 
    	}   
	    
	    
	    //lets mark the select boxes
	    
	    	var found=0;
	    	    
			for (i=startPos; i <= subSize - 1; i++){
                
				var tmpstr="";
                if (whichone=='S'){
                   tmpstr=document.forms['orderManage'].orders_submitted_select.options[i].value;
                } else {   
                   tmpstr=document.forms['orderManage'].orders_open_select.options[i].value;
                }
                                 
                mrec=tmpstr.split("`");
		        
                //lets trim and lowercase the two comps
                mrec[searchFld]=jQuery.trim(mrec[searchFld]);
		        mrec[searchFld]= mrec[searchFld].toLowerCase();           
		        searchStr=jQuery.trim(searchStr);
		        searchStr=searchStr.toLowerCase();
		        
		        var aPosition = mrec[searchFld].indexOf(searchStr);

		        
				if (aPosition > -1){
					found=1;  
					if (whichone=='S'){
						
					  document.forms['orderManage'].orders_submitted_select.selectedIndex=i;
					} else {
				      document.forms['orderManage'].orders_open_select.selectedIndex=i;
			        }
   		            break;
                }   
				
            }
	    
            if (found==0){
	        	   //blAlert({ title: 'Search Orders', text: 'End of search.' });
				   
	        	   alert('End of Search.');
	        	   return null;
	                
            }    
	    
	    
	    
    }
    
      
    		
	function grayOut(vis, options) {  
		
		// Stephen pulled this section from the net in tutorial- no credits
		// Pass true to gray out screen, false to ungray  
		// options are optional.  This is a JSON object with the following (optional) properties  
		// opacity:0-100         
		// Lower number = less grayout higher = more of a blackout   
		// zindex: #             
		// HTML elements with a higher zindex appear on top of the gray out  
		// bgcolor: (#xxxxxx)    
		// Standard RGB Hex color code  
		// grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});  
		// Because options is JSON opacity/zindex/bgcolor are all optional and can appear  
		// in any order.  Pass only the properties you need to set.  
		
		var options = options || {};   
		var zindex = options.zindex || 50;  
		var opacity = options.opacity || 20; 
		var opaque = (opacity / 100);  
		var bgcolor = options.bgcolor || '#000000';  
		var dark=document.getElementById('darkenScreenObject');  
		
		if (!dark) {    
			
			// The dark layer doesn't exist, it's never been created.  So we'll    
		    // create it here and apply some basic styles.    
		    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917    
		    
		    var tbody = document.getElementsByTagName("body")[0];    
		    var tnode = document.createElement('div');    // Create the layer.        
		    tnode.style.position='absolute';                 // Position absolutely        
		    tnode.style.top='0px';                           // In the top        
		    tnode.style.left='0px';                          // Left corner of the page        
		    tnode.style.overflow='hidden';                   // Try to avoid making scroll bars                    
		    tnode.style.display='none';                      // Start out Hidden        
		    tnode.id='darkenScreenObject';                   // Name it so we can find it later    
		    tbody.appendChild(tnode);                            // Add it to the web page    
		    dark=document.getElementById('darkenScreenObject');  // Get the object.  
		}  
		
		if (vis) {   // Calculate the page width and height     
		
		    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {        
			    var pageWidth = document.body.scrollWidth+'px';        
			    var pageHeight = document.body.scrollHeight+'px';    
			} else if( document.body.offsetWidth ) {      
				var pageWidth = document.body.offsetWidth+'px';      
				var pageHeight = document.body.offsetHeight+'px';    
			} else {       
				var pageWidth='100%';       
				var pageHeight='100%';    
			}   
			    
			//reload is not going to bottom
			var pageHeight='150%';
			var pageWidth='100%'; 
			//set the shader to cover the entire page and make it visible.    
			dark.style.opacity=opaque;                          
			dark.style.MozOpacity=opaque;                       
			dark.style.filter='alpha(opacity='+opacity+')';     
			dark.style.zIndex=zindex;            
			dark.style.backgroundColor=bgcolor;      
			dark.style.width= pageWidth;    
			dark.style.height= pageHeight;    
			dark.style.display='block';                            
			
		} else {     
			dark.style.display='none';  
		}

	} //end of function
	
	
	$(function() {
		(function dialogInit() {
			$.extend($.ui.dialog.defaults, {
				autoOpen:		false,
				closeOnEscape:	false,
				draggable:		false,
				modal:			true,
				resizable:		false
			});
			
			$('#login_dialog')
				.dialog({
					buttons: { 
						"Log in": loginSubmit
					},
					title: 'Please log in to continue'
				})
				.keyup(function(e) {
					var key = (e.keyCode || e.charCode);
					if (key === 13 || key === 10) {
						$(this).dialog('option', 'buttons')['Log in']();
					}
				});
		}());
				
		(function formValidate() {
			
		}());
		
		tabs // Instantiate main tabs
			.tabs({
				ajaxOptions:	{ cache: false },
				cache:			true,
				cookie:			{ name: 'bl_tab' },
				show:			function(event, ui) {
					var acc5,
						act	= $('#accordion-sidebar h3.ui-state-active').prevAll().length / 2; // Which accordion pane is active
					$('#new_tabs a').css('background-position', '0 0').eq(ui.index).css('background-position', '0 -37px'); // Fake tabs
					if (ui.index < 3 && ui.index !== act) { // Geography, Business, and List Options tabs activate the sidebar accordion
						$('#accordion-sidebar').accordion('activate', ui.index);
					}
					if (ui.panel.id === 'tabs-5') { // Orders tab - load the appropriate orders list
						acc5 = $('#accordion-5').accordion('option', 'active');
						if (acc5 === 0) {
							//orderList('open');
						} else if (acc5 === 1) {
							//orderList('submitted');
						}
					} else if (ui.panel.id === 'tabs-6' && !$('#accordion-6').hasClass('accordion')) { // Support tab
						$('#accordion-6')
							.accordion({
								autoHeight:	false,
								animated:	false,
								clearStyle:	true
							})
							.addClass('accordion');
					}
				}
			})
			.removeClass('ui-corner-all')
			.addClass('ui-corner-bottom');
				
		$('.accordion').each(function() { // Accordions - 'animated' must be false due to IE bug - revisit later
			var self	= $(this),
				tab		= Number($.cookie('bl_tab'));
			self.accordion({
				active:		(self.attr('id') === 'accordion-sidebar' && tab < 4) ? tab : 0,
				autoHeight:	false,
				animated:	false,
				change:		function(event, ui) {
					var self	= $(this),
						eID		= self.attr('id'),
						index	= self.find("h3").index(ui.newHeader[0]); // Which accordion pane was clicked
					if (eID === 'accordion-sidebar') {
						if (index < 3 && index !== tabs.tabs('option', 'selected')) {
							tabs.tabs('select', index); // Real tabs
						}
					} else if (eID ===  'accordion-5') {
						if (index === 0) {
							//orderList('open');
						} else if (index === 1) {
							//orderList('submitted');
						}
					}	
				},
				clearStyle:	true
			});
		});
		
		$.metadata.setType("html5");
		
		window.CV = new CountVars();
		
		// Set global AJAX events
		$('#spinner')
			.ajaxError(function() {
				$(this).hide();
			})
			.ajaxStart(function() {
				$(this).show();
			})
			.ajaxStop(function() {
				$(this).hide();
			});
			
			
		orderInfo(); // Load order info
		loadbldef(); // load the customers prices	
		loadCount();
		
		
		//stephen added to handle additional criteria inputs
		$('.addl_inputs').bind('change', function() {
            // Bound handler called.
            var self = $(this);  
            var selfID	= self.attr('id');
			//alert(selfID+" line #2619");
				switch (selfID) {
				
				case 'sort_orders_dir_2': case 'sort_orders_select_2':		
				    sortSubmittedOrders();	
				
				case 'sort_orders_dir': case 'sort_orders_select':		
				    sortOpenOrders();	
					
				case 'cutoff_input':
				
                    cvAddVal('job_cutoff', $('#cutoff_input').val());
					break;             
               	
                case 'employee_low_input':
                    cvAddVal('employee_low', $('#employee_low_input').val());
                    break;
                case 'employee_high_input':
                    cvAddVal('employee_high', $('#employee_high_input').val());
                    break;
                case 'sales_low_input':  
                    cvAddVal('sales_low', $('#sales_low_input').val());
                    break;
                case 'sales_high_input':
                    cvAddVal('sales_high', $('#sales_high_input').val());
                    break;
                default:
				
					break;
			}
			
			sidebarSet();   
                    
       
        });

		
		// Various click event handling
		$('button, .selectionGroupTitle, li.selection-radius span, img, a, input, th').live('click', function() {
			var self = $(this);
			//alert(self.attr('id')+" line #2652");
			if (self.attr('id')=='rsic'){
			   var thesearch=$('#sic_search_input').val();
			   var thetable=$('input:radio[name=rsic]:checked').val();
			   //getSicSearch('S',thesearch,thetable);
			   return null;
		    }
			
						
			//alert(self.attr('id').substring(0,3)+" line #4558");
				
			if (self.attr('id').substring(0,3)=="zip"){
			
			    var checkdup=jQuery.inArray(self.attr('value'), CV['zip'] );
                if (checkdup==0){
				   //alert('This zip is already loaded');
				   return null;
		        }			
							    
			
	        }	
			
				
			function a() {
				var	elem		= [],
					elemUn		= [],
					strBuilder	= [],
					tabsBind	= function(n) {
						var $a = $('#accordion-6');
						n = (n) ? n : 0;
						if ($a.hasClass('accordion')) {
							tabs.tabs('select', ($.cookie('bl_logged_in') ? 5 : 3));
							$a.accordion('activate', n);
						} else {
							tabs
								.bind('tabsload', function(event, ui) {
									$('#accordion-6')
										.accordion({
											active:		n,
											autoHeight:	false,
											animated:	false,
											clearStyle:	true
										})
										.addClass('accordion');
								})
								.tabs('select', ($.cookie('bl_logged_in') ? 5 : 3));
						}
					},
					ind;
					
				log('link ' + (self.attr('id') || self.attr('class') || self.text()) + ' click');
				
				if (self.is('#new_tabs a')) { // New 'fake' tabs
					tabs.tabs('select', self.prevAll().length);
					return false; // prevents the hyperlink from firing
				} else if (self.is('#login_link')) { // Login link in topBar
					$('#login_dialog')
						.dialog('option', 'buttons', { 
							"Log in": function() { loginSubmit(); }
						})
						.dialog('open');
					document.getElementById('username_input').focus();
					return false;
				}  else if (self.is('#feedback-link')) { // Logout link in topBar
				    $('#feedback-company_name').val(' ');
			   		$('#feedback-name').val(' ');
			   		$('#feedback-feedback').val(' ');
			   		$('#feedback_dialog').dialog({
						buttons: { 
							"Cancel":	function() {
								$(this).dialog('close');
							},
							"Send":		function() {
					 			sendFeedback();
							}
				   			
							
						},
						title: 'Feedback'
			   		})
				
					$('#feedback_dialog').dialog({ autoOpen: false })
               		$('#feedback_dialog').dialog('open')	
					
				} else if (self.is('#logout_link')) { // Logout link in topBar
				    
				   if (document.getElementById('theSkin').value=='FSI'){
				      
				      $.post('include/php/logout.php', { 
					  	a:	'logout'
					  }, function(){
						$.cookie('bl_logged_in', null);
						$.cookie('bl_tab', null);
						$.cookie('PHPSESSID', null);
						window.location = 'http://www.fsilists.com/business.cfm?logout'; // Redirect to different login pages for production / dev
					  });
				       			
			       } else {
				       
					  $.post('include/php/logout.php', { 
						a:	'logout'
					  }, function(){
						$.cookie('bl_logged_in', null);
						$.cookie('bl_tab', null);
						$.cookie('PHPSESSID', null);
						window.location = 'http://login.compactlists.com/business.cfm?logout'; // Redirect to different login pages for production / dev
					  });
					
				    } //end of lohout conditional
					return false;
				} else if (self.is('#sitemap')) {
					tabsBind(5);
					return false;
				} else if (self.is('.contact_us')) {
					//tabsBind(5);
					tabs.tabs('select', 5);	
					$('#accordion-6').accordion('activate', 0);
					return false;
					
				} else if (self.is('.selectAll')) { // Select all link for multiSelect elements
					elem	= self.closest('.column').find('input:checkbox');
					elemUn	= elem.not('input:checked');
					if (elemUn.length > 0) {
						sidebarAdd(elemUn);
						cvAddVal(elemUn.attr('checked', 'checked'));
					} else {
						sidebarRemove(elem);
						cvRemoveVal(elem.removeAttr('checked'));
					}
					return false;
				} else if (self.is('.options_toggle')) { // Advanced options toggle link
					self.children('img').attr('src', ((self.parent().next().toggle().is(':visible')) ? 'img/minus.png' : 'img/plus.png'));
					return false;
				} else if (self.is('.faq_question')) { // FAQ section toggle link
					self.closest('div.faq_question').next('div.faq_answer').toggle();
					return false;
				} else if (self.is('.faq_header')) {
					self.closest('.faq_category').find('.faq_section').toggle();
					return false;
				} else if (self.is('.sitemap')) {
					ind = self.metadata();
					tabs.tabs('select', ind.tab);
					$('#accordion-' + (ind.tab + 1)).accordion('activate', ind.accordion);
					return false;
				}	
			}
			
			function button() {
				var	selfID	= self.attr('id'),
					selfIDb	= selfID.replace('_button', '');
					
				//alert(selfID+" line #4776 bl.js");
				
				if (buttons.hasOwnProperty(selfIDb)) {
					buttons[selfIDb].call(self);
				} else {
					switch (selfID) {
						//could not trap the two excludes in the default-not sure why but doesn't matter enough to stop and ponder ;-)
						case 'exclude_sic_range_button':
						  mtext=$('#exclude_sic_textarea').val();
						  mtext=mtext.replace(/\n/g,",")
	                      mtext=mtext.replace(/\r/g,",")
	                      mtext=mtext.replace(/ /g,",")
	                      mtext=mtext.replace(/,,,/g,",,")
	                                mtext=mtext.replace(/,,/g,",")
	                      $('#exclude_sic_textarea').val(mtext);
	                      document.getElementById('plswait').style.display = 'block';          
						  $.getJSON( 'include/php/validate_manualEntries.php?thetext='+mtext+'&whichone='+selfID, function ( data ) { 
								var theret=data.retmessage; 
								document.getElementById('plswait').style.display = 'none'; 
							    if ( theret=="good to go"){
								    cvAddRange(self.closest('.select_section').find('textarea'));		    
							    } else {
								    blAlert({ title: 'Validation Failed', text: theret });   
							    }       
								
						   } ); 
							
						   //cvAddRange(self.closest('.select_section').find('textarea'));
						   break;
						case 'exclude_zip_range_button':
						    
						   mtext=$('#exclude_zip_textarea').val();
						   mtext=mtext.replace(/\n/g,",")
	                       mtext=mtext.replace(/\r/g,",")
	                       mtext=mtext.replace(/ /g,",")
	                       mtext=mtext.replace(/,,,/g,",,")
	                       mtext=mtext.replace(/,,/g,",")
	                       $('#exclude_zip_textarea').val(mtext);
	                      
	                       
	                       
	                       
	                       document.getElementById('plswait').style.display = 'block';						
						   $.getJSON( 'include/php/validate_manualEntries.php?thetext='+mtext+'&whichone='+selfID, function ( data ) { 
								var theret=data.retmessage; 
								document.getElementById('plswait').style.display = 'none';
							    if ( theret=="good to go"){
								    
								    
								    //lets loop over and build the range that will go to API
								    mtext=$('#exclude_zip_textarea').val();
						            var mstr=mtext.split(",");
								    for (var i = 0, il = mstr.length; i < il; i++) {
									    
									    //in a hurry come back and pad...
									    if (mstr[i].length == 3){
				                          mstr[i]=mstr[i]+"00-"+mstr[i]+"99"; 
		                   	            } else if (mstr[i].length == 4){
				                          mstr[i]=mstr[i]+"0-"+mstr[i]+"9"; 
		                   	            }     
    
			                        }
								    
			                        mtext=mstr.join(","); 

	                                $('#exclude_zip_textarea').val(mtext);
								    
 
								    cvAddRange(self.closest('.select_section').find('textarea'));
								    
							    		    
							    } else {
								    blAlert({ title: 'Validation Failed', text: theret });   
							    }       
								
						   } ); 
						   //cvAddRange(self.closest('.select_section').find('textarea'));
						   break;

						default:
							if (self.is('.remove_button')) {
								var e		= selfID.substring(0, selfID.indexOf('_')),
									geog	= {
										acode:	'Area Codes',
										city:	'Cities',
										county:	'Counties',
										crid:	'Carrier Routes',
										metro:	'Metro Areas',
										zip:	'ZIP Codes'
									};
								blConfirm({
									title:		'Remove Selection Criteria', 
									text:		'This action cannot be undone. Click "OK" to remove all ' + geog[e] + '.',
									callback:	function() {
										$('#selection-' + e).find('ul').replaceWith('<ul></ul>'); // Remove items from sidebar
										cvRemoveVal(e); // Remove values from CV object
										//added this per Mary 10/27/2011
										if (geog[e]=="ZIP Codes"){
											$('#zip_textarea').val('');
									    }	
									    if (geog[e]=="Carrier Routes"){
											$('#crid_textarea').val('');
									    }	
									    if (geog[e]=="Carrier Routes"){
											$('#crid_textarea').val('');
									    }	
									    
									    //if (geog[e]=="States"){
										if (geog[e]==null){    
											$('#state_textarea').val('');
											$('#sic_textarea').val('');
									    }	
									    
									    
										$('#' + selfID).closest('.ui-accordion-content').find('input:checkbox').removeAttr('checked'); // Uncheck any leftover checkboxes
									}
								});
							} else if (self.is('.range_button')) {
								
								//alert(selfID+" line #4891 bl.js");				
  							
								//tried declaring an array, loading it and sending as a get with escape() and the transport failed, also tried using the .post jquery and
								//got a stack overflow on line 505-- this worked and being pushed to complete.
								var mtext="An validation entry was not passed.";
								
  							
                                if (selfID=='zip_range_button'){
	                                mtext=$('#zip_textarea').val();
	                                mtext=mtext.replace(/\n/g,",")
	                                mtext=mtext.replace(/\r/g,",")
	                                mtext=mtext.replace(/ /g,",")
	                                mtext=mtext.replace(/,,,/g,",,")
	                                mtext=mtext.replace(/,,/g,",")
	                                $('#zip_textarea').val(mtext);
	                                
							    } else if (selfID=='crid_range_button') {
								    mtext=$('#crid_textarea').val();
								    mtext=mtext.replace(/\n/g,",")
	                                mtext=mtext.replace(/\r/g,",")
	                                mtext=mtext.replace(/ /g,",")
	                                mtext=mtext.replace(/,,,/g,",,")
	                                mtext=mtext.replace(/,,/g,",")
	                                $('#crid_textarea').val(mtext);
	                                
							    } else if (selfID=='sic_range_button') {
								    
								    mtext=$('#sic_textarea').val();
								    mtext=mtext.replace(/\n/g,",")
	                                mtext=mtext.replace(/\r/g,",")
	                                mtext=mtext.replace(/ /g,",")
	                                mtext=mtext.replace(/,,,/g,",,")
	                                mtext=mtext.replace(/,,/g,",")
	                                $('#sic_textarea').val(mtext);
	                                
	                                
							    } else {
								   //this is the catch all for any that are not trapped
								   cvAddRange(self.closest('.select_section').find('textarea'));
								  
							    }  
							    
							    
							    if (mtext !="An validation entry was not passed."){  
								    //alert(selfID+" line #4935 bl.js");      
	                            	document.getElementById('plswait').style.display = 'block';    
	                                
									$.getJSON( 'include/php/validate_manualEntries.php?thetext='+mtext+'&whichone='+selfID, function ( data ) { 
										document.getElementById('plswait').style.display = 'none';
																			
										var theret=data.retmessage;
										var thevdata=data.valid; 
										var thebaddata=data.notvalid; 
										
										//document.getElementById('plswait').style.display = 'none';
										
										if ( theret !="good to go"){
										   blAlert({ title: 'Validation Failed', text: theret });
									    }
										
									       
										    //lets loop over and build the range that will go to API
								   		 	//changed to valid return from --- mtext=$('#zip_textarea').val();
								   		 	mtext=thevdata;
								   		 
			                        	    
			                        	     
                                            if (selfID=='zip_range_button'){
	                                            var mstr=mtext.split(",");
								    			for (var i = 0, il = mstr.length; i < il; i++) {
										    
										       		//in a hurry come back and pad...
									    	   		if (mstr[i].length == 3){
				                        	   		  mstr[i]=mstr[i]+"00-"+mstr[i]+"99"; 
		                   	            	   		} else if (mstr[i].length == 4){
				                        	    	  mstr[i]=mstr[i]+"0-"+mstr[i]+"9"; 
		                   	            	   		}   
    
		                        	        	}
		                        	        	
	                                            mtext=mstr.join(",");
		                        	        	
	                                	        $('#zip_textarea').val(mtext);
	                                	        
							                } else if (selfID=='crid_range_button') {
							                   $('#crid_textarea').val(mtext);
							                } else if (selfID=='sic_range_button') {
							                   $('#sic_textarea').val(mtext);
                                            }
                                            
                                            
                                            //alert(selfID+" line #4978 bl.js");
							                cvAddRange(self.closest('.select_section').find('textarea'));		    
									          
	                                		if (selfID=='zip_range_button'){
	                                           	                                         
	                                	       $('#zip_textarea').val(thebaddata);
	                                	        
							                } else if (selfID=='crid_range_button') {
							                   
								               $('#crid_textarea').val(thebaddata);
							                   
							                } else if (selfID=='sic_range_button') {
							                   
								               $('#sic_textarea').val(thebaddata);
								               
                                            }
	                                		
	                                		
								
									} ); 
							    } //end of validation test
	
								
							}
							break;
					}
				}
				
				
				log('button ' + (self.attr('id') || self.attr('class')) + ' click');
				return false;
			}
			
			function img() {
				if (self.is('.cross')) { // Sidebar selection removal
					sidebarRemove(self.parent());
					cvRemoveVal(self.parent());
				} //removed sensitive data dialog open
				//else if (self.is('.flag_red')) { // Sensitive data dialog
				//	$('#sensitive_data_dialog').dialog('open');
				//}
				
				log('img ' + (self.attr('id') || self.attr('class')) + ' click');
			}
			
			function inputs() {
				
				var selfID	= self.attr('id'),
					selfCV,
					reports,
					reportsUn;
				var selfNM=self.attr('name');
				
				//alert(self.attr('id')+" line #4897");
				//var checkdup=jQuery.inArray(self.attr('value'), CV['sic'] );
                //if (checkdup==0){
	              //break;                    
                //} 
                                   
				switch (selfID) {
					
					
					case 'thepkg_input_1': 
					 	
					   	$('input[id="thepkg_input_2"]').attr('checked', false); 
					   	sidebarRemove($('input[id="thepkg_input_2"]'));			
						selfCV = self.attr('name');
						if (self.is(':checked')) {
							cvAddVal(self);
							sidebarAdd({ cv: selfCV, group: $('#selection-package'), text: self.next('label').text() });
						} else {
							CV[selfCV] = 'F';
							sidebarRemove(self);
						}
						
						$('#prices_basicrecord_items').show();
						
						
						if (!$('input[id="onetimeuse_input_2"]').is(':checked')){
						   //Single Mailing ($40.00/M)
					       $('input[id="onetimeuse_input_1"]').click(); 
					       //toggle the onetime use to 'F'
					       cvAddVal('onetimeuse', 'T');
					       sidebarAdd({ cv: 'onetimeuse', group: $('#selection-use'), text: $('input[id="onetimeuse_input_1"]').next('label').text() });		 
					
					    }				    
					    
						break;
						
					case 'thepkg_input_2':
					    
					    //get rid of use settings on panel & clear checks
					    $('input[id="onetimeuse_input_1"]').attr('checked', false); 
					   	sidebarRemove($('input[id="onetimeuse_input_1"]'));		   	 
					   	
					   	//alert('line 3779');
					   	$('input[id="onetimeuse_input_2"]').attr('checked', false); 
					   	sidebarRemove($('input[id="onetimeuse_input_2"]'));			
					   	
					   	
					   	//toggle the onetime use to 'F'
					    cvAddVal('onetimeuse', 'F');
					   	
					    //add the one setting unser sidebar			   	
					    $('input[id="thepkg_input_1"]').attr('checked', false); 
					   	sidebarRemove($('input[id="thepkg_input_1"]'));		
					 	
					   	selfCV = self.attr('name');
						if (self.is(':checked')) {
							cvAddVal(self);
							sidebarAdd({ cv: selfCV, group: $('#selection-package'), text: self.next('label').text() });
						} else {
							CV[selfCV] = 'F';
							sidebarRemove(self);
						}
						$('#prices_basicrecord_items').hide();
						
						//remove any checks and remove from the side for ones includes in full
						var extrafld = ['recSALES_VOL','recEMPL_TOTAL','recTELEPHONE','recCONTACT','recFRAN_CODE']; 
 
						$.each(extrafld, function(key, value) {
							//this takes into account grouping- could put on back end but did not want to bury values
							if (value=='recCONTACT'){
 								CV['recCEO_1ST_NM'] = 'F';
                            	CV['recCEO_LST_NM'] = 'F';
			                	CV['recDDM_TITLE'] = 'F';
			                	CV['recCONTACT'] = 'F';
		                    } else if (value=='recSALES_VOL'){
			                	CV['recSALES_VOL'] = 'F';
			                	CV['recSALES_VOL_CD'] = 'F';
			                } else if (value=='recEMPL_TOTAL'){
			                	CV['recEMPL_TOTAL'] = 'F';
			                	CV['recEMPL_TOT_CD'] = 'F';
						    } else {
								CV[value] = 'F';
				    		}
				    		 	
	                        eval('sidebarRemove($(\'input[id="'+value+'_input"]\'))');
                            eval('$(\'input[id="'+value+'_input"]\').attr(\'checked\', false)');
                                               
                        });
                        
					
					  	break;
						
					case 'onetimeuse_input_1':
					        
					    $('input[id="onetimeuse_input_2"]').attr('checked', false); 
					   	sidebarRemove($('input[id="onetimeuse_input_2"]'));			
					
					    selfCV = self.attr('name');
					    var selfCV2 = 'thepkg';
						if (self.is(':checked')) {
							cvAddVal(self);
							sidebarAdd({ cv: selfCV, group: $('#selection-use'), text: self.next('label').text() });
						} else {
							CV[selfCV] = 'F';
							sidebarRemove(self);
						}
						
						//full is checked move to basic
					    if ($('input[id="thepkg_input_2"]').is(':checked')){
						   $('input[id="thepkg_input_2"]').attr('checked', false); 
					   	   sidebarRemove($('input[id="thepkg_input_2"]'));
					   	   cvAddVal('thepkg', 'B');
					   	   sidebarAdd({ cv: selfCV2, group: $('#selection-package'), text: $('input[id="thepkg_input_1"]').next('label').text() });		 
					       $('input[id="thepkg_input_1"]').attr('checked', true); 
					       
					        $('input[id="onetimeuse_input_2"]').attr('checked', false); 
					       	sidebarRemove($('input[id="onetimeuse_input_2"]'));			
					 
					       
					       
					    }
						
						
						break;
					    
					case 'onetimeuse_input_2':
					    $('input[id="onetimeuse_input_1"]').attr('checked', false); 
					   	sidebarRemove($('input[id="onetimeuse_input_1"]'));		
					
					    selfCV = self.attr('name');
					    var selfCV2 = 'thepkg';
						if (self.is(':checked')) {
							cvAddVal(self);
							sidebarAdd({ cv: selfCV, group: $('#selection-use'), text: self.next('label').text() });
						} else {
							CV[selfCV] = 'F';
							sidebarRemove(self);
						}
						
						
						 //full is checked move to basic
					    if ($('input[id="thepkg_input_2"]').is(':checked')){
						   //Single Mailing ($40.00/M)
					       $('input[id="thepkg_input_2"]').attr('checked', false); 
					   	   sidebarRemove($('input[id="thepkg_input_2"]'));
					   	   cvAddVal('thepkg', 'B');	
					   	   sidebarAdd({ cv: selfCV2, group: $('#selection-package'), text: $('input[id="thepkg_input_1"]').next('label').text() });		 
					       $('input[id="thepkg_input_1"]').attr('checked', true); 
					       
					       $('input[id="onetimeuse_input_2"]').attr('checked', false); 
					   	   sidebarRemove($('input[id="onetimeuse_input_2"]'));			
					 
					       
					    }
						
						
						break;
					case 'all_reports_input':
						reports		= $('#report_div').find('input:not(#all_reports_input)');
						reportsUn	= reports.not(':checked');
						
						if (self.is(':checked')) {
							if (reportsUn.length) {
								cvAddVal(reportsUn.attr('checked', 'checked'));
							} else {
								cvRemoveVal(reports.removeAttr('checked'));
							}
						} else {
							cvRemoveVal(reports.removeAttr('checked'));
						}
						break;
						
					case 'options_includes_input_1':
						selfCV = self.attr('name');
						
						if (self.is(':checked')) {
							CV[selfCV] = 'T';
							sidebarAdd({ cv: selfCV, group: $('#selection-additional'), text: self.next('label').text() });
						} else {
							CV[selfCV] = 'F';
							sidebarRemove(self);
						}
						break;
					case 'options_includes_input_2':
					     selfCV = self.attr('name');
						
						if (self.is(':checked')) {
							CV[selfCV] = 'T';
							sidebarAdd({ cv: selfCV, group: $('#selection-additional'), text: self.next('label').text() });
						} else {
							CV[selfCV] = 'F';
							sidebarRemove(self);
						}
						break;
					
					case 'options_includes_input_3':	
						selfCV = self.attr('name');
						
						if (self.is(':checked')) {
							CV[selfCV] = 'T';
							sidebarAdd({ cv: selfCV, group: $('#selection-additional'), text: self.next('label').text() });
						} else {
							CV[selfCV] = 'F';
							sidebarRemove(self);
						}
						break;					
					default:
					
					   if (selfID.substring(0,5)==="metro") {
						   //alert(self.attr('label')+" line #3780");
							selfCV='metro';
							if (self.is(':checked')) {
								cvAddVal(self);
								sidebarAdd({ cv: selfCV, group: $('#selection-metro'), text: self.attr('label') });
							} else {
								cvRemoveVal(self);
								sidebarRemove(self);
							}
				       } else if (self.is('.multiSelect input')) {
							//alert(selfID.substring(0,5)+" line #3790");
							if (self.is(':checked')) {
								cvAddVal(self);
								sidebarAdd(self);
							} else {
								cvRemoveVal(self);
								sidebarRemove(self);
							}
	
					   }  else if (selfNM.substring(0,3)==="sic") {
							
							selfCV = selfNM.substring(0,3);
							if (self.is(':checked')) {
								
								var checkdup=jQuery.inArray(self.attr('value'), CV['sic'] );
                                if (checkdup==-1){
								   cvAddVal('sic', self.attr('value'));		
							    }  
							     
						    } else {
					            cvRemoveVal('sic', self.attr('value'));
				            }    
						    //no matter what I do I cannot seem to set the sidebar from here and had to add a sidebarset to fire after inputs run
				           
				       } else if (selfNM.substring(0,8)==="jobtitle") {
							
							selfCV = selfNM.substring(0,8);
							if (self.is(':checked')) {
								cvAddVal('jobtitle', self.attr('value'));		
						    } else {
					            cvRemoveVal('jobtitle', self.attr('value'));
				            }    
						    //no matter what I do I cannot seem to set the sidebar from here and had to add a sidebarset to fire after inputs run
				           
				       } else if (selfNM.substring(0,3)==="rec") {
							
							selfCV = self.attr('name');
							if (self.is(':checked')) {
								
								//this takes into account grouping- could put on back end but did not want to bury values
								if (selfCV=='recCONTACT'){
 									CV['recCEO_1ST_NM'] = 'T';
                            		CV['recCEO_LST_NM'] = 'T';
			                		CV['recDDM_TITLE'] = 'T';
			                		CV['recCONTACT'] = 'T';
		                    	} else if (selfCV=='recSALES_VOL'){
			                		CV['recSALES_VOL'] = 'T';
			                		CV['recSALES_VOL_CD'] = 'T';
			                	} else if (selfCV=='recEMPL_TOTAL'){
			                		CV['recEMPL_TOTAL'] = 'T';
			                		CV['recEMPL_TOT_CD'] = 'T';
						    	} else {
									CV[selfCV] = 'T';
				    			}
				    			
								sidebarAdd({ cv: selfCV, group: $('#selection-fields'), text: self.next('label').text() });
							} else {
								
								if (selfCV=='recCONTACT'){
 									CV['recCEO_1ST_NM'] = 'F';
                            		CV['recCEO_LST_NM'] = 'F';
			                		CV['recDDM_TITLE'] = 'F';
			                		CV['recCONTACT'] = 'F';
		                    	} else if (selfCV=='recSALES_VOL'){
			                		CV['recSALES_VOL'] = 'F';
			                		CV['recSALES_VOL_CD'] = 'F';
			                	} else if (selfCV=='recEMPL_TOTAL'){
			                		CV['recEMPL_TOTAL'] = 'F';
			                		CV['recEMPL_TOT_CD'] = 'F';
						    	} else {
									CV[selfCV] = 'F';
				    			}
								sidebarRemove(self);
							}	
							
							
							
							
						}	
						
						
						break;
				}
				log('inputs ' + (self.attr('id') || self.attr('class')) + ' click');
				sidebarSet();
			       
			}
			
			function selGroup() {
				
				var $ul = self.next('ul');
				
				
				//scw- I added this as the sidebar was having a disconnect on the addtional items/ sic has 3 tabs- could get it to fire right so
				//just hardcoded it here.
				var demoCnt=$("#accordion-sidebar h3").index($("#accordion-sidebar h3.ui-state-active"));
				var demoCnt2=self.parent().index();
				
				//alert(demoCnt+' | '+demoCnt2+'  3774');
			    if (demoCnt==1){
				    
				    if (demoCnt2==0){
					   $('#accordion-2').accordion('activate', 0);
				    } else if (demoCnt2==1){    
				       $('#accordion-2').accordion('activate', 3);
			        } else if (demoCnt2==2){    
				       $('#accordion-2').accordion('activate', 4);
			        } else if (demoCnt2==3){
				       $('#accordion-2').accordion('activate', 5);
			        } else if (demoCnt2==4){
					   $('#accordion-2').accordion('activate', 5);
			        }
			        //can add elseifs here
			    } else if (demoCnt==0){ 
			        
				    if (demoCnt2==0){
					   $('#accordion-1').accordion('activate', 0);
				    } else if (demoCnt2==1){    
				       $('#accordion-1').accordion('activate', 1);
			        } else if (demoCnt2==2){    
				       $('#accordion-1').accordion('activate', 2);
			        } else if (demoCnt2==3){
				       $('#accordion-1').accordion('activate', 3);
			        } else if (demoCnt2==4){
				       $('#accordion-1').accordion('activate', 4);
			        } else if (demoCnt2==5){
				       $('#accordion-1').accordion('activate', 5);
			        } else if (demoCnt2==6){
				       $('#accordion-1').accordion('activate', 6);
			        } else if (demoCnt2==7){
					   $('#accordion-1').accordion('activate', 7);
			        }
			    
			    
		        } else { //end of check for dem tabs    
						    
					if ($ul.is(':empty')) { // Activate appropriate accordion pane if selection group is empty
				    
						index		= self.parent().index();
						activePane	= $("#accordion-sidebar h3").index($("#accordion-sidebar h3.ui-state-active")) + 1;
					
						if (1 <= activePane <= 2) {
							$('#accordion-' + activePane).accordion('activate', index);
						}
					} else {
					
						$ul.toggle().end().find('img.bullet_toggle').toggle();
					}
				
			    } //end of mycheck when the active pane is specified and not progressive
				
				
				log('selgroup ' + (self.attr('id') || self.attr('class')) + ' click');
			}
			
			if (self.is('button')) {
				button();
			} else if (self.is('.selectionGroupTitle, li.selection-radius span')) {
				selGroup();
			} else if (self.is('img')) {
				img();
			} else if (self.is('a')) {
				return a(); // Must return false in order to prevent default action
			} else if (self.is(':checkbox, :radio')) {
				inputs();
			}
		});
		
		// Various change event handling
		$('select', tabs[0]).live('change', function() {
			var self		= $(this),
				selfCV,
				selfID		= self.attr('id'),
				selfVal		= self.val(),
				cTab		= tabs.tabs('option', 'selected');
			
				
			if (self.is('#some_id')) {
				return false;
			}
			
			log('input:text, select, input:file change');
			
			
			switch (selfID) {
				
                case 'employee_range_select': 
                    cvAddVal('employee_range', $('#employee_range_select').val());   
                    break;
                
                case 'sales_range_select': 
                    cvAddVal('sales_range', $('#sales_range_select').val());
                    break;
                case 'location_type_select':  
                    cvAddVal('location_type', $('#location_type_select').val());
                    break;
                case 'gender_select': 
                    cvAddVal('gender', $('#gender_select').val());
                    break;
                case 'pub_priv_select':  
                    cvAddVal('pub_priv', $('#pub_priv_select').val());
                    break;
              		
				case 'zip_state_select':
					getGeography({
						data:	{ geo: 'city', search: selfVal },
						target:	$('#zip_city_select')
					});
					break;
				case 'zip_city_select':
					getGeography({
						data:	{ geo: 'zip', search: selfVal },
						target:	$('#zip_zip_div')
					});
					break;
				case 'city_state_select':
					getGeography({
						data:	{ geo: 'city', search: selfVal },
						target:	$('#city_city_div')
					});
					break;
				case 'county_state_select':
					getGeography({
						data:	{ geo: 'county', search: selfVal },
						target:	$('#county_county_div')
					});
					break;
				case 'metro_state_select':
					getGeography({
						data:	{ geo: 'metro', search: selfVal },
						target:	$('#metro_metro_div')
					});
					break;
				case 'acode_state_select':
					getGeography({
						data:	{ geo: 'city', search: selfVal },
						target:	$('#acode_city_select')
					});
					break;
				case 'acode_city_select':
					getGeography({
						data:	{ geo: 'acode', search: selfVal },
						target:	$('#acode_acode_div')
					});
					
					break;
				case 'start_date_input': case 'cutoff':
					cvAddVal(self);
					break;
					
				case 'segment_select': 
					manageSegments('L','');
					break;
					
				case 'orders_open_select': 
					//manageOrders('E','','open','open'); //not active because the other buttons need to have focus
					break;		
					
				default:
					selfCV = self.attr('name') || self.metadata().cv;
					
					if (selfCV && CV.hasOwnProperty(selfCV)) {
						cvAddVal(self);
					}
					break;
			}
			sidebarSet();
		});
		
		// Various blur event handling
		$('input:text, input:file', tabs[0]).live('blur', function() {
			var self		= $(this),
				selfCV,
				selfID		= self.attr('id'),
				selfVal		= self.val();
			
			if (self.is('#some_id')) {
				return false;
			}
			
			switch (selfID) {
				default:
					selfCV = self.attr('name') || self.metadata().cv;
					
					if (selfCV && CV.hasOwnProperty(selfCV)) {
						cvAddVal(self);
					}
					break;
			}
			
			log('input:text, select, input:file blur');
		});
		
		// Button hover effect
		$('button').hover(function() { 
			$(this).addClass('ui-state-hover'); 
		}, function() { 
			$(this).removeClass('ui-state-hover'); 
		});
		
		// Keyup event handling- scw removed radius from here
		$('#crid_zip_input').keyup(function(e) {
			e				= e || event; //If "e" is undefined use the global "event" variable
			var key			= (e.keyCode ? e.keyCode : e.charCode),
				self		= $(this),
				selfVal		= self.val(),
				whichKey	= (selfVal.length === 5 && ((key >= 48 && key <= 57) || (key >= 96 && key <= 105)));
			if (self.is('#crid_zip_input') && whichKey) {
				
				getGeography({
					data:	{ geo: 'crid', search: selfVal },
					target:	$('#crid_crid_div')
				});

			} 
		});
		
		$('#spinner').hide(); // Needed for now
		
		$('#content').show(); // Show content div last to prevent FOUC
		
		sidebarSet();
	});
	
	// Expose publicly accessible methods and properties
	return {
		CountVars:		CountVars,
		BLdata:			BLdata,
		blAlert:		blAlert,
		blConfirm:		blConfirm,
		cvAddVal:		cvAddVal,
		cvAddRange:		cvAddRange,
		cvRemoveVal:	cvRemoveVal,
		formSet:		formSet,
		getGeography:	getGeography,
		getSicSearch:	getSicSearch,
		sidebarAdd:		sidebarAdd,
		sidebarRemove:	sidebarRemove,
		sidebarSet:		sidebarSet,
		grayOut:		grayOut,
		getsic:			getsic
		
	};
}());
