/*! Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (MIT_LICENSE.txt)
 * and GPL Version 2 (GPL_LICENSE.txt) licenses.
 *
 * Version: 1.1.1
 * Requires jQuery 1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */

(function($){$.extend($.fn,{livequery:function(type,fn,fn2){var self=this,q;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&type==query.type&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid))return(q=query)&&false});q=q||new $.livequery(this.selector,this.context,type,fn,fn2);q.stopped=false;q.run();return this},expire:function(type,fn,fn2){var self=this;if($.isFunction(type))fn2=fn,fn=type,type=undefined;$.each($.livequery.queries,function(i,query){if(self.selector==query.selector&&self.context==query.context&&(!type||type==query.type)&&(!fn||fn.$lqguid==query.fn.$lqguid)&&(!fn2||fn2.$lqguid==query.fn2.$lqguid)&&!this.stopped)$.livequery.stop(query.id)});return this}});$.livequery=function(selector,context,type,fn,fn2){this.selector=selector;this.context=context;this.type=type;this.fn=fn;this.fn2=fn2;this.elements=[];this.stopped=false;this.id=$.livequery.queries.push(this)-1;fn.$lqguid=fn.$lqguid||$.livequery.guid++;if(fn2)fn2.$lqguid=fn2.$lqguid||$.livequery.guid++;return this};$.livequery.prototype={stop:function(){var query=this;if(this.type)this.elements.unbind(this.type,this.fn);else if(this.fn2)this.elements.each(function(i,el){query.fn2.apply(el)});this.elements=[];this.stopped=true},run:function(){if(this.stopped)return;var query=this;var oEls=this.elements,els=$(this.selector,this.context),nEls=els.not(oEls);this.elements=els;if(this.type){nEls.bind(this.type,this.fn);if(oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)$.event.remove(el,query.type,query.fn)})}else{nEls.each(function(){query.fn.apply(this)});if(this.fn2&&oEls.length>0)$.each(oEls,function(i,el){if($.inArray(el,els)<0)query.fn2.apply(el)})}}};$.extend($.livequery,{guid:0,queries:[],queue:[],running:false,timeout:null,checkQueue:function(){if($.livequery.running&&$.livequery.queue.length){var length=$.livequery.queue.length;while(length--)$.livequery.queries[$.livequery.queue.shift()].run()}},pause:function(){$.livequery.running=false},play:function(){$.livequery.running=true;$.livequery.run()},registerPlugin:function(){$.each(arguments,function(i,n){if(!$.fn[n])return;var old=$.fn[n];$.fn[n]=function(){var r=old.apply(this,arguments);$.livequery.run();return r}})},run:function(id){if(id!=undefined){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id)}else $.each($.livequery.queries,function(id){if($.inArray(id,$.livequery.queue)<0)$.livequery.queue.push(id)});if($.livequery.timeout)clearTimeout($.livequery.timeout);$.livequery.timeout=setTimeout($.livequery.checkQueue,20)},stop:function(id){if(id!=undefined)$.livequery.queries[id].stop();else $.each($.livequery.queries,function(id){$.livequery.queries[id].stop()})}});$.livequery.registerPlugin('append','prepend','after','before','wrap','attr','removeAttr','addClass','removeClass','toggleClass','empty','remove','html');$(function(){$.livequery.play()})})(jQuery);
/* jQuery AutoGrow Plugin */
var colsDefault=0;var rowsDefault=0;function setDefaultValues(txtArea){colsDefault=txtArea.cols;rowsDefault=txtArea.rows}function bindEvents(txtArea){txtArea.onkeyup=function(){grow(txtArea)}}function grow(txtArea){var linesCount=0;var lines=txtArea.value.split('\n');for(var i=lines.length-1;i>=0;--i){linesCount+=Math.floor((lines[i].length/colsDefault)+1)}if(linesCount>=rowsDefault)txtArea.rows=linesCount+1;else txtArea.rows=rowsDefault}jQuery.fn.autoGrow=function(){return this.each(function(){setDefaultValues(this);bindEvents(this)})};
/**
 * @author JonG
 * custom functions
 * all site function should be located here
 */
var errors = "";
var cnr = "";

var engine = {
	utils : {
		return_current_date : function(){
			var raw_date = new Date(),
				month = raw_date.getMonth() + 1,
				day = raw_date.getDate(),
				year = raw_date.getFullYear(),
				date = "";
			
			if(day < 10) {day = '0' + day;}
			if(month < 10){month = '0' + month;}
			date = month + '/' + day + '/' + year;
			return date;
		},
		stringify : function(a){
			{quoteString=function(i){var j=/["\\\x00-\x1f\x7f-\x9f]/g,l={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};if(i.match(j))return'"'+i.replace(j,function(k){var f=l[k];if(typeof f==="string")return f;f=k.charCodeAt();return"\\u00"+Math.floor(f/16).toString(16)+(f%16).toString(16)})+'"';return'"'+i+'"'};if(typeof JSON=="object"&&JSON.stringify)return JSON.stringify(a);var c=typeof a;if(a===null)return"null";if(c!="undefined"){if(c=="number"||c=="boolean")return a+"";if(c=="string")return quoteString(a);if(c=="object"){if(typeof a.toJSON=="function")return jngFunctions.utils.stringify(a.toJSON());if(a.constructor===Date){var d=a.getUTCMonth()+1;if(d<10)d="0"+d;var b=a.getUTCDate();if(b<10)b="0"+b;c=a.getUTCFullYear();var e=a.getUTCHours();if(e<10)e="0"+e;var g=a.getUTCMinutes();if(g<10)g="0"+g;var h=a.getUTCSeconds();if(h<10)h="0"+h;a=a.getUTCMilliseconds();if(a<100)a="0"+a;if(a<10)a="0"+a;return'"'+c+"-"+d+"-"+b+"T"+e+":"+g+":"+h+"."+a+'Z"'}if(a.constructor===Array){d=[];for(b=0;b<a.length;b++)d.push(jngFunctions.utils.stringify(a[b])||"null");return"["+d.join(",")+"]"}d=[];for(b in a){c=typeof b;if(c=="number")c='"'+b+'"';else if(c=="string")c=quoteString(b);else continue;if(typeof a[b]!="function"){e=jngFunctions.utils.stringify(a[b]);d.push(c+":"+e)}}return"{"+d.join(", ")+"}"}}}
		},
		add_date_picker2 : function(id,param){
			switch(param){
				case 1 :
					var currentDate = new Date(), currentYear = currentDate.getFullYear(), param = param;
						currentYear = currentYear + 10;
					$(id).datepicker({
						yearRange: '1900:' + currentYear,
						changeMonth: true,
						changeYear: true,
						showButtonPanel: true,
						onChangeMonthYear: function(year, month, inst){
							var a = $(this).val();
							var curMonth = month;
							var curDay = a.split('/')[1];
							$(this).val(curMonth + '/' + curDay + '/' + year);
						}
					});
				break;
				case 2 :
					var currentDate = new Date(), currentYear = currentDate.getFullYear(), param = param;
						currentYear = currentYear;
					$(id).datepicker({
						yearRange: '1900:' + currentYear,
						changeMonth: true,
						changeYear: true,
						//minDate : 0,
						maxDate : 0,
						showButtonPanel: true,
						onChangeMonthYear: function(year, month, inst){
							var a = $(this).val();
							var curMonth = month;
							var curDay = a.split('/')[1];
							$(this).val(curMonth + '/' + curDay + '/' + year);
						}
					});
				break;
			}
				
		},
		add_date_picker : function(id,param){
			switch(param){
				case 1 :
					var currentDate = new Date(), currentYear = currentDate.getFullYear();
					currentYear = currentYear + 10;
					$(id).datepicker({
                		yearRange: '1900:' + currentYear,
                		changeMonth: true,
                		changeYear: true,
						showButtonPanel: true
            		}); 
				break;
				case 2 :
					// limit to current year only
					var currentDate = new Date(), currentYear = currentDate.getFullYear();
					$(id).datepicker({
                		yearRange: '1900:' + currentYear,
                		changeMonth: true,
                		changeYear: true,
						maxData : 0,
						showButtonPanel: true
            		}); 
				break;				
			}
		},
		copy_textbox_value : function(from,to){
			$(to).val($(from).val());
		},
		check_checkbox : function(this_checked, check_this){
			if($(this_checked).attr('checked')){
				$(check_this).attr('checked','checked');
			}else{
				$(check_this).removeAttr('checked');
			}
		},
		form_lock : function(id,height){
			var a = '<div class="pageLockLoader2"></div><div style="height: '+height+';" class="pageLock2"></div>';
			if($('.pageLock').length < 1){
				$(id).prepend(a);
			}else{
				$('.pageLock').remove();
				$('.pageLockLoader').remove();
			}
		},
		empty : function(mixed_var){
			var key;
    		if (mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false || typeof mixed_var === 'undefined') { return true; }
   			if (typeof mixed_var == 'object') { for (key in mixed_var) { return false; } return true; }   			
			return false;
		},
		checked : function(selector){
			if(selector.is(':checked')){return true;}else{return false;}
		},
		uniqid : function(prefix, more_entropy){
			if (typeof prefix == 'undefined') {prefix = "";}
			var retId;
			var formatSeed = function (seed, reqWidth) {
		    	seed = parseInt(seed,10).toString(16); // to hex str
		    	if (reqWidth < seed.length) { // so long we split
		        	return seed.slice(seed.length - reqWidth);
		    	}
		    if (reqWidth > seed.length) { // so short we pad
		        return Array(1 + (reqWidth - seed.length)).join('0')+seed;
		    }
		    return seed;
			};
		
			// BEGIN REDUNDANT
			if (!this.php_js) {
			    this.php_js = {};
			}
			// END REDUNDANT
			if (!this.php_js.uniqidSeed) { // init seed with big random int
		    	this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
			}	
			this.php_js.uniqidSeed++;
		
			retId  = prefix; // start with prefix, add current milliseconds hex string
			retId += formatSeed(parseInt(new Date().getTime()/1000,10),8);
			retId += formatSeed(this.php_js.uniqidSeed,5); // add seed hex string
		
			if (more_entropy) {
		    	// for more entropy we add a float lower to 10
		    	retId += (Math.random()*10).toFixed(8).toString();
			}
			return retId;
		},
		id_generator_function : function(){
			var d = new Date(),
				a = d.getDate().toString() + d.getDay().toString() + d.getFullYear().toString() + d.getHours().toString() + d.getMinutes().toString() + d.getSeconds().toString() + d.getMilliseconds(),
				b = parseInt(a) + (d.getSeconds() + d.getMilliseconds()),
				c = engine.utils.uniqid(engine.utils.uniqid(b)) + d.getMilliseconds().toString(),
				c = usba(c);
			return c;
		},
		url_encode : function(str){
			str = (str+'').toString();
    		return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');				
		},
		url_decode : function(str){
			return decodeURIComponent((str+'').replace(/\+/g, '%20'));
		}
	},
	inner_page_template : {
		member_logins_page : function(){
			if($('#memberLoginArea').length > 0){
				if ($.trim($('#members-isloggedin').text()) == "1") {
					switch ($.cookie('secure_zone')) {
						case "account_manager":
							window.location = '/administrator/administrator_home';
							break;
						case "provider":
							window.location = '/provider/provider_home';
						break
						case "vendor" :
							window.location = "/vendors/vendors_home";
						break;
					}
				}
			}
		}
	},
	intake_form : {
		form_steps_functionality : function(){
			// step 1 next button
			$('#step_1 .btn_next').bind('click', function(){
				if (engine.intake_form.validate_step_1()) {
					$('#step_1').hide();
					$('#step_2').fadeIn('slow');
					errors = "";
				}else{
					alert(errors);
				}
			});
			// step 2 next and previous buttons
			$('#step_2 .btn_previous').bind('click', function(){
				$('#step_2').hide();
				$('#step_1').fadeIn('slow');
			});
			$('#step_2 .btn_next').bind('click', function(){
				if (engine.intake_form.validate_step_2()) {
					$('#step_2').hide();
					$('#step_3').fadeIn('slow');
				}else{
					alert(errors);
				}
			});
			// step 3 next and prvious buttons
			$('#step_3 .btn_previous').bind('click', function(){
				$('#step_3').hide();
				$('#step_2').fadeIn('slow');
			});
			$('#step_3 .btn_next').bind('click', function(){
				if (engine.intake_form.validate_step_3()) {
					$('#step_3').hide();
					$('#step_4').fadeIn('slow');
				}else{
					alert(errors);
				}
			});
			// step 4 previous and submit button
			$('#step_4 .btn_previous').bind('click', function(){
				$('#step_4').hide();
				$('#step_3').fadeIn('slow');
			});
		},
		same_as_billing_address_button : function(){
			$('input[name=chk_same_as_billing]').bind('click', function(){
				if($(this).is(':checked')){
					// intake form
					$('input[name=txt_shipping_address]').val($('input[name=txt_billing_address]').val());
					$('input[name=txt_shipping_city]').val($('input[name=txt_billing_city]').val());
					$('input[name=txt_shipping_zipcode]').val($('input[name=txt_billing_zipcode]').val());	
					$('select[name=cbo_shipping_state] option').each(function(){
						if($(this).val() == $('select[name=cbo_billing_state]').val()){
							$(this).attr('selected','selected');
						}
					});
					// custom webapp form
					$('input[name=CAT_Custom_166507]').val($('input[name=txt_billing_address]').val());
					$('input[name=CAT_Custom_166508]').val($('input[name=txt_billing_city]').val());
					$('input[name=CAT_Custom_166509]').val($('select[name=txt_billing_state]').val());
					$('input[name=CAT_Custom_166510]').val($('input[name=txt_billing_zipcode]').val());
				}
			});
		},
		get_last_step_4_id : function(){
			var a = $('input[name=txt_provider_provider_name]').last(),
				b = a.attr('id').split('_'),
				c = parseInt(b[4]) + 1;
			return c;
		},
		add_step_4_field : function(){
			var new_field = "";
			last_id = engine.intake_form.get_last_step_4_id();
			new_field = "<tr class='step_4_data'>";
			new_field += "<td><input type='text' name='txt_provider_provider_name' id='txt_provider_provider_name_"+last_id+"'></td>";
			new_field += "<td><input type='text' name='txt_provider_credentials' id='txt_provider_credentials_"+last_id+"'></td>";
			new_field += "<td><input type='text' name='txt_provider_dea_number' id='txt_provider_dea_number_"+last_id+"' style='width: 70px;'></td>";
			new_field += "<td><input type='text' name='txt_provider_state_license' id='txt_provider_state_license_"+last_id+"'></td>";
			new_field += "<td><input type='text' name='txt_provider_email_address' id='txt_provider_email_address_"+last_id+"'></td>";
			new_field += "<td><input type='text' name='txt_provider_birthdate' id='txt_provider_birthdate_"+last_id+"'></td>";
			new_field += "</tr>";
			$('tr.step_4_data').last().after(new_field);
			engine.utils.add_date_picker('#txt_provider_birthdate_'+last_id,2);
		},
		bind_add_new_provider_field : function(){
			$('.btn_add_new_provider_field').live('click', function(){
				engine.intake_form.add_step_4_field();
			});
		},
		validate_step_1 : function(){
			errors = "";
			if($('#admin_account_intake_form').length > 0){
				if(engine.utils.empty($('#txt_clinic_name').val())){ errors += "Clinic Name \n"; }
				if(engine.utils.empty($('#txt_allervision_signup_date').val())){ errors += "Sign Up Date \n"; }
				if(engine.utils.empty($('#txt_business_address').val())){ errors += "Business Address \n"; }
				if(engine.utils.empty($('#txt_city').val())){ errors += "City \n"; }
				if(engine.utils.empty($('#txt_zipcode').val())){ errors += "Zip Code \n"; }
				if(!is_numeric($('#txt_zipcode').val())){ errors +="Zipcode should be numberic \n"; }
				if($('#cbo_state').val() == '-1'){ errors += 'State \n'; }
				if($('#txt_sales_representative').val() == '-1'){ errors += 'Sales Representative \n'; }
				if(engine.utils.empty($('#txt_primary_physician_owner').val())){ errors += 'Primary Physician / Owner \n'; }
				if(engine.utils.empty($('#txt_primary_physician_email_address').val())){ errors += "Primary Physician's Email Address \n"; }
				if(engine.utils.empty($('#txt_office_manager').val())){ errors += 'Office Manager \n'; }
				if(engine.utils.empty($('#txt_office_manager_email_address').val())){ errors += "Office Manager's Email Address \n"; }
				if(engine.utils.empty($('#txt_office_phone').val())){ errors += 'Office Phone \n'; }
				//if(engine.utils.empty($('#txt_allergy_counselor').val())){ errors += 'Allergy Counselor \n'; }
				//if(engine.utils.empty($('#txt_allergy_counselor_email_address').val())){ errors += "Allergy Counselor's Email Address \n"; }
				if($('#cbo_prescription_form_prices_starter').val() == "-1"){ errors += 'Starter Kit Price \n'; }
				if($('#cbo_prescription_form_prices_maintenance').val() == "-1"){errors += 'Maintenance Refill Dropper Price \n'; }
				if($('#cbo_vendor_pharmacy').val() == "-1"){ errors += 'Vendors - Pharmacy\n'; }
				if($('#cbo_vendor_supplies').val() == "-1"){ errors += 'Vendors - Supplies\n'; }
				//if($('#txt_primary_physician_email_address').val() == $('#txt_office_manager_email_address').val()){ errors += "Email Address should be unique : Primary Phsycian's Email and Office Manager's Email"; }
				//if($('#txt_primary_physician_email_address').val() == $('#txt_allergy_counselor_email_address').val()){ errors += "Email Address should be unqiue : Primary Physician's Email and Allergy Counselor's Email"; }
				//if($('#txt_office_manager_email_address').val() == $('#txt_allergy_counselor_email_address').val()){ errors += "Email Address should be unique : Office Manager's Email and Allergy Counselor's Email"; }
				//if($('#txt_office_manager_email_address').val() == $('#txt_primary_physician_email_address').val()){ errors += "Email Address should be unique : Office Manager's Email and Primary Physician's Email"; }
				//if($('#txt_allergy_counselor_email_address').val() == $('#txt_primary_phsician_email_address').val()){ errors += "Email Address should be unique : Allergy Counselor's Email and Primary Physician's Email"; }
				//if($('#txt_allergy_counselor_email_address').val() == $('#txt_office_manager_email_address').val()){ errors += "Email Address should be unique : Allergy Counselor's Email and Office Manager's Email"; }
				if(!engine.utils.empty(errors)){return false;}else{return true;}
			}
			if($('#provider_account_intake_form').length > 0){
				if(engine.utils.empty($('#txt_clinic_name').val())){ errors += "Clinic Name \n"; }
				if(engine.utils.empty($('#txt_allervision_signup_date').val())){ errors += "Sign Up Date \n"; }
				if(engine.utils.empty($('#txt_business_address').val())){ errors += "Business Address \n"; }
				if(engine.utils.empty($('#txt_city').val())){ errors += "City \n"; }
				if(engine.utils.empty($('#txt_zipcode').val())){ errors += "Zip Code \n"; }
				if($('#cbo_state').val() == '-1'){ errors += 'State \n'; }
				if($('#txt_sales_representative').val() == '-1'){ errors += 'Sales Representative \n'; }
				if(engine.utils.empty($('#txt_primary_physician_owner').val())){ errors += 'Primary Physician / Owner \n'; }
				if(engine.utils.empty($('#txt_primary_physician_email_address').val())){ errors += "Primary Physician's Email Address \n"; }
				if(engine.utils.empty($('#txt_office_manager').val())){ errors += 'Office Manager \n'; }
				if(engine.utils.empty($('#txt_office_manager_email_address').val())){ errors += "Office Manager's Email Address \n"; }
				if(engine.utils.empty($('#txt_office_phone').val())){ errors += 'Office Phone \n'; }
				//if(engine.utils.empty($('#txt_allergy_counselor').val())){ errors += 'Allergy Counselor \n'; }
				//if(engine.utils.empty($('#txt_allergy_counselor_email_address').val())){ errors += "Allergy Counselor's Email Address \n"; }
				if($('#cbo_prescription_form_prices_starter').val() == "-1"){ errors += 'Starter Kit Price \n'; }
				if($('#cbo_prescription_form_prices_maintenance').val() == "-1"){errors += 'Maintenance Refill Dropper Price \n'; }
				if($('#cbo_vendor').val() == "-1"){ errors += 'Vendors \n'; }
				if(!engine.utils.empty(errors)){return false;}else{return true;}
			}
		},
		validate_step_2 : function(){
			errors = "";	
			if($('#admin_account_intake_form').length > 0){
				if(engine.utils.empty($('#txt_billing_address').val())){ errors += 'Billing Address \n'; }
				if($('#cbo_billing_state').val() == '-1'){ errors += 'Billing State \n'; }
				if(engine.utils.empty($('#txt_billing_city').val())){ errors += "Billing City \n"; }
				if(engine.utils.empty($('#txt_billing_zipcode').val())){ errors += "Billing Zipcode"; }
				if(!is_numeric($('#txt_billing_zipcode').val())){ errors += "Billing Zipcode must be numeric. \n"; }
				if(engine.utils.empty($('#txt_shipping_address').val())){ errors += "Shipping Address \n"; }
				if(engine.utils.empty($('#txt_shipping_city').val())){ errors += "Shipping City \n"; }
				if($('#cbo_shipping_state').val() == '-1'){ errors += 'Shipping State \n'; }
				if(engine.utils.empty($('#txt_shipping_zipcode').val())){ errors += "Shipping Zipcode \n"; }
				if(!is_numeric($('#txt_shipping_zipcode').val())){ errors += "Shipping Zipcode must be numeric \n"; }
				if(engine.utils.empty($('#txt_name_on_card_0').val())){ errors += "Name on Card \n"; }
				if(engine.utils.empty($('#txt_card_number_0').val())){ errors += "Card Number \n"; }
				if($('#cbo_card_expiry_month_0').val() == '-1'){ errors += 'Card Expiry Month \n'; }
				if($('#cbo_card_expiry_year_0').val() == '-1'){ errors += 'Card Expiry Year \n'; }
				if($('#cbo_card_type_0').val() == '-1'){ errors += 'Card Type \n'; }
				if(!engine.utils.empty(errors)){return false;}else{return true;}
			}
			if($('#provider_account_intake_form').length > 0){
				if(engine.utils.empty($('#txt_billing_address').val())){ errors += 'Billing Address \n'; }
				if($('#cbo_billing_state').val() == '-1'){ errors += 'Billing State \n'; }
				if(engine.utils.empty($('#txt_billing_city').val())){ errors += "Billing City \n"; }
				if(engine.utils.empty($('#txt_billing_zipcode').val())){ errors += "Billing Zipcode \n"; }
				if(!is_numeric($('#txt_billing_zipcode').val())){ errors += "Billing Zipcode must be numeric \n"; }
				if(engine.utils.empty($('#txt_shipping_address').val())){ errors += "Shipping Address \n"; }
				if(engine.utils.empty($('#txt_shipping_city').val())){ errors += "Shipping City \n"; }
				if($('#cbo_shipping_state').val() == '-1'){ errors += 'Shipping State \n'; }
				if(engine.utils.empty($('#txt_shipping_zipcode').val())){ errors += "Shipping Zipcode \n"; }
				if(!is_numeric($('#txt_shipping_zipcode').val())){ errors += "Shipping Zipcode must be numeric \n"; }
				if(!engine.utils.empty(errors)){return false;}else{return true;}
			}
		},
		validate_step_3 : function(){
			errors = "";
			if($('#admin_account_intake_form').length > 0){
				if(!$('input[name=chk_focus_of_practice]').is(':checked')){ errors += "What is the focus of Practice? \n"; }
				if(engine.utils.empty($('#txt_years_in_practice').val())){ errors += "How many years in practice? \n"; }
				if(!$('input[name=chk_services_utilized_by_clinic]').is(':checked')){ errors += "AllerVision services utilized by clinic \n"; }
				if(engine.utils.empty($('#txt_describe_payor_mix').val())){ errors += "Describe payor mix \n"; }
				if(!engine.utils.empty(errors)){return false;}else{return true;}
			}
			if($('#provider_account_intake_form').length > 0){
				if(!$('input[name=chk_focus_of_practice]').is(':checked')){ errors += "What is the focus of Practice? \n"; }
				if(engine.utils.empty($('#txt_years_in_practice').val())){ errors += "How many years in practice? \n"; }
				if(!$('input[name=chk_services_utilized_by_clinic]').is(':checked')){ errors += "AllerVision services utilized by clinic \n"; }
				if(engine.utils.empty($('#txt_describe_payor_mix').val())){ errors += "Describe payor mix \n"; }
				if(!engine.utils.empty(errors)){return false;}else{return true;}
			}
		},
		validate_step_4 : function(){
			errors = "";
			//if(!$('#is_send_email').is(':checked')){errors += "Send login details ? \n"};
			if(engine.utils.empty($('input[name=txt_provider_provider_name]').first().val())){ errors += "Provider Name\n"; }
			if(engine.utils.empty($('input[name=txt_provider_credentials]').first().val())){ errors += "Credentials\n"; }
			if(engine.utils.empty($('input[name=txt_provider_dea_number]').first().val())){ errors += "DEA #\n"; }
			if(engine.utils.empty($('input[name=txt_provider_state_license]').first().val())){ errors += "State License #\n"; }
			if(engine.utils.empty($('input[name=txt_provider_email_address]').first().val())){ errors += "Email Address\n"; }
			if(engine.utils.empty($('input[name=txt_provider_birthdate]').first().val())){ errors += "Birthdate\n"; }
			if(!engine.utils.empty(errors)){return false;}else{return true;}
		},
		admin_intake_form : {
			generate_random_password : function(length){
				chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    			pass = "";
    			for (x = 0; x < length; x++) {
        			i = Math.floor(Math.random() * 62);
        			pass += chars.charAt(i);
    			}
    			return pass;
			},
			generate_random_username : function(length){
				chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    			user = "";
    			for (x = 0; x < length; x++) {
        			i = Math.floor(Math.random() * 62);
        			user += chars.charAt(i);
    			}
    			return user;
			},
			generate_dummy_email : function(){
				chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    			email = "";
    			for (x = 0; x < 10; x++) {
        			i = Math.floor(Math.random() * 62);
        			email += chars.charAt(i);
    			}
				email = email + '@allervision.com';				
    			return email;
			},
			generate_account_number : function(){
				var raw_account_number = $.trim($('#webapp_count').text()), account_number = '';
    			account_number = (parseInt(raw_account_number) + 1) + 2600;
                        var final_account_number='';
                        final_account_number='NAVN' + account_number;
    			return final_account_number;
			},
			encrypt_cc_details : function(){
				$('#CAT_Custom_159170').val(usba($('#CAT_Custom_159170').val())); // Name on Card 1
				$('#CAT_Custom_159171').val(usba($('#CAT_Custom_159171').val())); // CC Number 1 
				$('#CAT_Custom_159172').val(usba($('#CAT_Custom_159172').val())); // Expiry Month 1
				$('#CAT_Custom_159173').val(usba($('#CAT_Custom_159173').val())); // Expiry Year 1
				$('#CAT_Custom_159175').val(usba($('#CAT_Custom_159175').val())); // Card Type 1
				$('#CAT_Custom_159177').val(usba($('#CAT_Custom_159177').val())); // CCV Number 1
				$('#CAT_Custom_159178').val(usba($('#CAT_Custom_159178').val())); // Name On Card 2
				$('#CAT_Custom_159179').val(usba($('#CAT_Custom_159179').val())); // CC Number 2
				$('#CAT_Custom_159180').val(usba($('#CAT_Custom_159180').val())); // Expiry Month 2
				$('#CAT_Custom_159181').val(usba($('#CAT_Custom_159181').val())); // Expiry Year 2
				$('#CAT_Custom_159182').val(usba($('#CAT_Custom_159182').val())); // Card Type 2
				$('#CAT_Custom_159183').val(usba($('#CAT_Custom_159183').val())); // CCV Number 2
				$('#CAT_Custom_159184').val(usba($('#CAT_Custom_159184').val())); // Name On Card 3
				$('#CAT_Custom_159185').val(usba($('#CAT_Custom_159185').val())); // CC Number 3
				$('#CAT_Custom_159186').val(usba($('#CAT_Custom_159186').val())); // Expiry Month 3
				$('#CAT_Custom_159188').val(usba($('#CAT_Custom_159188').val())); // Expiry Year 3
				$('#CAT_Custom_159191').val(usba($('#CAT_Custom_159191').val())); // Card Type 3
				$('#CAT_Custom_159192').val(usba($('#CAT_Custom_159192').val())); // CCV Number 3
 			},
			cc_info_interactivity : function(){
				$('.btn_new_cc_field').bind('click', function(){
					if($('.credit_card_details_1').hasClass('none')){
    					$('.credit_card_details_1').fadeIn('slow').removeClass('none');
					}else{
    					$('.credit_card_details_2').fadeIn('slow');
						$('.btn_new_cc_field').remove();
					}
				});
			},
			get_step_4_data : function(){
				
				data = "<table>";
				data += "<tr style='font-weight:bold;'><td>Provider Name</td><td>Crendentials</td><td>DEA #</td><td>State License #</td><td>Email Address</td><td>Birthdate</td></tr>";
				for(i=0;i < $('.step_4_data').length;i++){
					data += "<tr>";
					data += "<td class='provider_name'>"+$('input[name=txt_provider_provider_name]').eq(i).val()+"</td>";
					data += "<td class='provider_credentials'>"+$('input[name=txt_provider_credentials]').eq(i).val()+"</td>";
					data += "<td class='provider_dea_number'>"+$('input[name=txt_provider_dea_number]').eq(i).val()+"</td>";
					data += "<td class='provider_state_license'>"+$('input[name=txt_provider_state_license]').eq(i).val()+"</td>";
					data += "<td class='provider_email_address'>"+$('input[name=txt_provider_email_address]').eq(i).val()+"</td>";
					data += "<td class='provider_birthdate'>"+$('input[name=txt_provider_birthdate]').eq(i).val()+"</td>";
					data += "</tr>";
				}
				data +="</table>";
				$('#webapp_intake_form_container #ItemDescription').val(data);
			},
			submit_webform : function(){
				engine.utils.form_lock('#admin_account_intake_form',$('#admin_account_intake_form').height());
				var generated_username = $('input[name=Username]').val(),
					generated_password = $('input[name=Password]').val();
				// register dummy email 
				$('.pageLock2').text('Generating Dummy Account...JPE2-function.js');
				$.ajax({
					type : 'POST',
					url : $('form[name=catwebformform28673]').attr('action'),
					data : 'FullName=' + $.trim($('input[name=txt_clinic_name]').val()) +
						   '&EmailAddress=' + engine.intake_form.admin_intake_form.generate_dummy_email() + 
						   '&Username=' + engine.intake_form.admin_intake_form.generate_dummy_email() +
						   '&Password=' + generated_password +
						   '&PasswordConfirm=' + generated_password +
						   '&Company=' + $.trim($('input[name=txt_clinic_name]').val()) +
						   '&WebAddress=' + $.trim($('input[name=txt_allervision_account_no]').val()) + 
						   '&HomeAddress=0',
					success : function(){
						// register primary physician
						$('.pageLock2').text('Registering Primary Physician...JPE2-functions.js');
						$.ajax({
							type : 'POST',
							url : $('form[name=catwebformform28673]').attr('action'),
							data : 'FullName=' + $.trim($('input[name=txt_primary_physician_owner]').val()) +
								   '&EmailAddress=' + $.trim($('input[name=txt_primary_physician_email_address]').val()) + 
								   '&Username=' + $.trim($('input[name=txt_primary_physician_email_address]').val()) +
								   '&Password=' + generated_password +
								   '&PasswordConfirm=' + generated_password +
						  		   '&Company=' + $.trim($('input[name=txt_clinic_name]').val()) +
								   '&WebAddress=' + $.trim($('input[name=txt_allervision_account_no]').val()) +
								   '&HomeAddress=1', 
							success: function(){
                                $('.pageLock2').text('Skip Sending Login Details to Primary Physician..JPE2-functions.js');
                                // email details to primary physician
								//primary_physician_url = 'https://bigblue007.com/bc_cloud/allervision/aller/intakeForm/admin_intake_form_mailer.php?';
								//primary_physician_url += 'FullName=' + $.trim($('input[name=txt_primary_physician_owner]').val());
								//primary_physician_url += '&EmailAddress=' + $.trim($('input[name=txt_primary_physician_email_address]').val());
								//primary_physician_url += '&Username=' + $.trim($('input[name=txt_primary_physician_email_address]').val());
								//primary_physician_url += '&Password=' + generated_password;
								//primary_physician_url += '&SendEmail=' + $('input[name=is_send_email]').val();
								//$.getScript(primary_physician_url, function(){
								//	if(response){
										$('.pageLock2').text('Registering Office Manager..JPE2-functions.js');
										// register office manager
										$.ajax({
											type : 'POST',
											url : $('form[name=catwebformform28673]').attr('action'),
											data : 'FullName=' + $.trim($('input[name=txt_office_manager]').val()) +
												   '&EmailAddress=' + $.trim($('input[name=txt_office_manager_email_address]').val()) +
												   '&Username=' + $.trim($('input[name=txt_office_manager_email_address]').val()) +
												   '&Password=' + generated_password +
												   '&PasswordConfirm=' + generated_password +
												   '&Company=' + $.trim($('input[name=txt_clinic_name]').val()) +
												   '&WebAddress=' + $.trim($('input[name=txt_allervision_account_no]').val()) +
												   '&HomeAddress=2',
											success : function(){
												$('.pageLock2').text('Skip Sending Login Details to Office Manager..JPE2..functions.js');
												// send details to office manager
												//office_manager_url = 'https://bigblue007.com/bc_cloud/allervision/aller/intakeForm/admin_intake_form_mailer.php?';
												//office_manager_url += 'FullName=' + $.trim($('input[name=txt_office_manager]').val());
												//office_manager_url += '&EmailAddress=' + $.trim($('input[name=txt_office_manager_email_address]').val());
												//office_manager_url += '&Username=' + $.trim($('input[name=txt_office_manager_email_address]').val());
												//office_manager_url += '&Password=' + generated_password;
												//office_manager_url += '&SendEmail=' + $('input[name=is_send_email]').val();
												//$.getScript(office_manager_url, function(){
												//	if(response){
														//$('.pageLock2').text('Registering Allergy Counselor');
														//register allergy Counselor
														//var allergy_counselor_password = engine.intake_form.admin_intake_form.generate_random_password(10);
														//$.ajax({
														//	type : 'POST',
														//	url : $('form[name=catwebformform28673]').attr('action'),
														//	data : 'FullName=' + $.trim($('input[name=txt_allergy_counselor]').val()) +
														//		   '&EmailAddress=' + $.trim($('input[name=txt_allergy_counselor_email_address]').val()) +
														//		   '&Username=' + $.trim($('input[name=txt_allergy_counselor_email_address]').val()) +
														//		   '&Password=' + allergy_counselor_password +
														//		   '&PasswordConfirm=' + allergy_counselor_password +
														//		   '&Company=' + $.trim($('input[name=txt_clinic_name]').val()) +
														//		   '&WebAddress=' + $.trim($('input[name=txt_allervision_account_no]').val()) +
														//		   '&HomeAddress=3',
														//	success : function(){
														//		$('.pageLock2').text('Sending Login Details to Allergy Counselor');
														//		// send details to allergy counselor
														//		allergy_counselor_url = 'https://bigblue007.com/bc_cloud/allervision/aller/intakeForm/admin_intake_form_mailer.php?';
														//		allergy_counselor_url += 'FullName=' + $.trim($('input[name=txt_allergy_counselor]').val());
														//		allergy_counselor_url += '&EmailAddress=' + $.trim($('input[name=txt_allergy_counselor_email_address]').val());
														//		allergy_counselor_url += '&Username=' + $.trim($('input[name=txt_allergy_counselor_email_address]').val());
														//		allergy_counselor_url += '&Password=' + allergy_counselor_password;
														// 		allergy_counselor_url += '&SendEmail=' + $('input[name=is_send_email]').val();
														//		$.getScript(allergy_counselor_url, function(){
														//			if(response){
																		$('.pageLock2').text('Refreshing Account Manager Session...awesome JPE2-Functions.js');
																		// relogin account manager
																		$.ajax({
																			type : 'POST', 
																			url : '/ZoneProcess.aspx?ZoneID=-1&OID='+$.trim($('#moduleOID').text())+'&OTYPE=' + $.trim($('#moduleOTYPE').text()),
																			data : 'Username=' + $.trim($('#currentUserUsername').text()) +
																				   '&Password=' + $.trim($('#currentUserPassword').text()),
																			success : function(){
																				$('.pageLock2').text('Submitting Clinic Data... Finalizing Submission');
																				$('.pageLock2').text('Encrypting risky Data..JPE2-functions.js');
																				engine.intake_form.admin_intake_form.encrypt_cc_details();
																				// submit webapp item (clinic : custom intake form)
																				$.ajax({
																					type : 'POST',
																					url : $('form[name=catcustomcontentform21833]').attr('action'),
																					data : $('form[name=catcustomcontentform21833]').serialize(),
																					success : function(){
																						$('.pageLock2').text('Encrypting and Submitting Credit Card Information');
																						// submit cc_details_form after encryption
																						$.ajax({
																							type : 'POST',
																							url : $('form[name=catcustomcontentform23612]').attr('action'),
																							data : $('form[name=catcustomcontentform23612]').serialize(),
																							success : function(){
																								$('.pageLock2').text('Done...');
																								alert('Clinic Registration Complete... Page will now return to Administrator Homepage.');
																								$('input[name=txt_clear_field]').trigger('click');
																								var a = window.location.pathname;
																								a = a.split('/')
																								if(in_array("sales_representative", a)){
																									window.location = "/sales_representative/sales_representative_home";
																								}else{
																									window.location = '/administrator/administrator_home';
																								}
																									
																							}
																						});
																						
																					}
																				});
																			}
																		});
																//	} //*
															//	}); //*
															//} // *
														//}); // *
												//	}  jpe//*
											//	});   jpe//*
											}
										});
								//	}  jpe//*
							//	});  jpe//*
							}
						});
					} 
				})
			},
			bind_submit_button : function(){
				$('.btn_submit').bind('click', function(){
					if (engine.intake_form.validate_step_4()) {
						if($('input[name=is_send_email]').is(':checked')){
								//if (engine.utils.empty($('input[name=txt_office_manager_email_address]').val())) {
								//	var generated_email = engine.intake_form.admin_intake_form.generate_dummy_email();
			  					//	$('input[name=txt_office_manager_email_address]').val(generated_email);
								//	$('input[name=CAT_Custom_166497]').val(generated_email);
								//}
								engine.utils.copy_textbox_value('#txt_allervision_signup_date', '#CAT_Custom_166484');
								engine.intake_form.admin_intake_form.get_step_4_data();
								engine.intake_form.admin_intake_form.submit_webform();
							
						}else{
							alert("Send login details ?");
						}
					}else{
						alert(errors);
					}
				});
			},
			execute_functions : function(){
				if ($('#admin_account_intake_form').length > 0) {
					$('.btn_next').button();
					$('.btn_previous').button();
					$('.btn_submit').button();
					$('input[name=txt_provider_dea_number]').css('width','70px');
/* !!WN - this stopped working in 2011	$.getScript('https://bigblue007.com/bc_cloud/allervision/aller_account_no.php', function(){
          				var generated = allervisionAccountNo;
						$('input[name=txt_allervision_account_no]').val(generated);
						$('#cc_details_container input[name=ItemName]').val(generated);
						$('input[name=CAT_Custom_166482]').val(generated);
						$('input[name=CAT_Custom_168511]').val(generated);			
    				});  !!WN */
/*				$('input[name=txt_allervision_account_no]').val(engine.intake_form.admin_intake_form.generate_account_number());
					$('#cc_details_container input[name=ItemName]').val(engine.intake_form.admin_intake_form.generate_account_number());
					$('input[name=CAT_Custom_166482]').val(engine.intake_form.admin_intake_form.generate_account_number());
					$('input[name=CAT_Custom_168511]').val(engine.intake_form.admin_intake_form.generate_account_number()); */

//!!WN Begin new account no population

var newacc='';
var newacc=engine.intake_form.admin_intake_form.generate_account_number();

$('input[name=txt_allervision_account_no]').val(newacc);
$('#cc_details_container input[name=ItemName]').val(newacc);
$('input[name=CAT_Custom_166482]').val(newacc);
$('input[name=CAT_Custom_168511]').val(newacc);
//!!WN End new account no population


					$('input[name=EmailAddress]').val(engine.intake_form.admin_intake_form.generate_dummy_email());
					$('input[name=Username]').val(engine.intake_form.admin_intake_form.generate_random_username(10));
					$('input[name=Password]').val(engine.intake_form.admin_intake_form.generate_random_password(10));
					$('input[name=txt_provider_birthdate]').each(function(){engine.utils.add_date_picker(this,2);});
					engine.utils.add_date_picker('#txt_allervision_signup_date',2);
					engine.intake_form.admin_intake_form.cc_info_interactivity();
					engine.intake_form.same_as_billing_address_button();
					engine.intake_form.admin_intake_form.bind_submit_button();
					engine.intake_form.bind_add_new_provider_field();
					engine.intake_form.form_steps_functionality();
				}
			}
		},
		provider_intake_form : {
			start_observation : function(){
				var start_observation = setInterval(function(){
					if($('#process_log .custom_search_results').length > 0){
						engine.intake_form.provider_intake_form.populate_provider_intake_form();
						engine.intake_form.provider_intake_form.stop_observation(start_observation);
						engine.secure_zone.provider_zone.welcome_message();
						$('.provider_clinic_name_header').text($.trim($('#custom_clinic_name').text()) + " ");
						$.cookie('top_welcome_link', $.trim($('#custom_clinic_name').text()));
						Cufon.refresh();
						if($('#prov_mainCont').length > 0){$(".accordion").accordion({header: "h3"});}
						if($('#pageLockLoader2').length > 0){$('#pageLockLoader2').remove();}
						if($('#pageLock2').length > 0){$('#pageLock2').remove();}
					}
				},100);
			},
			stop_observation : function(a){
				clearInterval(a);
			},
			populate_provider_intake_form : function(){
				// step 1
				$('input[name=txt_clinic_name]').val($.trim($('#custom_clinic_name').text())); // clinic name
				$('input[name=txt_allervision_account_no]').val($.trim($('#custom_allervision_account_number').text())); // allervision account number
				$('input[name=txt_business_address]').val($.trim($('#custom_business_address').text())); // business address
				$('input[name=txt_allervision_signup_date]').val($.trim($('#custom_sign_up_date').text())); // signup date
				$('input[name=txt_city]').val($.trim($('#custom_city').text())); // city
				$('select[name=cbo_state] option').each(function(){ // state
	    			if($(this).val() == $.trim($('#custom_state').text())){
	        			$(this).attr('selected','selected');      
	    			}
				});
				$('input[name=txt_zipcode]').val($.trim($('#custom_zipcode').text())); // zipcode
				$('input[name=txt_sales_representative]').val($.trim($('#custom_sales_representative').text())); // sales representative
				$('input[name=txt_affiliated_clinics]').val($.trim($('#custom_affiliated_clinic').text())); // affiliated clinics
				$('input[name=txt_distributor]').val($.trim($('#custom_distributor').text())); // distributor
				$('input[name=txt_primary_physician_owner]').val($.trim($('#custom_primary_physician_owner').text())); // primary physician
				$('input[name=txt_primary_physician_email_address]').val($.trim($('#custom_primary_physician_emailaddress').text())); // primary physician email
				$('input[name=txt_primary_physician_phone]').val($.trim($('#custom_primary_physician_phone').text())); // primary physician phone
				$('input[name=txt_office_manager]').val($.trim($('#custom_office_manager').text())); // office manager
				$('input[name=txt_office_manager_email_address]').val($.trim($('#custom_office_manager_emailaddress').text())); // office manager email
				$('input[name=txt_office_manager_phone]').val($.trim($('#custom_office_manager_phone').text())); // office manager phone
				$('input[name=txt_office_phone]').val($.trim($('#custom_office_phone').text())); // office phone
				$('input[name=txt_allergy_counselor]').val($.trim($('#custom_allergy_counselor').text())); // allergy couselor 
				$('input[name=txt_allergy_counselor_email_address]').val($.trim($('#custom_allergy_counselor_emailaddress').text())); // allergy counselor email
				$('input[name=txt_allergy_counselor_phone]').val($.trim($('#custom_allergy_counselor_phone').text())); // allergy counselor phone
				$('input[name=txt_website]').val($.trim($('#custom_website').text())); // website
				$('input[name=txt_fax]').val($.trim($('#custom_fax').text())); // fax

				// step 2
				$('input[name=txt_billing_address]').val($.trim($('#custom_billing_address').text())); // billing address
				$('input[name=txt_billing_city]').val($.trim($('#custom_billing_city').text())); // billing city
				$('select[name=cbo_billing_state] option').each(function(){ // billing state
					if($(this).val() == $.trim($('#custom_billing_state').text())){
						$(this).attr('selected','selected');
					}
				});
				$('input[name=txt_billing_zipcode]').val($.trim($('#custom_billing_zipcode').text())); // billing zipcode
				$('input[name=txt_shipping_address]').val($.trim($('#custom_shipping_address').text())); // shipping address
				$('input[name=txt_shipping_city]').val($.trim($('#custom_shipping_city').text())); // shipping city
				$('select[name=cbo_shipping_state] option').each(function(){ // shipping city
					if($(this).val() == $.trim($('#custom_shipping_state').text())){
						$(this).attr('selected','selected');
					}
				});
				$('input[name=txt_shipping_zipcode]').val($.trim($('#custom_shipping_zipcode').text())); // shipping zipcode
				// step 3 
				var focus_of_practice = $.trim($('#custom_focus_of_practice').text()).split(','), b = "";
				$('input[name=chk_focus_of_practice]').each(function(){ b += $(this).val() + ';';});
				$.each(focus_of_practice,function(i){
    				if(in_array(focus_of_practice[i], b.split(';'))){
        				$('input[name=chk_focus_of_practice]').eq(array_search(focus_of_practice[i], b.split(';'))).attr('checked','checked');
    				}
				});
				$('input[name=txt_patients_are_seen_weekly]').val($.trim($('#custom_patients_seen_weekly').text()));
				$('input[name=txt_established_patients]').val($.trim($('#custom_established_patients').text()));
				$('input[name=txt_new_patients]').val($.trim($('#custom_new_patients').text()));
				$('textarea[name=txt_special_services_offered]').val($.trim($('#custom_special_services_offered').text()));
				$('input[name=txt_years_in_practice]').val($.trim($('#custom_years_in_practice').text()));
				var services_utilized = $('#custom_services_utilized_by_clinic').text().split(','), c = '';
				$('input[name=chk_services_utilized_by_clinic]').each(function(){c += $(this).val() + ';';});
				$.each(services_utilized, function(i){
					if(in_array(services_utilized[i], c.split(';'))){
						$('input[name=chk_services_utilized_by_clinic]').eq(array_search(services_utilized[i], c.split(';'))).attr('checked','checked');
					}
				});
				$('textarea[name=txt_describe_payor_mix]').val($.trim($('#custom_describe_payor_mix').text()));
				$('textarea[name=txt_notes]').val($.trim($('#custom_notes').text()));
				// step 4
				var d = '';
				$('#custom_step_4_data .provider_name').each(function(i){
					d += "<tr class='step_4_data'>";
					d += "<td><input type='text' value='"+$.trim($('.provider_name').eq(i).text())+"' name='txt_provider_provider_name' id='txt_provider_provider_name_"+i+"'></td>";
					d += "<td><input type='text' value='"+$.trim($('.provider_credentials').eq(i).text())+"' name='txt_provider_credentials' id='txt_provider_credentials_"+i+"'></td>";
					d += "<td><input type='text' value='"+$.trim($('.provider_dea_number').eq(i).text())+"' name='txt_provider_dea_number' id='txt_provider_dea_number_"+i+"' style='width: 70px;'></td>";
					d += "<td><input type='text' value='"+$.trim($('.provider_state_license').eq(i).text())+"' name='txt_provider_state_license' id='txt_provider_state_license_"+i+"'></td>";
					d += "<td><input type='text' value='"+$.trim($('.provider_email_address').eq(i).text())+"' name='txt_provider_email_address' id='txt_provider_email_address_"+i+"'></td>";
					d += "<td><input type='text' value='"+$.trim($('.provider_birthdate').eq(i).text())+"' name='txt_provider_birthdate' id='txt_provider_birthdate_"+i+"'></td>";
					d += '</tr>';
				});
				$('#step_4_data_marker').after(d);
				$('input[name=txt_provider_birthdate]').each(function(){engine.utils.add_date_picker(this,2);});
				engine.intake_form.provider_intake_form.load_custom_account_intake_webapp();
				$('.pageLockLoader2').fadeOut('slow').remove();
				$('.pageLock2').fadeOut('slow').remove();
			},
			identify_position_and_get_value : function(){
				var position = $.trim($('#provider_position').text());
				switch(position){
					case "0" :
						// do nothing
					break;
					case "1" :
						$('#EmailAddress').val($.trim($('input[name=txt_primary_physician_email_address]').val()));
					break;
					case "2" :
						$('#EmailAddress').val($.trim($('input[name=txt_office_manager_email_address]').val()));
					break;
					case "3" :
						$('#EmailAddress').val($.trim($('input[name=txt_office_manager_email_address]').val()));
					break;
				}
			},
			get_step_4_data : function(){
				data = "<table id='provider_step_4_item_description'>";
				data += "<tr style='font-weight:bold;'><td>Provider Name</td><td>Crendentials</td><td>DEA #</td><td>State License #</td><td>Email Address</td><td>Birthdate</td></tr>";
				for(i=0;i < $('.step_4_data').length;i++){
					data += "<tr>";
					data += "<td class='provider_name'>"+$('input[name=txt_provider_provider_name]').eq(i).val()+"</td>";
					data += "<td class='provider_credentials'>"+$('input[name=txt_provider_credentials]').eq(i).val()+"</td>";
					data += "<td class='provider_dea_number'>"+$('input[name=txt_provider_dea_number]').eq(i).val()+"</td>";
					data += "<td class='provider_state_license'>"+$('input[name=txt_provider_state_license]').eq(i).val()+"</td>";
					data += "<td class='provider_email_address'>"+$('input[name=txt_provider_email_address]').eq(i).val()+"</td>";
					data += "<td class='provider_birthdate'>"+$('input[name=txt_provider_birthdate]').eq(i).val()+"</td>";
					data += "</tr>";
				}
				data +="</table>";
				if ($('#provider_step_4_item_description').length < 1) {
					$('#webapp_intake_form_container #ItemDescription').val(data);
				}
			},
			load_custom_account_intake_webapp : function(){
				$('#webapp_intake_form_container').load($('#custom_edit_button a').attr('href'));
			},
			search_custom_account_intake_webapp : function(){
				if(!engine.utils.empty($.trim($('#provider_web_address').text()))){
						$.ajax({
						type : 'POST',
						url : $('#custom_fields_search form').attr('action'),
						data : 'CAT_Custom_166482=' + $.trim($('#provider_web_address').text()),
						success : function(res){
							$('#process_log').html(res);
							engine.intake_form.provider_intake_form.start_observation();
						}
					});
				}else{
					$.post('/LogOutProcess.aspx', function(data) {
						$.cookie('vendor',null);
						$.cookie('administrator',null);
						$.cookie('provider', null);
						$.cookie('salesrep', null);
						$.cookie('sz_redir', null);
						alert('Your Session is Expired, Please re-login to continue.');
  						window.location = '/provider_zone';
					});
				}
				
			},
			bind_submit_button : function(){
				if($('#provider_account_intake_form').length > 0){
					$('.btn_submit').bind('click', function(){
						engine.intake_form.provider_intake_form.get_step_4_data();
						engine.intake_form.provider_intake_form.identify_position_and_get_value();
						engine.utils.form_lock('.la-cont',$('.la_cont').height());
						$.ajax({
							type : 'POST',
							url : $('#webapp_intake_form_container form').attr('action'),
							data : $('#webapp_intake_form_container form').serialize(),
							success : function(){
								$.ajax({
									type : 'POST',
									url : $('form[name=catupdatedetailsformform99571]').attr('action'),
									data : $('form[name=catupdatedetailsformform99571]').serialize(),
									success : function(){
										alert('Account Details Successfully Updated. Page will now reload.');
										window.location.reload(true);		
									}
								});
							}
						});
					});
				}
			},
			execute_functions : function(){
				if ($('#provider_account_intake_form').length > 0) {
					$('.btn_next').button();
					$('.btn_previous').button();
					$('.btn_submit').button();
					$('input[name=FullName]').val($.trim($('#provider_fullname').text()))
					$('input[name=EmailAddress]').val($.trim($('#provider_emailaddress').text()));
					$('input[name=Company]').val($.trim($('#provider_company').text()));
					engine.intake_form.form_steps_functionality();
					engine.intake_form.bind_add_new_provider_field();
					engine.intake_form.provider_intake_form.bind_submit_button();
				}
			}
		}
	}, 
	secure_zone : {
		administrator_zone : {
			
		},
		provider_zone : {
			welcome_message : function(){
				if ($.trim($('#custom_is_activated').text()) == '0') {
					$('#messageContainer').html('<p style="border:1px solid #6FB3DD;background-color:#D4F1FF;">Welcome to AllerVision! You can order allergy testing supplies&mdash;including antigens, MAST devices, and more&mdash;input patient prescriptions, watch training videos, download forms, and more. But first, if you haven&rsquo;t already completed the account intake form with your AllerVision sales representative, please do so now. To get started, click on the "<strong>Update Information</strong>" on the menu.</p><br><br>');
					engine.secure_zone.provider_zone.provider_navigation_link.emphasize_update_account_information();
					// update is_activated status
					$('#process_log').load($('#custom_edit_button a').attr('href'), function(){
						$('input[name=CAT_Custom_168188]').val('1');
						$.post($('#process_log form').attr('action'), $('#process_log form').serialize());
					});
				}
			},
			provider_navigation_link : {
				emphasize_update_account_information : function(){
					$('#nav_558537 li').each(function(){
    					if($.trim($(this).text()) == 'Update Account Information'){
        					$(this).css('font-weight','bold');
    					}
					});
				}
			}
		}
	}
}




var jngFunctions = {
	utils : {
		makeButton : function(id){
			$(id).button();
		},
		getCurrentDate : function(){
		    var currentDate = new Date(), 
				month = currentDate.getMonth() + 1, 
				day = currentDate.getDate(), 
				year = currentDate.getFullYear();
				 
		    if (day < 10) {day = '0' + day;} // if date is less than 10 append 0 - ex. 01 02 03
		    if (month < 10) {month = '0' + month;} // if date is less than 10 append 0 - ex. 01 02 03
		    orderDate = month + "/" + day + "/" + year;
			return orderDate;
		}, 
		stringify : function(a){
			{quoteString=function(i){var j=/["\\\x00-\x1f\x7f-\x9f]/g,l={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};if(i.match(j))return'"'+i.replace(j,function(k){var f=l[k];if(typeof f==="string")return f;f=k.charCodeAt();return"\\u00"+Math.floor(f/16).toString(16)+(f%16).toString(16)})+'"';return'"'+i+'"'};if(typeof JSON=="object"&&JSON.stringify)return JSON.stringify(a);var c=typeof a;if(a===null)return"null";if(c!="undefined"){if(c=="number"||c=="boolean")return a+"";if(c=="string")return quoteString(a);if(c=="object"){if(typeof a.toJSON=="function")return jngFunctions.utils.stringify(a.toJSON());if(a.constructor===Date){var d=a.getUTCMonth()+1;if(d<10)d="0"+d;var b=a.getUTCDate();if(b<10)b="0"+b;c=a.getUTCFullYear();var e=a.getUTCHours();if(e<10)e="0"+e;var g=a.getUTCMinutes();if(g<10)g="0"+g;var h=a.getUTCSeconds();if(h<10)h="0"+h;a=a.getUTCMilliseconds();if(a<100)a="0"+a;if(a<10)a="0"+a;return'"'+c+"-"+d+"-"+b+"T"+e+":"+g+":"+h+"."+a+'Z"'}if(a.constructor===Array){d=[];for(b=0;b<a.length;b++)d.push(jngFunctions.utils.stringify(a[b])||"null");return"["+d.join(",")+"]"}d=[];for(b in a){c=typeof b;if(c=="number")c='"'+b+'"';else if(c=="string")c=quoteString(b);else continue;if(typeof a[b]!="function"){e=jngFunctions.utils.stringify(a[b]);d.push(c+":"+e)}}return"{"+d.join(", ")+"}"}}}
		},
		addDatePicker : function(id, param){
			switch(param){
				case 1 :
					var currentDate = new Date(), currentYear = currentDate.getFullYear();
					currentYear = currentYear + 10;
					$(id).datepicker({
                		yearRange: '1900:' + currentYear,
                		changeMonth: true,
                		changeYear: true
            		}); 
				break;
				case 2 :
					// limit to current year only
					var currentDate = new Date(), currentYear = currentDate.getFullYear();
					$(id).datepicker({
                		yearRange: '1900:' + currentYear,
                		changeMonth: true,
                		changeYear: true
            		}); 
				break;				
			}
		}, 
		formLock : function(id, height){
			var a = '<div class="pageLockLoader"></div><div style="height: '+height+';" class="pageLock"></div>';
			if($('.pageLock').length < 1){
				$(id).prepend(a);
			}else{
				$('.pageLock').remove();
				$('.pageLockLoader').remove();
			}
		},
		generateRandomPassword : function(length){
			chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    		pass = "";
    		for (x = 0; x < length; x++) {
        		i = Math.floor(Math.random() * 62);
        		pass += chars.charAt(i);
    		}
    		return pass;
		},
		generateRandomUsername : function(length){
			chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    		user = "";
    		for (x = 0; x < length; x++) {
        		i = Math.floor(Math.random() * 62);
        		user += chars.charAt(i);
    		}
    		return user;
		}
	},
    memberLoginProcess: {
        // removes the cookie set by logging in
        logOutProcess: function(){
            $('#logOutLink').bind('click', function(){
                $.cookie('secure_zone', null);
				$.cookie('sz_redir', null);
				$.cookie('return_url',null);
            });
			$('.logout_link_button').bind('click', function(){
				$.cookie('secure_zone', null);
				$.cookie('sz_redir', null);
				$.cookie('return_url',null);
			});
        },
        // changes the member login link if is logged in or not
        memberLoginLink: function(isLoggedIn, fullName){
            var isLoggedIn = jQuery.trim(isLoggedIn);
            var getFullName = jQuery.trim(fullName);
            if (isLoggedIn == 1) {
                jQuery("#member-logout-link").show();
                jQuery("#member-logout-link").html("<a id='return_url' style='font-weight: bold;' href='#'>RETURN</a>| Welcome, <span class='provider_clinic_name_header'></span><a href='http://allervision.com/LogOutProcess.aspx' class='logout_link_button' id='logOutLink'><strong>LOGOUT</strong></a>");
				var a = setInterval(function(){
					if($('.provider_clinic_name_header').length > 0){
						if($.trim($('.provider_clinic_name_header').text()) == ""){
							$('.provider_clinic_name_header').text($.cookie('top_welcome_link'));
						}
						clearInterval(a);
					}
				},500);
            }
            else {
                jQuery("#member-login-link").show();
            }
        },
        secureZoneLogin: function(value){
            var $adminZone = $('#administrator-login');
            var $vendorZone = $('#vendor-login');
            var $providerZone = $('#provider-login');
                switch (value) {
                    case "0":
                        $adminZone.fadeIn('slow');
                        $vendorZone.hide();
                        $providerZone.hide();
                        break;
                    case "1":
                        $adminZone.hide();
                        $vendorZone.hide();
                        $providerZone.fadeIn('slow');
                        break;
                    case "2":
                        $adminZone.hide();
                        $vendorZone.fadeIn('slow');
                        $providerZone.hide();
                        break;
                }
        }
    },
    mainNavProcees: {
        // IE hack
        addClassMainNav: function(){
            $('#menu ul li').each(function(i){
                var index = i
                if ($(this).attr('class') == "selected") {
                    $(this).addClass('link' + (index + 1));
                }
                $(this).bind('mouseover', function(){
                    $(this).addClass('link' + (index + 1));
                });
                $(this).bind('mouseout', function(){
                    $(this).addClass('link' + (index + 1));
                });
            });
        }
    },
    footerNavProcess: {
        // adds class to footer
        addClassFooter: function(navLeft, navRight){
            $("#" + navLeft).addClass('left');
            $("#" + navRight).addClass('right');
        }
    },
    orderSuppliesScript: function(){
        $('.productListCont').each(function(i){
            var URL = $('.catalogName:eq(' + i + ') a').attr('href');
            var headers = '<div class="indiProdContHeader"><div class="prodRowHeader"><div class="prodPanel left">Panel</div><div class="prodName left">Description</div><div class="prodPrice left">Price</div><div class="prodIntQuant left">QTY</div><div class="prodAddCart left"></div><div class="clr"></div></div><div class="clr"></div></div>'
            $(this).load(URL, function(){
                if (i == 0) {
                    $('.productListCont:eq(0)').prepend(headers);
                } else if (i == 1) {
                        $('.productListCont:eq(1)').prepend(headers);
                 }
                if ($('.indiProdContHeader').length > 0) {
                    $('.prodList_loader').fadeOut('slow').remove();
                    $('.overallProductList').hide().css('left', '0px').fadeIn('slow');
                    $.getScript('/CatalystScripts/Java_OnlineShopping.js', function(){
                        console.log('Java_OnlineShopping.js is loaded');
                    });
                    $.getScript('/CatalystScripts/Java_Cookies.js', function(){
                        console.log('Java_Cookies.js is loaded');
                    });
                    /*$.getScript('/CatalystScripts/Java_Box.js', function(){
                        console.log('Java_Box.js is loaded');
                    });*/
                    $.getScript('/ajaxpro/prototype-core.ashx', function(){
                        console.log('prototype-core.ashx is loaded');
                    });
                    $.getScript('/ajaxpro/CMS.CatalogueRetrieve,Catalyst.Web.CMS.ashx', function(){
                        console.log('CMS.CatalogueRetrieve,Catalyst.Web.CMS.ashx is loaded');
                    });
                    $('.productListButton').button();
                    $('.cartSummaryLink').button();
                    $('.productSubmitInput').button();
                    $('.productTextInput').val("");
                }
            });
        });
		$('.productSubmitInput').livequery('click', function(){
			$('.productSubmitInput').button();
			$('.cartSummaryLink').button();
			$('.productTextInput').val("");
		});
    }, 
	orderSuppliesScript2 : function(){
		$('.productListCont').each(function(i){
			var URL = $('.catalogName:eq(' + i + ') a').attr('href');
			$(this).load(URL, function(){
				$('.prodList_loader').fadeOut('slow').remove();
                $('.overallProductList').hide().css('left', '0px').fadeIn('slow');
			});
		});
	},
	intakeFormProcess: {
		formLock : function(id){
			var a = '<div class="pageLockLoader"></div><div class="pageLock"></div>';
				if($('.pageLock').length < 1){
					$(id).prepend(a);
				}else{
					$('.pageLock').remove();
					$('.pageLockLoader').remove();
				}
		},
		adminForm: {
			generateAccountNo : function(){
				$("#dateToday script").remove();
        		var completeDate = $.trim($("#dateToday").text()).split(",");
        		var twoYear = ($.trim(completeDate[1]).substr("2")).toString();
				var webAppCount = (parseInt($.trim($("#webAppCount").text())) + 1).toString();
				if (webAppCount.length === 1) {
           			webAppCount = "0" + webAppCount;
        		}
				var accountNumber = twoYear + webAppCount;
        		$('#AllervisionAccount').val(accountNumber);
        		$('#CAT_Custom_144669').val(accountNumber);
			},
			generateProviderDatePicker : function(){
				$('.provBirthday').each(function(i){
        			$(this).datepicker({
			            buttonImage: '/images/calendar.gif',
			            buttonImageOnly: true,
			            changeMonth: true,
			            changeYear: true,
			            showButtonPanel: true,
			            yearRange: '1900:' + currentDate.getFullYear()
        			});
    			});
			},
			getStepFourData: function(){
				var data = "";
				data += "<table><tr><td><strong>Provider Name</strong></td><td><strong>Credentials</strong></td><td><strong>DEA #</strong></td><td><strong>License Number</strong></td><td><strong>Email Address</strong></td><td><strong>Birthday</strong></td></tr>";
			    var a = $('.providerName');
			    for (i = 0; i < a.length; i++) {
			        data += "<tr class='step4data'>";
			        data += "<td class='provName'>" + $('.providerName').eq(i).val() + "</td>"
			        data += "<td class='cred'>" + $('.credential').eq(i).val() + "</td>";
			        data += "<td class='deaNum'>" + $('.deaNumber').eq(i).val() + "</td>";
					data += "<td class='licenseNum'>" + $('.licenseNumber').eq(i).val() + "</td>";
			        data += "<td class='eadd'>" + $('.emailAddress').eq(i).val() + "</td>";
			        data += "<td class='birthday'>" + $('.provBirthday').eq(i).val() + "</td>";
			        data += "</tr>";
			    }
			    data += "</table>";
			    $('#ItemDescription').val(data);
			},
			validateProviderCred: function(){
				var e = true;
				if ($('#provProviderName_0').val() == "") {
					e = false;
				}
				if ($('#provCredential_0').val() == "") {
					e = false;
				}
				if ($('#provDeaNumber_0').val() == "") {
					e = false;
				}
				if ($('#provLicenseNumber_0').val() == "") {
					e = false;
				}
				if ($('#provEmailAddress_0').val() == "") {
					e = false;
				}
				if ($('#provBirthday_0').val() == "") {
					e = false;
				}
				return e;
			},
			populateAdditionalData: function(){
				populateFromTo('allervisionSignUpDate', 'CAT_Custom_144670');
				populateFromTo('EmailAddress', 'EmailEmailAddress');
				populateFromTo('officeManager', 'OfficeManagerFullName')
				populateFromTo('officeManagersEmailAddress', 'OfficeManagerEmail');
				populateFromTo('Password', 'AutoGeneratedPassword');
				populateFromTo('Company', 'ItemNameCC');
				jngFunctions.intakeFormProcess.adminForm.getStepFourData();
				return true;
			},
			addNewCC: function(){
				if($('.addCCInfo_2').hasClass('none')){
					$('.addCCInfo_2').fadeIn('slow').removeClass('none');
				}else{
					if($('.addCCInfo_3').hasClass('none')){
						$('.addCCInfo_3').fadeIn('slow').removeClass('none');
						$('#addnewcreditcard').hide();
					}					
				}
			},
			changeCCVal: function(){
				$('input[name=CAT_Custom_159170]').val(usba($('input[name=CAT_Custom_159170]').val()));
				$('input[name=CAT_Custom_159171]').val(usba($('input[name=CAT_Custom_159171]').val()));
				$('input[name=CAT_Custom_159172]').val(usba($('input[name=CAT_Custom_159172]').val()));
				$('input[name=CAT_Custom_159173]').val(usba($('input[name=CAT_Custom_159173]').val()));
				$('input[name=CAT_Custom_159175]').val(usba($('input[name=CAT_Custom_159175]').val()));
				$('input[name=CAT_Custom_159177]').val(usba($('input[name=CAT_Custom_159177]').val()));
				$('input[name=CAT_Custom_159178]').val(usba($('input[name=CAT_Custom_159178]').val()));
				$('input[name=CAT_Custom_159179]').val(usba($('input[name=CAT_Custom_159179]').val()));
				$('input[name=CAT_Custom_159180]').val(usba($('input[name=CAT_Custom_159180]').val()));
				$('input[name=CAT_Custom_159181]').val(usba($('input[name=CAT_Custom_159181]').val()));
				$('input[name=CAT_Custom_159182]').val(usba($('input[name=CAT_Custom_159182]').val()));
				$('input[name=CAT_Custom_159183]').val(usba($('input[name=CAT_Custom_159183]').val()));
				$('input[name=CAT_Custom_159184]').val(usba($('input[name=CAT_Custom_159184]').val()));
				$('input[name=CAT_Custom_159185]').val(usba($('input[name=CAT_Custom_159185]').val()));
				$('input[name=CAT_Custom_159186]').val(usba($('input[name=CAT_Custom_159186]').val()));
				$('input[name=CAT_Custom_159188]').val(usba($('input[name=CAT_Custom_159188]').val()));
				$('input[name=CAT_Custom_159191]').val(usba($('input[name=CAT_Custom_159191]').val()));
				$('input[name=CAT_Custom_159192]').val(usba($('input[name=CAT_Custom_159192]').val()));
			},
			submitCCInfoForm: function(){
				$.ajax({
					type : "POST",
					url : $('form[name=catcustomcontentform13508]').attr('action'),
					data : $('form[name=catcustomcontentform13508]').serialize(),
					complete : function(){
				        $.ajax({
							type : "POST",
							url : "/ZoneProcess.aspx?ZoneID=2451&OID=4792192&OTYPE=1",
							data : "Username=" + $.trim($('#currentUserUsername').text()) + "&Password=" + $.trim($('#currentUserPassword').text()),
							complete : function(){
								var url = "https://bigblue007.com/bc_cloud/allervision/aller/intakeForm/intakeFormProcess.php?";
									url += "pp=" + $.trim($('#FullName').val());
									url += "&ppe=" + $.trim($('#EmailAddress').val());
									url += "&om=" + $.trim($('#officeManager').val());
									url += "&ome=" + $.trim($('#officeManagersEmailAddress').val());
									url += "&agu=" + $.trim($.trim($('#Username').val()));
									url += "&agp=" + $.trim($('#AutoGeneratedPassword').val());
									url += "&ia=Administrator";
								$.getScript(url, function(){
									if(response){
										alert('Form Submission Complete. Page will now reload.');
										window.location.reload(true);
									}else{
										alert('Unknown Error : Please contact the developer');
										window.location = '/administrator/administrator_home';
									}
								});
							}
						});
					}
				});
			},
			submitPHPMailer: function(){
				/*var a = "http://mtiwhrilpools.bigblue007.com/aller/intakeForm/intakeFormProcess.php" +
						"?PrimaryPhysicianOwner=" +	$.trim($('#FullName').val()) +
						"&EmailEmailAddress=" +	$.trim($('#EmailAddress').val()) +
						"&OfficeManagerFullName=" +	$.trim($('#officeManager').val()) +
						"&OfficeManagerEmail=" + $.trim($('#officeManagersEmailAddress').val()) +
						"&AutoGeneratedPassword=" +	$.trim($('#AutoGeneratedPassword').val()) +
						"&intakeArea=admin";
				$('#phpMailerFrame').attr('src', a);*/
			},
			submitAllForms : function(){
				// submit webform first
				jngFunctions.intakeFormProcess.formLock('#adminAccountIntakeForm');
				$.ajax({
					type : "POST",
					url : $('form[name=catwebformform90404]').attr('action'),
					data : $('form[name=catwebformform90404]').serialize(),
					success : function(){
						// if webform is successfully submitted 
						// submit custom intake form 
						$.ajax({
							type : "POST",
							url : $('form[name=catcustomcontentform49985]').attr('action'),
							data : $('form[name=catcustomcontentform49985]').serialize(),
							success : function(){
								// if submission of custom intake form fields is completed 
								jngFunctions.intakeFormProcess.adminForm.changeCCVal();
								jngFunctions.intakeFormProcess.adminForm.submitCCInfoForm();
								// submit cc details form fields
							}
						});
					}
				});
			},
			processAdminIntake: function(){
				if (jngFunctions.intakeFormProcess.adminForm.validateProviderCred()) {
					if (jngFunctions.intakeFormProcess.adminForm.populateAdditionalData()) {
						jngFunctions.intakeFormProcess.adminForm.submitAllForms();
					}else{
						alert('Cannot find Information : - AllerVision Sign up date \n -Email Address \n - Office Manager Full Name \n - Office Manager Email Address \n');
					}
				}else{
					alert('Unable to validate Step 4 Data. Please make sure the first row are not empty.');
				}
			}
		},
		providerForm : {
			getCustomFieldsLink : function(){
				var a = $('.customField .tag_edit a').attr('href');
				return a;
			},
			populateFields : {
				populateStates : function(){
					$('#WorkState option').each(function(){
						if($(this).val() == $.trim($('.custstate:first').text()).toUpperCase()){
							$(this).attr('selected','selected');
						}
					});
				},
				stepOne : function(){
					populateFromTo('ItemName', 'Company');
					populateFromTo('CAT_Custom_144669', 'AllervisionAccount');
					populateFromTo('CAT_Custom_144671', 'allervisionSalesConsultant');
					populateFromTo('CAT_Custom_144672', 'distributor');
					populateFromTo('CAT_Custom_144673', 'affiliatedClinics');
					populateFromTo('CAT_Custom_144674', 'officeManager');
					populateFromTo('CAT_Custom_144675', 'officeManagersEmailAddress');
					populateFromTo('CAT_Custom_144676', 'officeManagersPhoneExtension');
					populateFromTo('CAT_Custom_144790', 'primaryPhysiciansPhoneExtension');
					$("#allervisionSignUpDate").datepicker("setDate", $('#CAT_Custom_144670').val());
				},
				stepTwo : function(){
					// billing address
					populateFromTo('CAT_Custom_144972', 'BillingAddress');
					populateFromTo('CAT_Custom_144973', 'BillingCity');
					populateFromTo('CAT_Custom_144974', 'BillingState');
					populateFromTo('CAT_Custom_144975', 'BillingZip');
					// shipping address
					populateFromTo('CAT_Custom_144976', 'ShippingAddress');
					populateFromTo('CAT_Custom_144977', 'ShippingCity');
					populateFromTo('CAT_Custom_144978', 'ShippingState');
					populateFromTo('CAT_Custom_144979', 'ShippingZip');
				},
				stepThree : function(){
					checkedThis('CAT_Custom_144884_0', 'whatIsTheFocusOfPractice_0');
					checkedThis('CAT_Custom_144884_1', 'whatIsTheFocusOfPractice_1');
					checkedThis('CAT_Custom_144884_2', 'whatIsTheFocusOfPractice_2');
					checkedThis('CAT_Custom_144884_3', 'whatIsTheFocusOfPractice_3');
					checkedThis('CAT_Custom_144884_4', 'whatIsTheFocusOfPractice_4');
					checkedThis('CAT_Custom_144884_5', 'whatIsTheFocusOfPractice_5');
					checkedThis('CAT_Custom_144884_6', 'whatIsTheFocusOfPractice_6');
					checkedThis('CAT_Custom_144884_7','whatIsTheFocusOfPractice_7');
					populateFromTo('CAT_Custom_144885', 'howManyPatientsAreSeenWeekly');
					populateFromTo('CAT_Custom_144886', 'establishedPatients');
					populateFromTo('CAT_Custom_144887', 'newPateints');
					populateFromTo('CAT_Custom_144889', 'howManyYearsInPractice');
					checkedThis('CAT_Custom_144890_0', 'servicesUtilizedByClinic_0');
					checkedThis('CAT_Custom_144890_1', 'servicesUtilizedByClinic_1');
					checkedThis('CAT_Custom_144890_2', 'servicesUtilizedByClinic_2');
					checkedThis('CAT_Custom_144890_3', 'servicesUtilizedByClinic_3');
					populateFromTo('CAT_Custom_144889', 'howManyYearsInPractice');
					populateFromTo('CAT_Custom_144888', 'whatSpecialServicesAreOffered');
					populateFromTo('CAT_Custom_144891', 'describePayorMix');
					populateFromTo('CAT_Custom_144892', 'notes');
					checkedThis('CAT_Custom_144893_0', 'isThisClinicNewToSlit_0');
					checkedThis('CAT_Custom_144893_1', 'isThisClinicNewToSlit_1');
					checkedThis('CAT_Custom_144894_0', 'ifNoFormerAccountOfNewConcepts_0');
					checkedThis('CAT_Custom_144894_1', 'ifNoFormerAccountOfNewConcepts_1');
				},
				extractStepFourData : function(){
					$('#stepFourDataContainer').html($('#ItemDescription').val());
				},
				stepFour : function(){
					var data = "";
					for (i = 0; i < $('.provName').length; i++) {
                		data += "<tr class='step4dataUpdate'>";
                		data += "<td><input value='" + $.trim($('.provName:eq(' + i + ')').text()) + "' name='provProviderName' id='provProviderName_" + i + "' class='provProviderName' type='text'></td>";
                		data += "<td><input value='" + $.trim($('.cred:eq(' + i + ')').text()) + "' name='provCredential' id='provCredential_" + i + "' class='provCredential' type='text'></td>";
                		data += "<td><input value='" + $.trim($('.deaNum:eq(' + i + ')').text()) + "' name='provDeaNumber' id='provDeaNumber_" + i + "' class='provDeaNumber' type='text' style='width: 90px;'></td>";
						data += "<td><input value='" + $.trim($('.licenseNumber:eq(' + i + ')').text()) + "' name='provLicenseNumber' id='provLicenseNumber_" + i + "' class='provLicenseNumber' type='text'></td>";
                		data += "<td><input value='" + $.trim($('.eadd:eq(' + i + ')').text()) + "' name='provEmailAddress' id='provEmailAddress_" + i + "' class='provEmailAddress' type='text'></td>";
                		data += "<td><input value='" + $.trim($('.birthday:eq(' + i + ')').text()) + "' name='provBirthday' id='provBirthday_" + i + "' class='provBirthday' type='text'></td>";
                		data += "</tr>";
            		}
					$('#insertStep4TableAfterThis').after(data);
				},
				getStepFour : function(){
					var data = "";
					data += "<table><tr><td><strong>Provider Name</strong></td><td><strong>Credentials</strong></td><td><strong>DEA #</strong></td><td><strong>License #</strong></td><td><strong>Email Address</strong></td><td><strong>Birthday</strong></td></tr>";
					for (i = 0; i < $('.provProviderName').length; i++) {
						data += "<tr class='step4data'>";
						data += "<td class='provName'>" + $('.provProviderName:eq(' + i + ')').val() + "</td>"
						data += "<td class='cred'>" + $('.provCredential:eq(' + i + ')').val() + "</td>";
						data += "<td class='deaNum'>" + $('.provDeaNumber:eq(' + i + ')').val() + "</td>";
						data += "<td class='licenseNumber'>" + $('.provLicenseNumber:eq(' + i + ')').val() + "</td>";
						data += "<td class='eadd'>" + $('.provEmailAddress:eq(' + i + ')').val() + "</td>";
						data += "<td class='birthday'>" + $('.provBirthday:eq(' + i + ')').val() + "</td>";
						data += "</tr>";
					}
					data += "</table>";
					$('#ItemDescription').val(data);
				},
				generateProviderDatePicker : function(){
					$('.provBirthday').each(function(i){
				        $(this).datepicker({
				            buttonImage: '/images/calendar.gif',
				            buttonImageOnly: true,
				            changeMonth: true,
				            changeYear: true,
				            showButtonPanel: true,
				            yearRange: '1900:' + currentDate.getFullYear()
				        });
    				});
				},
				changeCustomFieldFormAction : function(){
					$("#customFieldContainer form").attr('action', $("#customFieldContainer form").attr('action') + "&PageID=/provider/messages/form_details_success");
				}
			},
			loadCustomFields : function(){
				$('#customFieldContainer').load(jngFunctions.intakeFormProcess.providerForm.getCustomFieldsLink(), function(){
					jngFunctions.intakeFormProcess.providerForm.populateFields.stepOne();
					jngFunctions.intakeFormProcess.providerForm.populateFields.populateStates();
					jngFunctions.intakeFormProcess.providerForm.populateFields.stepTwo();
					jngFunctions.intakeFormProcess.providerForm.populateFields.stepThree();
					jngFunctions.intakeFormProcess.providerForm.populateFields.extractStepFourData();
					jngFunctions.intakeFormProcess.providerForm.populateFields.stepFour();
					jngFunctions.intakeFormProcess.providerForm.populateFields.generateProviderDatePicker();
					
				});
			},
			processProviderIntake: function(){
				jngFunctions.intakeFormProcess.formLock('#providerAccountIntakeForm');
				jngFunctions.intakeFormProcess.providerForm.populateFields.changeCustomFieldFormAction();
				populateFromTo('allervisionSignUpDate', 'CAT_Custom_144670');
				jngFunctions.intakeFormProcess.providerForm.populateFields.getStepFour();
				$.ajax({
					type: "POST",
					url: $('form[name=catupdatedetailsformform22364]').attr('action'),
					data: $('form[name=catupdatedetailsformform22364]').serialize(),
					success: function(response){
						// update isActivated Status to 1 
						$('#CAT_Custom_144781').val(1);
						jngFunctions.intakeFormProcess.formLock('#providerAccountIntakeForm');
						$("#customFieldContainer form").submit();
					}
				});
			}
		}
	},
	checkOutProcess : {
		ccCardType : function(val){
			var a = "";
			switch(val){
				case "1" :
					a="Visa";
					return a;
				break;
				case "2" :
					a="Master Card";
					return a;
				break;
				case "3" :
					a="Bank Card";
					return a;
				break;
				case "4" :
					a="American Express";
					return a;
				break;
				case "5" :
					a="Diners Club";
					return a;
				break;
				case "6" :
					a="JC";
					return a;
				break;
				default :
					return a;
			}
		},
		useCreditCard : function(){
			/*$('input[name=useCC]').bind('change',function(){
				switch($(this).val()){
					case "1" :
						var nym = balik($.trim($('#ngan_1').text())),
							m = balik($.trim($('#hupasBuwan_1').text())),
							y = balik($.trim($('#hupasTuig_1').text())),
							t = balik($.trim($('#cartonTipo_1').text())),
							cv = balik($.trim($('#cartonKlaroNum_1').text()));
							t = jngFunctions.checkOutProcess.ccCardType(t);
						var a = balik($.trim($('#carton_1').text())), cn = "";
						for(i=0;i < a.length - 3; i++){
							cn += str_replace(a[i],'X',a[i]);
						}
						cn += a.substr(a.length - 3, a.length);
						// labels
						$('#ccNameOnCard').text(nym);
						$('#ccCardNumber').text(cn);
						$('#ccExpiryMonth').text(m);
						$('#ccExpiryYear').text(y);
						$('#ccCardType').text(t);
						$('#ccCCVNumber').text(cv);
						$('#CardName').val(nym);
						$('#CardNumber').val(balik($.trim($('#carton_1').text())));
						$('#CardExpiryMonth').val(m);
						$('#CardExpiryYear').val(y);
						$('#CardType').val(balik($.trim($('#cartonTipo_1').text())));
						$('#CardCCV').val(cv);
					break;
					case "2" :
						var nym = balik($.trim($('#ngan_2').text())),
							m = balik($.trim($('#hupasBuwan_2').text())),
							y = balik($.trim($('#hupasTuig_2').text())),
							t = balik($.trim($('#cartonTipo_2').text())),
							cv = balik($.trim($('#cartonKlaroNum_2').text()));
							t = jngFunctions.checkOutProcess.ccCardType(t);
						var a = balik($.trim($('#carton_2').text())), cn = "";
						for(i=0;i < a.length - 3; i++){
							cn += str_replace(a[i],'X',a[i]);
						}
						cn += a.substr(a.length - 3, a.length);
						// labels
						$('#ccNameOnCard').text(nym);
						$('#ccCardNumber').text(cn);
						$('#ccExpiryMonth').text(m);
						$('#ccExpiryYear').text(y);
						$('#ccCardType').text(t);
						$('#ccCCVNumber').text(cv);
						$('#CardName').val(nym);
						$('#CardNumber').val(balik($.trim($('#carton_2').text())));
						$('#CardExpiryMonth').val(m);
						$('#CardExpiryYear').val(y);
						$('#CardType').val(balik($.trim($('#cartonTipo_2').text())));
						$('#CardCCV').val(cv);
					break;
					case "3" :
						var nym = balik($.trim($('#ngan_3').text())),
							m = balik($.trim($('#hupasBuwan_3').text())),
							y = balik($.trim($('#hupasTuig_3').text())),
							t = balik($.trim($('#cartonTipo_3').text())),
							cv = balik($.trim($('#cartonKlaroNum_3').text()));
							t = jngFunctions.checkOutProcess.ccCardType(t);
						var a = balik($.trim($('#carton_3').text())), cn = "";
						for(i=0;i < a.length - 3; i++){
							cn += str_replace(a[i],'X',a[i]);
						}
						cn += a.substr(a.length - 3, a.length);
						// labels
						$('#ccNameOnCard').text(nym);
						$('#ccCardNumber').text(cn);
						$('#ccExpiryMonth').text(m);
						$('#ccExpiryYear').text(y);
						$('#ccCardType').text(t);
						$('#ccCCVNumber').text(cv);
						$('#CardName').val(nym);
						$('#CardNumber').val(balik($.trim($('#carton_3').text())));
						$('#CardExpiryMonth').val(m);
						$('#CardExpiryYear').val(y);
						$('#CardType').val(balik($.trim($('#cartonTipo_3').text())));
						$('#CardCCV').val(cv);
					break;
				}
			});*/
		},
		populateBillShipFields: function(){
			// populates Shipping and Billing Information
			/*$.getCurrentDate('#CAT_Custom_149409');
            $.addNewDatePicker('#CAT_Custom_149406');
            $('#ShippingAddress').val($.trim($('.custShippingAddress').text()));
            $('#ShippingCity').val($.trim($('.custShippingCity').text()));
            $('#ShippingState').val($.trim($('.custShippingState').text()));
            $('#ShippingZip').val($.trim($('.custShippingZip').text()));
            $('#BillingAddress').val($.trim($('.custBillingAddress').text()));
            $('#BillingCity').val($.trim($('.custBillingCity').text()));
            $('#BillingState').val($.trim($('.custBillingState').text()));
            $('#BillingZip').val($.trim($('.custBillingZip').text())); */
		},
		identifySelected : function(val){
			var a="";
			switch(val){
				case '1' :
					a = $.trim($('#carton_1').text());
					return a;
				break;
				case '2' :
					a = $.trim($('#carton_2').text());
					return a;
				break;
				case '3' :
					a = $.trim($('#carton_3').text());
					return a;
				break;
				default :
					return a;
			}
		},
		submitCheckOut: function(theForm){
			theForm.submit();
        }
		
	},
	shoppingCartPage : {
		setCookies : function(){
			var productItemsNo = "";
			$('#gCode .productitemcell').each(function(){
				productItemsNo += $.trim($(this).text()) + ";";
			});
			var productNames = "";
			$('td:eq(2) .productitemcell').each(function(){
				productNames += $.trim($(this).text()) + ";";
			});
			var productQuantities = "";
			$('.cartInputText').each(function(){
				productQuantities += $.trim($(this).val() + ";");
			});
			$.cookie('productItemsNo',productItemsNo);
			$.cookie('productNames',productNames);
			$.cookie('productQuantities',productQuantities);
			$.cookie('placedBy',$.trim($('#members-full-name').text()));
			$.cookie('orderDate',jngFunctions.utils.getCurrentDate());
			$.cookie('clinicName',$.trim($('.tag_name:eq(0)').text()));
			$.cookie('customerUsername',$.trim($('#currentUserUsername').text()));
			$.cookie('customerPassword',$.trim($('#currentUserPassword').text()));
			$.cookie('allerVisionAccountNo',$.trim($('.custallervisionaccountnumber').text()));
			$.cookie('physicianEmail', $.trim($('.custprimaryphysiciansemailaddress').text()));
			$.cookie('officeManagerEmail', $.trim($('.custofficemanagersemailaddress').text()));
		}
	},
	prescriptionForm: {
		notPrintable: {
			prepopulateFields: function(){
				$('input[name=Company]').val($.trim($('.tag_name a').text())); // Clinic Name
				$('input[name=CAT_Custom_150813]').val($.trim($('.custallervisionaccountnumber').text())); // AllerVision Account Number
				$('input[name=WorkAddress]').val($.trim($('.custbusinessaddress').text())) // Address
				$('input[name=WorkCity]').val($.trim($('.custcity').text())) // City
				$('#WorkState option').each(function(i){
					if ($(this).val() == ($.trim($('.custstate').text())).toUpperCase()) {
						$(this).attr('selected', 'selected'); // States
					}
				});
				$('input[name=WorkZip]').val($.trim($('.custzipcode').text())); // Zipcode
				$('input[name=WorkPhone]').val($.trim($('.custofficephone').text())); // Phone
				$('input[name=WorkFax]').val($.trim($('.custfax').text())); // Fax Number
				$('input[name=EmailAddress]').val($.trim($('.custprimaryphysiciansemailaddress').text())) // Primary Physician's Email Address
				$('input[name=FullName]').val($.trim($('.custprimaryphysicianowner').text())); // Primary Physician's Full Name
				$('input[name=CAT_Custom_150828]').val(jngFunctions.utils.getCurrentDate()); // Order Date 
				// custom form - fields
				$('input[name=ItemName]').val($.trim($('.tag_name a').text())); // clinic name
				$('input[name=CAT_Custom_150833]').val($.trim($('.custallervisionaccountnumber').text())); // AllerVision Account Number
				$('input[name=CAT_Custom_150834]').val($.trim($('.custbusinessaddress').text())); // Address
				$('input[name=CAT_Custom_150835]').val($.trim($('.custcity').text())); // City
				$('input[name=CAT_Custom_150836]').val($.trim($('.custstate').text())); // State
				$('input[name=CAT_Custom_150837]').val($.trim($('.custzipcode').text())); // ZipCode
				$('input[name=CAT_Custom_150838]').val($.trim($('.custofficephone').text())); // Phone
				$('input[name=CAT_Custom_150839]').val($.trim($('.custfax').text())); // Fax Number
				$('input[name=CAT_Custom_150840]').val($.trim($('.custprimaryphysiciansemailaddress').text())); // Email Address
				$('input[name=CAT_Custom_150963]').val($.trim($('.custprimaryphysicianowner').text())); // Physicians Name
				$('input[name=CAT_Custom_150984]').val(jngFunctions.utils.getCurrentDate()) // Order Date
			},
			interactivity : {
				backToPrescriptionForm : function(){
					$('#presBacktoForm').bind('click',function(){
						$('#prescriptionPaymentForm').hide();
						$('#prescriptionFormItself').css('margin-left','75px').fadeIn('slow');	
					});
				},
				validateFields : function(type,className){
					type.toLowerCase();
					switch (type) {
						case "textbox":
							$('input[type=text].' + className).each(function(i){
							if ($(this).val() == "") {
								errors += $(this).attr('alt') + "\n";
								}
							});
							if (errors != "") {	return false;} else {return true;}
						break;
						case "textarea":
							$('textarea.' + className).each(function(i){
								if ($(this).val() == "") {
									errors += $(this).attr('alt') + "\n";
								}
							});
							if (errors != ""){	return false;}else {return true;}
						break;
						case "checkbox":
							$('input[type=checkbox].' + className).each(function(i){
								if (!$('input[type=checkbox][name=' + $(this).attr('name') + '].' + className).attr('checked')) {
									if (i % 2 == 0) {
							    		errors += $('input[type=checkbox][name=' + $(this).attr('name') + '].' + className).attr('alt') + "\n";
									}
								}
							});
						break;
					}
				},
				addDatePickers : function(){
					jngFunctions.utils.addDatePicker('#CAT_Custom_150828',2);
					jngFunctions.utils.addDatePicker('#CAT_Custom_150826',2);	
				},
				orderSets : function(id){
					switch(id){
						case "chk_order-sets_0" :
						 	if($('#chk_order-sets_0').attr('checked')){
								// disables checkbox and textbox
								$('#chk_order-sets_1').removeAttr('checked').attr('disabled','disabled');
								$('#CAT_Custom_150943').attr('disabled','disabled').val(""); // disables chk_order-set_1's textbox
								$('#CAT_Custom_150985_0').attr('checked','checked') // checked custom fields	
								$('#Amount').val($.trim($('.custpresFormStart').text())); // starter kit
								$('#Amount2').val($.trim($('.custpresFormStart').text())); // starter kit custom
								$.cookie('prescription_for','Starter Set');
							}else{
								// removes disabled attribute
								$('#chk_order-sets_1').removeAttr('disabled');
								$('#CAT_Custom_150943').removeAttr('disabled'); 
								$('#CAT_Custom_150943').attr('disabled','disabled').val("");
								$('#CAT_Custom_150985_0').removeAttr('checked');
								$('#Amount').val("");
								$('#Amount2').val("");
								$.cookie('prescription_for','');
							}
						break;
						case "chk_order-sets_1" :
							if($('#chk_order-sets_1').attr('checked')){
								$('#CAT_Custom_150985_1').attr('checked','checked');
								$('#chk_order-sets_0').attr('disabled','disabled').removeAttr('checked');
								$('#CAT_Custom_150943').removeAttr('disabled');
								$('#Amount').val($.trim($('.custpresFormMain').text())); //maintenance
								$('#Amount2').val($.trim($('.custpresFormMain').text())); //maintenance custom
								$.cookie('prescription_for','Maintenance Dropper');
							}else{
								$('#chk_order-sets_0').removeAttr('disabled');
								$('#CAT_Custom_150985_1').removeAttr('checked');
								$('#CAT_Custom_150943').attr('disabled','disabled').val("");
								$('#Amount').val("");
								$('#Amount2').val("");
								$.cookie('prescription_for','');
							}
						break;
					}
				},
				proceedToPayment: function(){
					$('#proceedToPayment').bind('click',function(){
						jngFunctions.prescriptionForm.notPrintable.interactivity.validateFields('textbox','required');
						jngFunctions.prescriptionForm.notPrintable.interactivity.validateFields('textarea','required');
						jngFunctions.prescriptionForm.notPrintable.interactivity.validateFields('checkbox','required');
						if(errors == ""){
							$('#prescriptionFormItself').hide();
							$('#prescriptionPaymentForm').css('margin-left','75px').fadeIn('slow');	
						}else{
							alert(errors);	
							errors = ""; // declared as Global					
						}
					});
				},
				processPayment : function(){
						// determine if clinic is EL-Paso if yes set cookie vendor as compound else greer;
						populateFromTo('CAT_Custom_150826','CAT_Custom_150982');
						populateFromTo('CAT_Custom_150828','CAT_Custom_150984');
						// set cookies 
						$.cookie('order_date',$('#CAT_Custom_150828').val()); // order date
						$.cookie('patient_name',$('#CAT_Custom_150824').val()); // patient name
						$.cookie('physicianName',$('#FullName').val()); // physicians name
						$.cookie('physicianEmail', $('#EmailAddress').val()); // physicians email
						$.ajax({
							type : "POST",
							url : $('form[name=catcustomcontentform3653]').attr('action'),
							data : $('form[name=catcustomcontentform3653]').serialize(),
							complete : function(){
								$('#catwebformform40318').submit();
								cnr = "";					
							}
						});
						
				},
				setAdditionalInfo : function(){
					$.cookie('customerUsername',$.trim($('#customerUsername').text()));
					$.cookie('customerPassword',$.trim($('#customerPassword').text()));
					$.cookie('clinic_name',$.trim($('#Company').val()));
					if($.trim($('.isElPaso').text()).toLowerCase() == "no"){
						$('#notes_other_clinics').show();
						$('#notes_other_clinics').show();
						$.cookie('vendor','Compounding Pharmacy');
					}else if($.trim($('.isElPaso').text()).toLowerCase() == "yes"){
						$('#notes_el_paso_clinics').show();
						$.cookie('vendor','Greer Pharmacy');
					}
				}
			},
			functionality : function(){
				jngFunctions.prescriptionForm.notPrintable.prepopulateFields();
				jngFunctions.prescriptionForm.notPrintable.interactivity.setAdditionalInfo();
				jngFunctions.prescriptionForm.notPrintable.interactivity.addDatePickers();
				jngFunctions.prescriptionForm.notPrintable.interactivity.proceedToPayment();
				jngFunctions.prescriptionForm.notPrintable.interactivity.backToPrescriptionForm();
				jngFunctions.checkOutProcess.useCreditCard();
			}
		},
		confirmationPage : {
			returnCurrentTime: function(){
				var a = new Date();
		        var curHour = a.getHours();
		        var curMin = a.getMinutes();
		        var curSec = a.getSeconds();
		        var curMil = a.getMilliseconds();
		        if (curHour < 10) {
		            curHour = "0" + curHour;
		        }
		        if (curMin < 10) {
		            curMin = "0" + curMin;
		        }
		        if (curSec < 10) {
		            curSec = "0" + curSec;
		        }
		        return curHour + curMin + curSec + curMil;
			},
			updatePrescriptionCustomForm : function(){
				$('#onLoadContainer').load($('#pres_edit a:eq(0)').attr('href'), function(){
		            // update payment status to 1
		            $('#CAT_Custom_153810').val(1);
		            // adds generated RX Number to textbox
		            $('#CAT_Custom_150964').val(jngFunctions.prescriptionForm.confirmationPage.generateRXNumber());
		            $('#ItemName').val($('#ItemName').val() + ";" + jngFunctions.prescriptionForm.confirmationPage.returnCurrentTime());
		            $.ajax({
		                type: "POST",
		                url: $("form[name=" + $('#onLoadContainer form').attr('name') + "]").attr('action'),
		                data: $("form[name=" + $('#onLoadContainer form').attr('name') + "]").serialize(),
		                success: function(response){
							$('.pageLockLoader2').remove();
							$('.pageLock2').remove();
							$('#successMessage').fadeIn('slow');
		                    $.timer(5000, function(timer){
								window.location = '/provider/individual_patient_prescription_for_immunotherapy_print';
		                        timer.stop();
		                    });
		                }
		            });
		        });
			},
			generateRXNumber : function(){
				var $a = parseInt($.trim($('#webAppCount').text()));
        		var $b = $a + 2000;
        		var $c = "HP" + $b.toString(); // HP2001;
        		return $c;
			},
			setMailerIframeSource : function(){
				var a = "https://bigblue007.com/bc_cloud/allervision/aller/prescriptionForm/prescriptionConfirmation.php?";
					a += "orderDate=" + $.cookie('order_date');
					a += "&rxNumber=" + $.trim(jngFunctions.prescriptionForm.confirmationPage.generateRXNumber());
					a += "&clinicName=" + $.cookie('clinic_name');
					a += "&vendor=" + $.cookie('vendor'); 
					a += "&prescriptionFor=" + $.cookie('prescription_for');
					a += "&primaryPhysicianEmail=" + $.cookie('physicianEmail');
					a += "&patientName=" + $.cookie('patient_name');
					a += "&physicianName=" + $.cookie('physicianName');
				$("#pres_confirmation_mailer_frame").attr('src', a);
				console.log($a); 
				/* $.getScript(a, function(){
					if(response){
						alert(response);
					}else{
						alert(response);
					}
				});*/
		   		
			},
			setAdditionalCookies : function(){
				$.cookie('RXNumber',jngFunctions.prescriptionForm.confirmationPage.generateRXNumber());
				return jngFunctions.prescriptionForm.confirmationPage.generateRXNumber();
			},
			addOrdersToVendor : function(){
				// @1. login AllerVision Website Data Communication Account to be able to view / get vendors list
				$.ajax({
					type : "POST",
					url : "/ZoneProcess.aspx?ZoneID=3145&OID="+ $.trim($('#formOID').text()) + "&OTYPE=" + $.trim($('#formOTYPE').text()),
					data : "Username=data&Password=CTPEXO",
					success : function(){
						// @2. load the vendors_list page to the extracontainer
						$('#extraContainer').load('/vendors_list', function(){
							// @3. Match Vendor Cookie to .vendCompany in vendors_list page
							$('.vendorsListContainer').each(function(i){
								if($.trim($('.vendorsListContainer .vendCompany').eq(i).text()) == $.trim($.cookie('vendor'))){
									// @4. if match set vendor's username and password as cookie
									$.ajax({
										type : "POST",
										url : "/ZoneProcess.aspx?ZoneID=3102&OID=" + $.trim($('#formOID').text()) + "&OTYPE=" + $.trim($('#formOTYPE').text()),
										data : "Username=" + $.trim($('.vendorsListContainer .vendUsername').eq(i).text()) +
											   "&Password=" + $.trim($('.vendorsListContainer .vendPassword').eq(i).text()),
										success : function(){
											// 6. Add Orders to Vendor Using Ajax 
											$.ajax({
												type: "POST",
												url : "/CustomContentProcess.aspx?CCID=7093&OID=" + $.trim($('#formOID').text()) + "&OTYPE=" + $.trim($('#formOTYPE').text()),
												data : "ItemName=" + jngFunctions.prescriptionForm.confirmationPage.returnCurrentTime() + " - " + $.cookie('clinic_name') +
													   "&CAT_Custom_158722=" + $.cookie('order_date') +
													   "&CAT_Custom_158723=" + $.trim(jngFunctions.prescriptionForm.confirmationPage.generateRXNumber()) +
													   "&CAT_Custom_158724=" + $.cookie('clinic_name') +
													   "&CAT_Custom_160230=" + $.cookie('patient_name') +
													   "&CAT_Custom_160232=" + $.cookie('prescription_for') +
													   "&CAT_Custom_160242=Prescription",
												success : function(){
													/*
													var a = "http://mtiwhrilpools.bigblue007.com/aller/prescriptionForm/prescriptionConfirmation.php?";
														a += "orderDate=" + $.cookie('order_date');
														a += "&rxNumber=" + $.trim(jngFunctions.prescriptionForm.confirmationPage.generateRXNumber());
														a += "&clinicName=" + $.cookie('clinic_name');
														a += "&vendor=" + $.cookie('vendor'); 
														a += "&prescriptionFor=" + $.cookie('prescription_for');
														a += "&primaryPhysicianEmail=" + $.cookie('physicianEmail');
														a += "&patientName=" + $.cookie('patient_name');
														a += "&physicianName=" + $.cookie('physicianName');
													$.getScript(a, function(){
														if(response){
															$.ajax({
																type : "POST",
																url : "/ZoneProcess.aspx?ZoneID=2452&OID=" +  $.trim($('#formOID').text()) + "&OTYPE=" + $.trim($('#formOTYPE').text()),
																data : "Username=" + $.trim($.cookie('customerUsername')) +
																	   "&Password=" + $.trim($.cookie('customerPassword')),
																success : function(){
																	jngFunctions.prescriptionForm.confirmationPage.updatePrescriptionCustomForm();		
																}
															});
														}else{
															alert(response);
														}
													});*/
													jngFunctions.prescriptionForm.confirmationPage.setMailerIframeSource();
													// 7. Re-login Customer Using the $.cookie('customerUsername') for username and for password $.cookie('customerPassword')
													$.ajax({
														type : "POST",
														url : "/ZoneProcess.aspx?ZoneID=2452&OID=" +  $.trim($('#formOID').text()) + "&OTYPE=" + $.trim($('#formOTYPE').text()),
														data : "Username=" + $.trim($.cookie('customerUsername')) +
															   "&Password=" + $.trim($.cookie('customerPassword')),
														success : function(){
															jngFunctions.prescriptionForm.confirmationPage.updatePrescriptionCustomForm();		
														}
													});
												}
											});
										}
									});									
								}
							});
						});							
					}
				});
				
			},
			processPage : function(){
				jngFunctions.prescriptionForm.confirmationPage.addOrdersToVendor();
			}
		
		},
		printable : {
			prepopulateFields : function(){
				$('input[name=txt_medical-office-clinic]').val($.trim($('.pres_name:eq(0)').text().split(';')[0])); // Clinic Name
				$('input[name=txt_allervision-account-number]').val($.trim($('.pres_allervisionaccount:eq(0)').text())); // AllerVision Account Number
				$('input[name=txt_address]').val($.trim($('.pres_address:eq(0)').text())); // Address
				$('input[name=txt_city]').val($.trim($('.pres_city:eq(0)').text())); // City
				$('#txt_state option').each(function(){ // state
					if($(this).val() == $.trim($('.pres_state:eq(0)').text())){
						$(this).attr('selected','selected'); // add selected attribute if the value of custom state is equal to $(this).val()
					}
				});
				$('input[name=txt_zip]').val($.trim($('.pres_zip:eq(0)').text())); // Zipcode
				$('input[name=txt_phone]').val($.trim($('.pres_phone:eq(0)').text())); // Phone Number
				$('input[name=txt_fax]').val($.trim($('.pres_fax:eq(0)').text())); // Fax Number
				$('input[name=txt_email]').val($.trim($('.pres_emailaddress:eq(0)').text())); // Email Address
				$('input[name=txt_physician-name]').val($.trim($('.pres_physicianname:eq(0)').text())); // Physician Name
				$('input[name=txt_allervision-rx-number]').val($.trim($('.pres_allervisionwebsiterx:eq(0)').text())); // RX Number
				$('input[name=txt_tree-1]').val($.trim($('.pres_treecol1:eq(0)').text())); // Tree Column 1
				$('input[name=txt_tree-2]').val($.trim($('.pres_treecol2:eq(0)').text())); // Tree Column 2
				$('input[name=txt_grass-1]').val($.trim($('.pres_grasscol1:eq(0)').text())); // Grass Column 1
				$('input[name=txt_grass-2]').val($.trim($('.pres_grasscol2:eq(0)').text())); // Grass Column 2
				$('input[name=txt_mold-1]').val($.trim($('.pres_moldcol1:eq(0)').text())); // Mold Column 1
				$('input[name=txt_mold-2]').val($.trim($('.pres_moldcol2:eq(0)').text())); // Mold Column 2
				$('input[name=txt_weed-1]').val($.trim($('.pres_weedcol1:eq(0)').text())); // Weed Column 1
				$('input[name=txt_weed-2]').val($.trim($('.pres_weedcol2:eq(0)').text())); // Weed Column 2
				$('input[name=txt_epidermals-1]').val($.trim($('.pres_epidermalscol1:eq(0)').text())); // Epidermals Column 1
				$('input[name=txt_epidermals-2]').val($.trim($('.pres_epidermalscol2:eq(0)').text())); // Epidermals Column 2
				$('input[name=txt_insect-inhalant-1]').val($.trim($('.pres_insectandinhalantcol1:eq(0)').text())); // Insects and Inhalants Column 1
				$('input[name=txt_insect-inhalant-1]').val($.trim($('.pres_insectandinhalantcol2:eq(0)').text())); // Insects and Inhalants Column 2
				if($('.pres_comprehensivemix').eq(0).text() != ""){
					$('input[name=chk_comprehensive_mix]').attr('checked'); // Comprehensive Mix Checkbox
				}
				switch($.trim($('.pres_shipto').eq(0).text())){
					case "Physician's Office" :
						$('#order_ship-to_0').attr('checked','checked');
						$('#order_ship-to_1').remove();
						$('#shipping_info_patients_home').remove();
					break
					case "Patient's Home" :
						$('#order_ship-to_1').attr('checked','checked');
						$('#order_ship-to_0').remove();
						$('#shipping_info_physicians_office').remove();
					break
				}
				$('input[name=txt_patient-information-name]').val($.trim($('.pres_patientinformationname:eq(0)').text())); // Patient Information Name
				$('#txt_patient-information-address').val($.trim($('.pres_patientinformationaddress:eq(0)').text())); // Patient Information Address
				$('input[name=txt_patient-information-phone]').val($.trim($('.pres_patientinformationphone:eq(0)').text())); // Patient Information Phone Number
				$('input[name=txt_patient-information-dob]').val($.trim($('.pres_patientinformationdob:eq(0)').text())); // Patient Information Date Of Birth
				$('input[name=txt_drug-allergies]').val($.trim($('.pres_patientinformationdrugallergies:eq(0)').text())); // Drug Allergies
				$('input[name=txt_order-date]').val($.trim($('.pres_orderdate:eq(0)').text())); // Order Date
				switch($.trim($('.pres_ordersets').eq(0).text())){
					case "Starter Set" :
						$('#chk_order-sets_0').attr('checked','checked');
						$('#chk_order-sets_1').remove();
						$('#order_set_maintenance_dropper_refill').remove();
					break;
					case "Maintenance Dropper Refill #" :
						$('#chk_order-sets_1').attr('checked','checked');
						$('#chk_order-sets_0').remove();
					break;
				}
				$('input[name=txt_maintenance-dropper-refill-number]').val($.trim($('.pres_maintenancedropperrefill:eq(0)').text())); // Maintenance Refill Dropper
				$('#txt_notes-and-special-instructions').val($.trim($('.pres_notesandspecialinstructions:eq(0)').text())); // Notes and Special Instructions
			}, 
			printPageButton : function(){
				$('#PrintButton').bind('click', function(){
					$("#prescription_formCont").printElement();	
				});
				
			},
			printPageAuto : function(){
				$("#prescription_formCont").printElement();
			},
			functionality : function(){
				jngFunctions.prescriptionForm.printable.prepopulateFields();
				jngFunctions.prescriptionForm.printable.printPageButton();
				jngFunctions.prescriptionForm.printable.printPageAuto();
			}
		}
	}, 
	providerZoneInteractivity : {
		orderSuppliesLink: {
			returnCurrentState: function(){
				return $.trim($('#workState').text()).toUpperCase();
			},
			isNextCare: function(){
				return $.trim($('.isNextCare').text()).toLowerCase();
			},
			isElPaso: function(){
				return $.trim($('.isElPaso').text()).toLowerCase();
			},
			isActive : function(){
				return $('.isActive').text();
			},
			setOrderSuppliesLink: function(link){
				$('.orderSupplies a').attr('href', link);
			},
			setOrderFormLink : function(link){
				$('#OrderFormLink').attr('href', link);
			},
			determineLink: function(){
				jngFunctions.providerZoneInteractivity.orderSuppliesLink.setOrderSuppliesLink('/provider/master_matrix');
				jngFunctions.providerZoneInteractivity.orderSuppliesLink.setOrderFormLink('/provider/master_matrix');
				$.cookie('orderFormVendor','Greer Pharmacy');
			}
		},
		welcomeMessage : function(){
			if(jngFunctions.providerZoneInteractivity.orderSuppliesLink.isActive() == 0){
				$('#nav_558537 li a').each(function(){
	                if ($.trim($(this).text()) == "Update Account Information") {
	                    $(this).css('font-weight', 'bold');
	                }
	            });
	            $('#messageContainer').html('<p style="border:1px solid #6FB3DD;background-color:#D4F1FF;">Welcome to AllerVision! You can order allergy testing supplies&mdash;including antigens, MAST devices, and more&mdash;input patient prescriptions, watch training videos, download forms, and more. But first, if you haven&rsquo;t already completed the account intake form with your AllerVision sales representative, please do so now. To get started, click on the "<strong>Update Information</strong>" on the menu.</p><br><br>');
				/*if ($('.tag_name a:eq(0)').text() != "") {
					$.getScript("http://mtiwhrilpools.bigblue007.com/aller/provider/providerProcess.php?data=" + jngFunctions.utils.stringify({
						'ClinicName': $.trim($('.tag_name a:eq(0)').text())
					}), function(){
						if (response == 1) {
							console.log('Notification Sent');
						}
					});
				}else{
					$.getScript("http://mtiwhrilpools.bigblue007.com/aller/provider/providerProcess.php?data=" + jngFunctions.utils.stringify({
						'ClinicName': $.trim($('#members-full-name').text())
					}), function(){
						if (response == 1) {
							console.log('Notification Sent');
						}
					});
				}*/
			}
		}
	},
	vendorZone : {
		loadForms : function(id){
			$('#' + id + ' .vendLog').load($('#' + id + ' .vend_additional a').attr('href'), function(){
				if($('#' + id + ' .vendLog form input[name=CAT_Custom_161691]').is(':checked')){
					$('#' + id + ' .vendConfirmReceived').remove();
				}
				if($('#' + id + ' .vendLog form input[name=CAT_Custom_161692]').is(':checked')){
					$('#' + id + ' .vendConfirmShipped').remove();
				}
			});
		},
		confirmReceived : function(id){
			var form = $('#' + id + ' .vendLog form');
			switch ($.trim($('#' + id + ' .vend_orderType').text()).toLowerCase()) {
				case "supplies" :
					$('#confirmationDisplayArea').hide();
					var prodNames = $.trim($('#' + id + ' .supp_productNames').text());
					var prodQuant = $.trim($('#' + id + ' .supp_productQuantities').text());
					var confirmationForm = "<center><form onsubmit='return false;' name='received_confirmation_form' id='received_confirmation_form'><table border='0'>";
						confirmationForm += "<tr><td colspan='10' align='center' style='background-color: #cccccc; font-weight: bold;'>Received - Confirmation Form</td></tr>"
						confirmationForm += "<tr><td style='height: 20px' colspan='10'></td></tr>";
						confirmationForm += "<tr><td><strong>AllerVision Order # :</strong></td><td><label id='allerVisionOrder'>" + $.trim($('#' + id + ' .vend_rxNumber').text()) + "</label></td></tr>";
						confirmationForm += "<tr><td><strong>Customer # : </strong></td><td><label id='customerNumber'>" + $.trim($('#' + id + ' .supp_allervisionAccountNo').text()) + "</label></td></tr>";
						confirmationForm += "<tr><td style='height: 20px' colspan='10'></td></tr>";
						confirmationForm += "<tr><td colspan='10' align='center' style='background-color: #cccccc; font-weight: bold;'>Summary Of Order</td></tr>";
						confirmationForm += "<tr><td colspan='' align='center' style='background-color: #cccccc; font-weight: bold;'>Product Name(s)</td><td colspan='' align='center' style='background-color: #cccccc; font-weight: bold;'>Quantities</td></tr>";
						for (i = 0; i < prodNames.split(';').length; i++) {
							confirmationForm += "<tr><td align='center'>" + prodNames.split(';')[i] + "</td><td align='center'>" + prodQuant.split(';')[i] + "</td></tr>";
						}
						confirmationForm += "<tr><td style='height: 20px' colspan='10'><hr></td></tr>";
						confirmationForm += "<tr><td><strong>Estimated Delivery Date : </strong></td><td><input type='text' name='txt_estimatedDeliveryDate' id='txt_estimatedDeliveryDate'></td></tr>";
						confirmationForm += "<tr><td style='height: 20px' colspan='10'><hr></td></tr>";
						confirmationForm += "<tr><td></td><td><a href='javascript: void(0);' id='closeFrame' class='jQbutton'>X</a><a class='jQbutton' href='javascript: void(0);' id='btn_confirmReceived'>Confirm Received</a></td></tr>";
						confirmationForm += "</table></form></center><br><br>";
					$('#confirmationDisplayArea').html(confirmationForm).fadeIn('slow').highlightFade();
					jngFunctions.utils.makeButton('.jQbutton');
					jngFunctions.utils.addDatePicker('#txt_estimatedDeliveryDate',1);
					$('#closeFrame').bind('click', function(){
						$('#confirmationDisplayArea').fadeOut();
					});
					$('#btn_confirmReceived').bind('click', function(){
						jngFunctions.utils.formLock('#confirmationDisplayArea', $('.la-cont').height() + "px");
						$.getScript('https://bigblue007.com/bc_cloud/allervision/aller/vendor/vendorProcess.php?data=' + jngFunctions.utils.stringify({
									'avOr' : $.trim($('#' + id + ' .vend_rxNumber').text()),
									'cNo' : $.trim($('#' + id + ' .supp_allervisionAccountNo').text()),
									'pin' : $.trim($('#' + id + ' .supp_productItemsNo').text()),
									'pn' : $.trim($('#' + id + ' .supp_productNames').text()),
									'pq' : $.trim($('#' + id + ' .supp_productQuantities').text()),
									'pe' : $.trim($('#' + id + ' .vend_physicianEmail').text()),
									'oe' : $.trim($('#' + id + ' .vend_offmanagerEmail').text()),
									'pf' : $.trim($('#' + id + ' .vend_prescriptionFor').text()),
									'patient' : $.trim($('#' + id + ' .vend_patientName').text()),
									'edd' : $('input[name=txt_estimatedDeliveryDate]').val(),
									'st' : 'supplies',
									'cnfrm' : 'received'
						}), function(){
							if (response) {
								$('#' + id + ' input[name=CAT_Custom_161691]').attr('checked','checked');
								$.ajax({
									type : "POST",
									url : $('#' + id + ' .vendLog form').attr('action'),
									data : $('#' + id + ' .vendLog form').serialize(),
									success : function(){
										jngFunctions.utils.formLock('#confirmationDisplayArea', $('.la-cont').height() + "px");
										$('#btn_confirmReceived').hide();
										alert('Order has been confirmed, A Notification Email will be sent to the Customer.');
										window.location.reload(true);
									}
								});
							}
						});
					});
				break;
				case "prescription" :
					$('#confirmationDisplayArea').hide();
					var presConfirmationReceived = '<center><form id="received_confirmation_form" name="received_confirmation_form" onsubmit="return false;">';
			    		presConfirmationReceived += '<table border="0"><tbody>';
						presConfirmationReceived += '<tr><td align="center" style="background-color: #cccccc; font-weight: bold;" colspan="10">Received - Confirmation Form</td></tr>';
						presConfirmationReceived += '<tr><td colspan="10" style="height: 20px;"></td></tr>';
						presConfirmationReceived += '<tr><td><strong>Prescription # :</strong></td><td><label id="allerVisionOrder">'+ $.trim($('#' + id + ' .vend_rxNumber').text()) +'</label></td></tr>';
						presConfirmationReceived += '<tr><td><strong>Customer # : </strong></td><td><label id="customerNumber">'+ $.trim($('#' + id + ' .supp_allervisionAccountNo').text()) +'</label></td></tr>';
						presConfirmationReceived += '<tr><td colspan="10" style="height: 20px;"></td></tr>';
						presConfirmationReceived += '<tr><td align="center" style="background-color: #cccccc; font-weight: bold;" colspan="10">Summary of Prescription</td></tr>';
						presConfirmationReceived += '<tr><td><strong>Patient Name : </strong></td><td>'+ $.trim($('#' + id + ' .vend_patientName').text()) +'</td></tr>';
						presConfirmationReceived += '<tr><td><strong>Prescription For : </strong></td><td>'+ $.trim($('#' + id + ' .vend_prescriptionFor').text()) +'</td></tr>';
						presConfirmationReceived += '<tr><td colspan="10" style="height: 20px;"></td></tr>';
						presConfirmationReceived += '<tr><td><strong>Estimated Delivery Date : </strong></td><td><input type="text" id="txt_estimatedDeliveryDate" name="txt_estimatedDeliveryDate"></td></tr>';
						presConfirmationReceived += '<tr><td colspan="10" style="height: 20px;"><hr></td></tr>';
						presConfirmationReceived += '<tr><td></td><td><a href="javascript: void(0);" id="closeFrame" class="jQbutton">X</a><a class="jQbutton" href="javascript: void(0);" id="btn_confirmReceived">Confirm Received</a></td></tr>';
						presConfirmationReceived += '</table></form></center><br><br>';
					$('#confirmationDisplayArea').html(presConfirmationReceived).fadeIn('slow').highlightFade();
					jngFunctions.utils.makeButton('.jQbutton');
					jngFunctions.utils.addDatePicker('#txt_estimatedDeliveryDate',1);
					$('#closeFrame').bind('click', function(){
						$('#confirmationDisplayArea').fadeOut();
					});
					$('#btn_confirmReceived').bind('click', function(){
						jngFunctions.utils.formLock('#confirmationDisplayArea', $('.la-cont').height() + "px");
						$.getScript('https://bigblue007.com/bc_cloud/allervision/aller/vendor/vendorProcess.php?data=' + jngFunctions.utils.stringify({
									'avOr' : $.trim($('#' + id + ' .vend_rxNumber').text()),
									'cNo' : $.trim($('#' + id + ' .supp_allervisionAccountNo').text()),
									'pin' : $.trim($('#' + id + ' .supp_productItemsNo').text()),
									'pn' : $.trim($('#' + id + ' .supp_productNames').text()),
									'pq' : $.trim($('#' + id + ' .supp_productQuantities').text()),
									'pe' : $.trim($('#' + id + ' .vend_physicianEmail').text()),
									'oe' : $.trim($('#' + id + ' .vend_offmanagerEmail').text()),
									'pf' : $.trim($('#' + id + ' .vend_prescriptionFor').text()),
									'patient' : $.trim($('#' + id + ' .vend_patientName').text()),
									'edd' : $('input[name=txt_estimatedDeliveryDate]').val(),
									'st' : 'prescription',
									'cnfrm' : 'received'
						}), function(){
							if (response) {
								$('#' + id + ' input[name=CAT_Custom_161691]').attr('checked','checked');
								$.ajax({
									type : "POST",
									url : $('#' + id + ' .vendLog form').attr('action'),
									data : $('#' + id + ' .vendLog form').serialize(),
									success : function(){
										jngFunctions.utils.formLock('#confirmationDisplayArea', $('.la-cont').height() + "px");
										$('#btn_confirmReceived').hide();
										alert('Order has been confirmed, A Notification Email will be sent to the Customer.');
										window.location.reload(true);
									}
								});
							}
						});
					});
				break;
			}
		},
		confirmShipped : function(id){
			var form = $('#' + id + ' .vendLog form');
			var prodNames = $.trim($('#' + id + ' .supp_productNames').text());
			var prodQuant = $.trim($('#' + id + ' .supp_productQuantities').text());
			switch($.trim($('#' + id + ' .vend_orderType').text()).toLowerCase()){
				case "supplies" :
					$('#confirmationDisplayArea').hide();
					var suppConfirmationShipped = "<center><div style='margin: 0 auto; padding: 0;'><table width='500px;' border='0'>";
						suppConfirmationShipped += "<tr><td colspan='20' style='font-weight: bold;background-color:#cccccc;text-align:center;'>Shipped - Confirmation Form</td></tr>";
						suppConfirmationShipped += "<tr><td colspan='20' style='height:20px;'></td></tr>";
						suppConfirmationShipped += "<tr><td><strong>AllerVision Order # : </strong></td><td>"+$.trim($('#' + id + ' .vend_rxNumber').text())+"</td></tr>";
						suppConfirmationShipped += "<tr><td><strong>Customer # : </strong></td><td>"+$.trim($('#' + id + ' .supp_allervisionAccountNo').text())+"</td></tr>";
						suppConfirmationShipped += "<tr><td colspan='20' style='height:20px;'></td></tr>";
						suppConfirmationShipped += "<tr><td colspan='20' style='background-color: #cccccc;' align='center'><strong>Summary of Order</strong></td></tr>";
						suppConfirmationShipped += "<tr><td align='center' style='background-color: #cccccc;'><strong>Product Name(s)</strong></td><td align='center' style='background-color: #cccccc;'><strong>Quantities</strong></td></tr>";
						for (i = 0; i < prodNames.split(';').length; i++) {
							suppConfirmationShipped += "<tr><td align='center'>" + prodNames.split(';')[i] + "</td><td align='center'>" + prodQuant.split(';')[i] + "</td></tr>";
						}
						suppConfirmationShipped += "<tr><td colspan='20' style='height:20px;'></td></tr>";
						suppConfirmationShipped += "<tr><td><strong>Date Shipped : </strong></td><td align='center'><input type='text' name='txtDateShipped' id='txtDateShipped'></td></tr>";
						suppConfirmationShipped += "<tr><td><strong>Estimate Delivery Date : </strong></td><td align='center'><input type='text' name='txtEstimatedDeliveryDate' id='txtEstimatedDeliveryDate'></td></tr>";
						suppConfirmationShipped += "<tr><td><strong>Shipped Via : </strong></td><td align='center'><input type='text' name='txtShippedVia' id='txtShippedVia'></td></tr>";
						suppConfirmationShipped += "<tr><td><strong>Tracking Number : </strong></td><td align='center'><input type='text' name='txtTrackingNumber' id='txtTrackingNumber'></td></tr>";
						suppConfirmationShipped += "<tr><td><strong>Sent to : </strong></td><td align='center'><input type='text' name='txtSentTo' id='txtSentTo'></td></tr>";
						suppConfirmationShipped += "<tr><td><strong>Number Of Packages : </strong></td><td align='center'><input type='text' name='txtNumberOfPackeges' id='txtNumberOfPackages'></td></tr>";
						suppConfirmationShipped += "<tr><td colspan='20' style='height:20px;'></td></tr>";
						suppConfirmationShipped += "<tr><td></td><td align='center'><a class='jQButton' href='javascript: void(0);' id='btnClose'>X</a><a class='jQButton' href='javascript: void(0);' id='btnConfirmShipped'>Confirm Shipped</a></td></tr>";
						suppConfirmationShipped += "</table>";
						suppConfirmationShipped += "</div></center><br><br>";
					$('#confirmationDisplayArea').html(suppConfirmationShipped).fadeIn('slow').highlightFade();
					jngFunctions.utils.makeButton('.jQButton');
					jngFunctions.utils.addDatePicker('#txtDateShipped',1);
					jngFunctions.utils.addDatePicker('#txtEstimatedDeliveryDate',1);
					$('#btnClose').bind('click', function(){
						$('#confirmationDisplayArea').fadeOut();
					});
					$('#btnConfirmShipped').bind('click', function(){
						jngFunctions.utils.formLock('#confirmationDisplayArea', $('.la-cont').height() + "px");
						$.getScript('https://bigblue007.com/bc_cloud/allervision/aller/vendor/vendorProcess.php?data=' + jngFunctions.utils.stringify({
									'avOr' : $.trim($('#' + id + ' .vend_rxNumber').text()),
									'cNo' : $.trim($('#' + id + ' .supp_allervisionAccountNo').text()),
									'pin' : $.trim($('#' + id + ' .supp_productItemsNo').text()),
									'pn' : $.trim($('#' + id + ' .supp_productNames').text()),
									'pq' : $.trim($('#' + id + ' .supp_productQuantities').text()),
									'pe' : $.trim($('#' + id + ' .vend_physicianEmail').text()),
									'oe' : $.trim($('#' + id + ' .vend_offmanagerEmail').text()),
									'pf' : $.trim($('#' + id + ' .vend_prescriptionFor').text()),
									'patient' : $.trim($('#' + id + ' .vend_patientName').text()),
									'dateShipped' : $('input[name=txtDateShipped]').val(),
									'edd' : $('input[name=txt_estimatedDeliveryDate]').val(),
									'shippedVia' : $('input[name=txtShippedVia]').val(),
									'trackingNo' : $('input[name=txtTrackingNumber]').val(),
									'sentTo' : $('input[name=txtSentTo]').val(),
									'noPackages' : $('input[name=txtNumberOfPackages]').val(),
									'st' : 'supplies',
									'cnfrm' : 'shipped'
						}), function(){
							if (response) {
								$('#' + id + ' input[name=CAT_Custom_161692]').attr('checked','checked');
								$.ajax({
									type : "POST",
									url : $('#' + id + ' .vendLog form').attr('action'),
									data : $('#' + id + ' .vendLog form').serialize(),
									success : function(){
										jngFunctions.utils.formLock('#confirmationDisplayArea', $('.la-cont').height() + "px");
										$('#btnConfirmShipped').hide();
										alert('Order has been confirmed, A Notification Email will be sent to the Customer.');
										window.location.reload(true);
									}
								});
							}
						});
					});
				break;
				case "prescription" :
					
				break;
			}
		},
		UpdateOrderStatus : function(){
			alert($('#' + id + ' .vendLog form').attr('name'));
		},
		CloseFrame : function(){
			$('#confirmationDisplayArea').hide();
		}
	}
}
function closeFrame(){
	//alert('test');
	alert(window.location.href);
	//$('#confirmationDisplayArea').hide();
}
var currentDate = new Date();
// random password generator
jQuery.randomPassword = function(length){
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    pass = "";
    for (x = 0; x < length; x++) {
        i = Math.floor(Math.random() * 62);
        pass += chars.charAt(i);
    }
    return pass;
}
// form validation and navigation functions
var isEmpty = 0;
var checkedAll = 0;
// form validation
jQuery.validateForm = function(id){
    isEmpty = 0;
    var fieldID = new Array();
    var fieldName = new Array();
    var fieldType = new Array();
    $(id + " input").each(function(i){
        fieldID[i] = "#" + $(this).attr('id');
        fieldName[i] = $(this).attr('name');
        fieldType[i] = $(this).attr('type');
        if (fieldType[i] == "text") {
            if ($.validationEngine.loadValidation(fieldID[i])) {
                if (fieldID[i] == "#EmailAddress" || fieldID[i] == "#officeManagersEmailAddress") {
                    $.validationEngine.buildPrompt(fieldID[i], "This field is required. <br> Invalid Email Address.", "error");
                    closeBalloon();
                }
                else 
                    if (fieldID[i] == "#WorkPhone") {
                        $.validationEngine.buildPrompt(fieldID[i], "This field is required.", "error");
                    }
                    else {
                        $.validationEngine.buildPrompt(fieldID[i], "This field is required.", "error");
                        closeBalloon();
                    }
                isEmpty++;
            }
            else {
                $.validationEngine.closePrompt(fieldID[i]);
                closeBalloon();
            }
        }
    });
}

jQuery.checkCheckboxes = function(name){
    if ($('input[name=' + name + ']:checked').length > 0) {
        return true;
    }
    else {
        return false;
    }
}

// form navigation
jQuery.formNav = function(from, to){
    closeBalloon();
    switch (from) {
        case "#step1":
            if (from == "#step1") {
                $.validateForm(from);
                if (isEmpty === 0) {
                    $(from).hide();
                    $(to).fadeIn('slow');
                    $(to).highlightFade();
                }
            }
            else {
                if (isEmpty === 0) {
                    $(from).hide();
                    $(to).fadeIn('slow');
                    $(to).highlightFade();
                }
            }
            break;
        case "#step2":
            if (from == "#step2") {
                $.validateForm(from);
                if (isEmpty === 0) {
                    $(from).hide();
                    $(to).fadeIn('slow');
                    $(to).highlightFade();
                }
            }
            else {
                if (isEmpty === 0) {
                    $(from).hide();
                    $(to).fadeIn('slow');
                    $(to).highlightFade();
                }
            }
            break;
        case "#step3":
            if (from == "#step3") {
                if ($('.validateCheckbox:checked').length > 0) {
                    if ($('.validateOption1:checked').length > 0) {
                        if ($('.validateCheckbox1:checked').length > 0) {
                            $.validateForm(from);
                            if (isEmpty === 0) {
                                $(from).hide();
                                $(to).fadeIn('slow');
                                $(to).highlightFade();
                            }
                        }
                        else {
                            $.validationEngine.buildPrompt('#ifNoError', "This field is required <br> Please select an option. ", "error");
                        }
                    }
                    else {
                        $.validationEngine.buildPrompt('#slitError', "This field is required <br> Please select an option. ", "error");
                    }
                }
                else {
                    $.validationEngine.buildPrompt('#checkboxErrCont', "This field is required <br> Please select an option. ", "error");
                }
            }
            else {
                if (isEmpty === 0) {
                    $(from).hide();
                    $(to).fadeIn('slow');
                    $(to).highlightFade();
                }
            }
            break;
        case "#step4":
            $(from).hide();
            $(to).fadeIn('slow');
            $(to).highlightFade();
            break;
    }
}

// end of form validation and navigation functions and more
jQuery.showLargeImg = function(val){
    $.facebox({
        image: val
    });
}

jQuery.showLargeImg2 = function(source){
    jQuery.facebox({
        image: source
    });
}


jQuery.faqInteractivity = function(){
    var a = $('.faq-question a');
    var b = $('.faq-question .faq-details .answer');
    $(a).each(function(){
        if ($.trim($(this).text()) == 'Preparing Skin Test FAQs') {
            $(this).addClass('skin-test-faq');
            $(this).html('<h6>' + $(this).text() + '</h6>');
            Cufon.replace('.faq-question a h6');
            $(this).trigger('onclick').siblings('div').find('div.answer').attr('class', 'answer1');
            //$('#skin-test-faq')
        }
    });
    $('.in-question a').live('click', function(){
        $('.individual_question .in-ans').each(function(){
            $(this).show();
        });
    });
}

jQuery.initMapHighlight = function(){
    jQuery.fn.maphilight.defaults = {
        fill: true,
        fillColor: 'DEECF6',
        fillOpacity: 0.4,
        stroke: true,
        strokeColor: '2aa1f7',
        strokeOpacity: 0.6, 
		strokeOpacity: 1,
        strokeWidth: 1,
        fade: true,
        alwaysOn: false
    }
    jQuery('.map').maphilight({
        fade: false
    });
}

jQuery.initScrollPane = function(){
    $('#contents-container').jScrollPane({
        showArrows: true
    });
}


jQuery.preloadImages = function(){
    for (var i = 0; i < arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}
jQuery.getLastBirthdayFieldID = function(){
    var lastBirthdayField = $('.provBirthday').last();
    var lastBirthdayIDSplit = lastBirthdayField.attr('id').split('_');
    var lastBirthdayID = lastBirthdayIDSplit[1];
    return lastBirthdayID;
}

jQuery.addNewField = function(){
    var lastID = parseInt($.getLastBirthdayFieldID()) + 1;
    $('tr.step4data').last().after("<tr class='step4data'><td><input type='text' alt='Provider Name' class='provProviderName' name='provProviderName' id='provProviderName_"+lastID+"'></td><td><input type='text' alt='Credentials' class='provCredential' name='provCredential' id='provCredential_"+lastID+"'></td><td><input type='text' alt='DEA #' style='width: 90px;' class='provDeaNumber' name='provDeaNumber' id='provDeaNumber_"+lastID+"'></td><td><input type='text' name='provLicenseNumber' class='licenseNumber' id='licenseNumber_"+lastID+"'></td><td><input type='text' alt='Email Address' class='provEmailAddress' name='provEmailAddress' id='provEmailAddress_"+ lastID +"'></td><td><input type='text' alt='Birthday' class='provBirthday' name='provBirthday' id='provBirthday_" + lastID + "'></td></tr>");
    $('#provBirthday_' + lastID).datepicker({
        buttonImage: '/images/calendar.gif',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        yearRange: '1900:' + currentDate.getFullYear()
    });
}
jQuery.addNewFieldUpdate = function(){
    var lastID = parseInt($.getLastBirthdayFieldID()) + 1;
    $('tr.step4dataUpdate').last().after("<tr class='step4dataUpdate'><td><input type='text' alt='Provider Name' class='provProviderName' name='provProviderName' id='provProviderName_"+lastID+"'></td><td><input type='text' alt='Credentials' class='provCredential' name='provCredential' id='provCredential_"+lastID+"'></td><td><input type='text' alt='DEA #' class='provDeaNumber' name='provDeaNumber' id='provDeaNumber_"+lastID+"'  style='width:90px;'></td><td><input type='text' name='provLicenseNumber' class='licenseNumber' id='licenseNumber_"+lastID+"'></td><td><input type='text' alt='Email Address' class='provEmailAddress' name='provEmailAddress' id='provEmailAddress_"+lastID+"'></td><td><input type='text' alt='Birthday' class='provBirthday' name='provBirthday' id='provBirthday_" + lastID + "'></td></tr>");
    $('#provBirthday_' + lastID).datepicker({
        buttonImage: '/images/calendar.gif',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        yearRange: '1900:' + currentDate.getFullYear()
    });
}

jQuery.addNewDatePicker = function(id){
    $(id).datepicker({
        showOn: 'button',
        buttonImage: '/images/calendar.gif',
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        yearRange: '1900:' + currentDate.getFullYear()
    });
}
jQuery.getCurrentDate = function(id){
    var currentDate = new Date();
    var month = currentDate.getMonth() + 1;
    var day = currentDate.getDate();
    var year = currentDate.getFullYear();
    var orderDate = "";
    if (day < 10) {
        day = '0' + day;
    }
    if (month < 10) {
        month = '0' + month;
    }
    orderDate = month + "/" + day + "/" + year;
    $(id).val(orderDate);
}
jQuery.returnCurrentDate = function(){
    var currentDate = new Date();
    var month = currentDate.getMonth() + 1;
    var day = currentDate.getDate();
    var year = currentDate.getFullYear();
    var orderDate = "";
    if (day < 10) {
        day = '0' + day;
    }
    if (month < 10) {
        month = '0' + month;
    }
    orderDate = month + "/" + day + "/" + year;
    return orderDate;
}


function popFromBusinessAdd(name){
    switch ($('input[name=' + name + ']').val()) {
        case "sameBilling":
            if ($('input[name=' + name + ']').attr('checked')) {
                $('#BillingAddress').val($('#WorkAddress').val());
                $('#CAT_Custom_144972').val($('#WorkAddress').val());
				$('#BillingCity').val($('#WorkCity').val());
				$('#CAT_Custom_144973').val($('#WorkCity').val());
                $('#BillingState').val($('#WorkState').val());
				$('#CAT_Custom_144974').val($('#WorkState').val());
                $('#BillingZip').val($('#WorkZip').val());
				$('#CAT_Custom_144975').val($('#WorkZip').val());
            }
            else {
                $('#BillingAddress').val("");
				$('#CAT_Custom_144972').val("");
                $('#BillingCity').val("");
				$('#CAT_Custom_144973').val();
                $('#BillingState').val("");
				$('#CAT_Custom_144974').val("");
                $('#BillingZip').val("");
				$('#CAT_Custom_144975').val("");
            }
            break;
        case "sameShipping":
            if ($('input[name=' + name + ']').attr('checked')) {
                $('#ShippingAddress').val($('#WorkAddress').val());
				$('#CAT_Custom_144977').val($('#WorkAddress').val());
                $('#ShippingCity').val($('#WorkCity').val());
				$('#CAT_Custom_144978').val($('#WorkCity').val());
                $('#ShippingState').val($('#WorkState').val());
				$('#CAT_Custom_144978').val($('#WorkState').val());
                $('#ShippingZip').val($('#WorkZip').val());
				$('#CAT_Custom_144979').val($('#WorkZip').val());
            }
            else {
                $('#ShippingAddress').val("");
				$('#CAT_Custom_144977').val("");
                $('#ShippingCity').val("");
				$('#CAT_Custom_144978').val("");
                $('#ShippingState').val("");
				$('#CAT_Custom_144978').val("");
                $('#ShippingZip').val("");
				$('#CAT_Custom_144979').val("");
            }
            break;
    }
}

function isEmpty(mixed_var){
    // source phpjs.org
    var key;
    if (mixed_var === "" ||
    mixed_var === 0 ||
    mixed_var === "0" ||
    mixed_var === null ||
    mixed_var === false ||
    typeof mixed_var === 'undefined') {
        return true;
    }
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }
    
    return false;
}

function jsucfirst(str){
    // Makes a string's first character uppercase  
    // version: 1006.1915
    // discuss at: http://phpjs.org/functions/ucfirst    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: ucfirst('kevin van zonneveld');
    // *     returns 1: 'Kevin van zonneveld'    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}

// close balloon on click function
function closeBalloon(){
    $('.formError').click(function(){
        $('.formError').fadeOut();
    });
}

function isChecked(name){
    if ($(name).attr('checked')) {
        return false;
    }
    else {
        return true;
    }
}

// this function is used to insert the data into the update details form
function insertStep4Data(){
    var a = $('.provName');
    var data = "";
    for (i = 0; i < a.length; i++) {
        data += "<tr class='step4dataUpdate'>";
        data += "<td><input value='" + $.trim($('.provName:eq(' + i + ')').text()) + "' type='text' name='provProviderName' id='provProviderName' class='provProviderName'></td>";
        data += "<td><input value='" + $.trim($('.cred:eq(' + i + ')').text()) + "' type='text' name='provCredential' id='provCredential' class='provCredential'></td>";
        data += "<td><input value='" + $.trim($('.deaNum:eq(' + i + ')').text()) + "' type='text' name='provDeaNumber' id='provDeaNumber' class='provDeaNumber'></td>";
        data += "<td><input value='" + $.trim($('.eadd:eq(' + i + ')').text()) + "' type='text' name='provEmailAddress' id='provEmailAddress' class='provEmailAddress'></td>";
        data += "<td><input value='" + $.trim($('.birthday:eq(' + i + ')').text()) + "' type='text' name='provBirthday' id='provBirthday' class='provBirthday'></td>";
        data += "</tr>";
    }
    $('#insertStep4TableAfterThis').after(data);
}

function checkedThis(ifThisCheck, checkThisAlso){
    if ($('#' + ifThisCheck).attr('checked')) {
        $('#' + checkThisAlso).attr('checked', 'true');
    }
    else {
        $('#' + checkThisAlso).removeAttr('checked');
    }
}

// add field function for provider in allervision intake form
function providers_addField(){
    $('tr.pnone:first').removeClass('pnone').hide().highlightFade().fadeIn('slow');
}

function showLostPassForm(){
    $("#lost-password-form").fadeIn('slow');
}

// navigation animation and functionalities
function navFunction(from, to){
    $('#' + from).hide();
    $("#" + to).fadeIn('slow');
    $("#" + to).highlightFade();
}

function populateFromTo(fromThis, toThis){
    $('#' + toThis).val($('#' + fromThis).val());
}

// hide radio on click
function hidehide(radioClicked, showThis){
    if ($(radioClicked + ":checked").length == 1) {
        $(showThis).fadeIn('slow');
        $(showThis).highlightFade();
    }
    else {
        $(showThis).fadeOut('slow');
    }
}

function hideValErrorCont(){
    $('#validationErrorCont').fadeOut('slow');
}

function showLargeImg(source){
    $.facebox({
        image: source
    });
}

// get emailAdd and pass to username field 
function getEmail(emailID){
    // bc form
    $('#Username').val($(emailID).val());
    $('#Username2').val($(emailID).val());
}

// step 4 data
function getStep4Data(){
    var data = "";
    data += "<table>";
    data += "<tr>";
    data += "<td><strong>Provider Name</strong></td>";
    data += "<td><strong>Credentials</strong></td>";
    data += "<td><strong>DEA #</strong></td>";
    data += "<td><strong>Email Address</strong></td>";
    data += "<td><strong>Birthday</strong></td>";
    data += "</tr>";
    var a = $('.providerName');
    for (i = 0; i < a.length; i++) {
        data += "<tr class='step4data'>";
        data += "<td class='provName'>" + $('.providerName:eq(' + i + ')').val() + "</td>"
        data += "<td class='cred'>" + $('.credential:eq(' + i + ')').val() + "</td>";
        data += "<td class='deaNum'>" + $('.deaNumber:eq(' + i + ')').val() + "</td>";
        data += "<td class='eadd'>" + $('.emailAddress:eq(' + i + ')').val() + "</td>";
        data += "<td class='birthday'>" + $('.provBirthday:eq(' + i + ')').val() + "</td>";
        data += "</tr>";
    }
    data += "</table>";
    $('#ItemDescription').val(data);
}

// step 4 data provider update
function getStep4DataUpdate(){
    var data = "";
    data += "<table>";
    data += "<tr>";
    data += "<td><strong>Provider Name</strong></td>";
    data += "<td><strong>Credentials</strong></td>";
    data += "<td><strong>DEA #</strong></td>";
    data += "<td><strong>Email Address</strong></td>";
    data += "<td><strong>Birthday</strong></td>";
    data += "</tr>";
    var a = $('.provProviderName');
    for (i = 0; i < a.length; i++) {
        data += "<tr class='step4data'>";
        data += "<td class='provName'>" + $('.provProviderName:eq(' + i + ')').val() + "</td>"
        data += "<td class='cred'>" + $('.provCredential:eq(' + i + ')').val() + "</td>";
        data += "<td class='deaNum'>" + $('.provDeaNumber:eq(' + i + ')').val() + "</td>";
        data += "<td class='eadd'>" + $('.provEmailAddress:eq(' + i + ')').val() + "</td>";
        data += "<td class='birthday'>" + $('.provBirthday:eq(' + i + ')').val() + "</td>";
        data += "</tr>";
    }
    data += "</table>";
    $('#ItemDescription').val(data);
}

// DW Preloader
function MM_swapImgRestore(){ //v3.0
    var i, x, a = document.MM_sr;
    for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) 
        x.src = x.oSrc;
}

function MM_preloadImages(){ //v3.0
    var d = document;
    if (d.images) {
        if (!d.MM_p) 
            d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
        for (i = 0; i < a.length; i++) 
            if (a[i].indexOf("#") != 0) {
                d.MM_p[j] = new Image;
                d.MM_p[j++].src = a[i];
            }
    }
}

function MM_findObj(n, d){ //v4.01
    var p, i, x;
    if (!d) 
        d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) 
        x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++) 
        x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) 
        x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) 
        x = d.getElementById(n);
    return x;
}

function MM_swapImage(){ //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments;
    document.MM_sr = new Array;
    for (i = 0; i < (a.length - 2); i += 3) 
        if ((x = MM_findObj(a[i])) != null) {
            document.MM_sr[j++] = x;
            if (!x.oSrc) 
                x.oSrc = x.src;
            x.src = a[i + 2];
        }
}

// test form submit
function submitThisForm(theForm){
    // validate step4 first before submitting the form
    if ($('input[name=provProviderName]:eq(0)').val() == "" || 
		$('input[name=provCredential]:eq(0)').val() == "" || 
		$('input[name=provDeaNumber]:eq(0)').val() == "" ||
    	$('input[name=provEmailAddress]:eq(0)').val() == "" ||
    	$('input[name=provBirthday]:eq(0)').val() == "") {
        $.validationEngine.buildPrompt('#provNameErr', "Must have atleast 1 Provider | Credential | Dea # | Email Address | Birthday . ", "error");
    } else {
        populateFromTo('allervisionSignUpDate', 'CAT_Custom_144670');
        populateFromTo('EmailAddress', 'EmailEmailAddress');
        populateFromTo('officeManager', 'OfficeManagerFullName')
        populateFromTo('officeManagersEmailAddress', 'OfficeManagerEmail');
        populateFromTo('Password', 'AutoGeneratedPassword');
		populateFromTo('Company','ItemNameCC');
        $('form[name=phpForm]').submit()
        var topHeight = "-" + $('.la-cont').height();
        var paddingTop = $('.la-cont').height() / 2;
        var imageLoader = '<img style="border:10px solid #000;" src="/images/ajax-loader2.gif">';
        $('.la-cont').append("<div id='lockScreen'></div>");
        $('#lockScreen').css('height', $('.la-cont').height()).css('width', $('.la-cont').width()).css('top', topHeight + "px").css('padding-top', paddingTop + "px").append(imageLoader);
        getStep4Data();
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "/FormProcessv2.aspx?WebFormID=31040&OID={module_oid}&OTYPE={module_otype}&EID={module_eid}&CID={module_cid}&JSON=1&SAR=False",
            data: $('form[name=' + theForm + ']').serialize(),
            success: function(response){
                if (response.FormProcessV2Response.success) {
                    $('form[name=catcustomcontentform49985]').submit()
                }
            },
            error: function(errResponse){
                $('#lockScreen').remove();
            }
        });
        return false;
    }
}

function generateDatePickerOnLoad(){
    $('.provBirthday').each(function(i){
        $(this).datepicker({
            buttonImage: '/images/calendar.gif',
            buttonImageOnly: true,
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            yearRange: '1900:' + currentDate.getFullYear()
        });
    });
}

function validate(type, className){
    type.toLowerCase();
    switch (type) {
        case "textbox":
            $('input[type=text].' + className).each(function(i){
                if ($(this).val() == "") {
                    errors += $(this).attr('alt') + "\n";
                }
            });
            if (errors != "") {
                return false;
            }
            else {
                return true;
            }
            break;
        case "textarea":
            $('textarea.' + className).each(function(i){
                if ($(this).val() == "") {
                    errors += $(this).attr('alt') + "\n";
                }
            });
            if (errors != "") {
                return false;
            }
            else {
                return true;
            }
            break;
        case "checkbox":
            $('input[type=checkbox].' + className).each(function(i){
                if (!$('input[type=checkbox][name=' + $(this).attr('name') + '].' + className).attr('checked')) {
                    if (i % 2 == 0) {
                        errors += $('input[type=checkbox][name=' + $(this).attr('name') + '].' + className).attr('alt') + "\n";
                    }
                }
            });
            break;
    }
}

function isCreditCard( CC )
 {                        
      if (CC.length > 19)
           return (false);

      sum = 0; mul = 1; l = CC.length;
      for (i = 0; i < l; i++)
      {
           digit = CC.substring(l-i-1,l-i);
           tproduct = parseInt(digit ,10)*mul;
           if (tproduct >= 10)
                sum += (tproduct % 10) + 1;
           else
                sum += tproduct;
           if (mul == 1)
                mul++;
           else
                mul--;
      }
      if ((sum % 10) == 0)
           return (true);
      else
           return (false);
 }

function augustfilter() {
var chkdate="0";
var chkdate=$('#custom_sign_up_date').text().substr(-2,2);
if (chkdate>"0") {
if (chkdate < "11") {  
$('.orderSupplies').css('display','block');
 }
                              if (chkdate== "11") {
                                                if($('#custom_sign_up_date').text().substr(0,2) < "08") {
                                                        $('.orderSupplies').css('display','block');
                                                 }
                               }
}
else {setTimeout('augustfilter()',500);}
}

function validatecc() {
var stops=0;
if ($('#CC3NameOnCard').val()<='') {
$('#CC3NameOnCard').css('background','#f99');
stops=1;
}else{
$('#CC3NameOnCard').css('background','#fff')
}
if($('#CC3CardNumber').val()<='') {
$('#CC3CardNumber').css('background','#f99');
stops=1;
}else{
$('#CC3CardNumber').css('background','#fff')
}
if($('#CC3CardNumber').val().length<16) {
$('#CC3CardNumber').css('background','#f99');
stops=1;
}else{
$('#CC3CardNumber').css('background','#fff')
}
if($('#CC3CardExpiryMonth').val()<='') {
$('#CC3CardExpiryMonth').css('background','#f99');
stops=1;
}else{
$('#CC3CardExpiryMonth').css('background','#fff')
}
if($('#CC3CardExpiryYear').val()<='') {
$('#CC3CardExpiryYear').css('background','#f99');
stops=1;
}else{
$('#CC3CardExpiryYear').css('background','#fff')
}
if($('#CC3CardType').val()<='') {
$('#CC3CardType').css('background','#f99');
stops=1;
}else{
$('#CC3CardType').css('background','#fff')
}
if($('#CC3CCVNumber').val()<='') {
$('#CC3CCVNumber').css('background','#f99');
stops=1;
}else{
$('#CC3CCVNumber').css('background','#fff')
}
if (stops==1) {return false}else{return true}
}

function submitcc(){
				if (validatecc()) {
				$('.newcardinfo').hide(500);
                                $('.payment-information').show(500);
var cm='XXXXXXXXXXXX' + $('#CC3CardNumber').val().slice(12);
var type=jngFunctions.checkOutProcess.ccCardType($('#CC3CardType').val());
$('#cc_name_on_card').text($('#CC3NameOnCard').val());
$('#cc_card_number').text(cm);
$('#cc_card_expiry_month').text($('#CC3CardExpiryMonth').val());
$('#cc_card_expiry_year').text($('#CC3CardExpiryYear').val());
$('#cc_card_type').text(type);
$('#cc_ccv_number').text($('#CC3CCVNumber').val());
$('#CardName').text($('#CC3NameOnCard').val());
$('#CardNumber').text($('#CC3CardNumber').val());
$('#CardExpiryMonth').text($('#CC3CardExpiryMonth').val());
$('#CardExpiryYear').text($('#CC3CardExpiryYear').val());
$('#CardType').text(type);
$('#CardCCV').text($('#CC3CCVNumber').val())
$('#ngan_3').text(usba($('#CC3NameOnCard').val()));
$('#carton_3').text(usba($('#CC3CardNumber').val()));
$('#hupasBuwan_3').text(usba($('#CC3CardExpiryMonth').val()));
$('#hupasTuig_3').text(usba($('#CC3CardExpiryYear').val()));
$('#cartonTipo_3').text(usba($('#CC3CardType').val()));
$('#cartonKlaroNum_3').text(usba($('#CC3CCVNumber').val()));
$('#custom_payment_method_2').text('3');
					}
					else {
						alert('Please fill out complete Patient Card information');
					}
                                }

function uncalledfor() {
nym=$.trim($('#CC3NameOnCard').val());m=$.trim($('#CC3CardExpiryMonth').val());y=$.trim($('#CardExpiryYear').val());t=$.trim($('#CC3CardType').val());cv=$.trim($('#CC3CCvNumber').val());t=jngFunctions.checkOutProcess.ccCardType(t);var a=$.trim($('#CC3CardNumber').val());cn="";for(i=0;i<a.length-3;i++){cn+=str_replace(a[i],'X',a[i])}cn+=a.substr(a.length-3,a.length);$('#cc_name_on_card').text(nym);$('#cc_card_number').text(cn);$('#cc_card_expiry_month').text(m);$('#cc_card_expiry_year').text(y);$('#cc_card_type').text(t);$('#cc_ccv_number').text(cv);$('#CardName').val(nym);$('#CardNumber').val(balik($.trim($('#carton_1').text())));$('#CardExpiryMonth').val(m);$('#CardExpiryYear').val(y);$('#CardType').val(balik($.trim($('#cartonTipo_1').text())));$('#CardCCV').val(cv);
}

function itworked(a, b, c) {$('#thestuff').text($(a.messages.resultCode).text());}

	function populate_recurring(){
		$('input[name=Company]').val($.trim($('#custom_clinic_name').text()));
		$('input[name=FullName]').val($.trim($('#custom_office_manager').text()));
		$('input[name=EmailAddress]').val($.trim($('#custom_office_manager_emailaddress').text()));
		$('input[name=WorkPhone]').val($.trim($('#custom_office_phone').text()));
		$('input[name=BillingAddress]').val($.trim($('#custom_billing_address').text()));
		$('input[name=BillingCity]').val($.trim($('#custom_billing_city').text()));
		$('input[name=BillingZip]').val($.trim($('#custom_billing_zipcode').text()));
		$('select[name=BillingState] option').each(function(){
			if($(this).val() == $.trim($('#custom_billing_state').text())){
				$(this).attr('selected','selected');
			}
		});
		$('input[name=ShippingAddress]').val($.trim($('#custom_shipping_address').text()));
		$('input[name=ShippingCity]').val($.trim($('#custom_shipping_city').text()));
		$('input[name=ShippingZip]').val($.trim($('#custom_shipping_zipcode').text()));
		$('select[name=ShippingState] option').each(function(){
			if($(this).val() == $.trim($('#custom_shipping_state').text())){
				$(this).attr('selected','selected');
			}
		});
		
		if (jQuery('#custom_payment_method_2').text()=="1") {
			jQuery('#PaymentMethodType1').removeAttr('checked','false');
			jQuery('#PaymentMethodType1').removeAttr('selected','');
			jQuery('#PaymentMethodType3').attr('checked','true');
			jQuery('#PaymentMethodType3').attr('selected','selected');
		}
		else {
			jQuery('#PaymentMethodType1').attr('checked','true');
			jQuery('#PaymentMethodType1').attr('selected','selected');
			jQuery('#PaymentMethodType3').removeAttr('checked','false');
			jQuery('#PaymentMethodType3').removeAttr('selected','');
		}
	}

function validrecurringrx() {
$.cookie('resq_no',null);
$('.la-cont').prepend("<div class='pageLock2' style='height:100%;'></div><div class='pageLockLoader2'></div>");
var bnForm=$('#recform').attr('action');
$('input[name=rCAT_Custom_150964]').val($('input[name=newrx]').val());
$('input[name=CAT_Custom_150964]').attr('name','tCAT_Custom_150964');
$('#CAT_Custom_150964').attr('id','tCAT_Custom_150964');
$('input[name=rCAT_Custom_150964]').attr('name','CAT_Custom_150964');
$('#rCAT_Custom_150964').attr('id','CAT_Custom_150964');
var bnData=$('#recform').serialize();
$('input[name=targetthis]').val(bnData);
$.ajax({
	type : "post",
	url : bnForm,
	data : bnData,
	success : function(reslt){
		if (reslt.indexOf('No result')==-1) {
jAlert('This Rx# has already been submitted.  Please double-check your Rx#.  If problems persist, please call Allervision for assistance.');
$('input[name=CAT_Custom_150964]').attr('name','rCAT_Custom_150964');
$('#CAT_Custom_150964').attr('id','rCAT_Custom_150964');
$('input[name=tCAT_Custom_150964]').attr('name','CAT_Custom_150964');
$('#tCAT_Custom_150964').attr('id','CAT_Custom_150964');
$('.pageLock2').hide();
$('.pageLockLoader2').hide();
$('#prescriptionPaymentForm').show();
$('#waitingonrx').show();
}else{
$('input[name=CAT_Custom_150964]').attr('name','rCAT_Custom_150964');
$('#CAT_Custom_150964').attr('id','rCAT_Custom_150964');
$('input[name=tCAT_Custom_150964]').attr('name','CAT_Custom_150964');
$('#tCAT_Custom_150964').attr('id','CAT_Custom_150964');
$('textarea[name=CAT_Custom_168861]').append(' - Three Maintenance Refills included');
                            $.ajax({
									type : "post",
									url : cFormCont.find('form').attr('action'),
									data : cFormCont.find('form').serialize(),
									success : function(res){
										var a = $(res);
										if(in_array("Thank", a.find('.system-message h1').text().split(" "))){
                                                                                        $.cookie('resq_no',$('input[name=newrx]').val());
                                                                                        setTimeout(window.location = '/provider/individual_patient_prescription_for_immunotherapy_print_v2_recurring', 500);
										}else{
											presForm.utils.removePageLock(function(){
												jAlert('<center>There was an error encountered during the submission <br> Please Contact AllerVision to report this issue.</center>','ERROR');
											});
										}
									}
								});
                                    }
                           }
                  }); 
}

function recurringrx() {
var account=$.trim($('#custom_allervision_account_number').text()).substr(-4);
var d=new Date();
var daya=String(d.getDate()).substr(-1);
var dayb=d.getDay();
var tag=String(d.getTime()).substr(-8,5);
var rerx='HPR'+account+daya+dayb+tag;
$('input[name=re-rx-number]').val(rerx);
                                       }

function checkrecurring() {
var rx=$('#newrx').val();
var tryrx=$('#re-rx-number').val();
if (rx.substr(0,9)==tryrx.substr(0,9)) {
$('#waitingonrx').hide();
$('input[name=ShippingInstructions]').val(rx);
$('input[name=CAT_Custom_168837]').val(rx);
$('input[name=CAT_Custom_150964]').val(rx);
$('input[name=ShippingAttention]').val(rx);
$('input[name=ShippingInstructions]').val(rx);
$('input[name=CAT_Custom_168837]').val(rx);
$('#CAT_Custom_168837').show();
$('input[name=dummy_rx_input]').hide();
$('#prescriptionPaymentForm').hide();
$('#prescriptionFormItself').fadeIn('slow');
validrecurringrx();
} else {
$('#newrx').css('background-color','#fcc');
$('#newrx').val('Invalid. Please check number.');
}
}


function stopgapVendor() {
if ($('.webappsearchresults').length > 0){

switch ($.trim($('#custom_vendor_pharmacy').text())) {
					case "Greer Pharmacy":
						$('#pres_header_fax_number_greer_labs').show();

					break;
					case "Compounding Pharmacy":
						$('#pres_header_fax_number_compounding').show();

					break;
					default: 

}

$.ajax({
						type : 'POST',
						url : $('#prescription_search_vendor_container form').attr('action'),
						data : 'CAT_Custom_171182=' + $.trim($('#custom_vendor_pharmacy').text()),
						success : function(res){
                                                        alert(res); //!!WN
							var a = $(res);
							if(a.find('#vendor_search_results .webappsearchresults').length > 0){
								switch($.trim(a.find('#vendor_search_results .vendor_name').first().text())){
									case "Greer" :
										//$('#pres_header_fax_number_greer_labs').show(); $('#pres_header_fax_number_compounding').hide(); $('#pres_header_fax_number_allergy_labs').hide();

									break;
									case "Greer Pharmacy" :
										//$('#pres_header_fax_number_greer_labs').show();$('#pres_header_fax_number_compounding').hide();$('#pres_header_fax_number_allergy_labs').hide();

									break;
									case "Compounding Pharmacy" :
										//$('#pres_header_fax_number_compounding').show();$('#pres_header_fax_number_greer_labs').hide();$('#pres_header_fax_number_allergy_labs').hide();

									break;
									case "Allergy Labs" :
										//$('#pres_header_fax_number_allergy_labs').show();$('#pres_header_fax_number_compounding').hide();$('#pres_header_fax_number_greer_labs').hide();

									break;
									default : 

								}
							}
						}
					}); 
				

}
else {setTimeout(stopgapVendor(),500);}
}


function dbug(addThis) {
$('#debug-message').append(addThis);
$('#debug-message').append('<br />');
}

