// global variable
// determine whether the state source is ip detection or not
var isIpDetection = false;

( function($) {
	var planCommitState = true;
	var competingDrugCommitState = true;
	var competingNo = 1;
	var labelPlanName = "&nbsp;";
	var planTypeCategories = [ "Commercial", "Medicare", "Medicaid" ];
	$( function() {
		
		// bind product selected event 
		$("#primaryDrug").change(primaryDrugSelectorHandler);

		// bind state select event
		$("#eformularyState").change(stateSelectorHandler);
		
		// bind plans popup event
		$('.btn-selectPlans-fml').click(showSelectPlans);
		$('.formulary-popup a.close').click(hideSelectPlans);
		$('.formulary-popup a.bg-viewResults').click(choosePlansSubmit);
		$('.formulary-popup a.bg-cancel').click(choosePlansCancel);
		$('.formulary-popup .contTop li').click(changePlanType);
		$('.formulary-popup .clearSelected').click(function() {
//			$('.formulary-popup .list:visible').find('input').attr('checked', null);
			$('.formulary-popup .list').find('input').attr('checked', null);
			calculateSelectedPlansAndResetLabel();
		});
		
		// bind compare popup event
		bindShowEventToCompareButtons();
		
		// pulls the users location from google
		var location = '';
		// google.loader.ClientLocation =
		// {"latitude":42.359,"longitude":-71.061,"address":{"city":"Boston","region":"MA","country":"USA","country_code":"US"}};
		try {
			if (google.loader.ClientLocation) {
				var loc = google.loader.ClientLocation;
				if (loc && loc.address && loc.address.region)
					location = loc.address.region;
			}
		} catch(e) {
			// do nothing
		}

		if ($("#eformularyState").getSelectedIndex() <= 0) {
			//if the user has a stored state from a previous use then load it, otherwise pull it from google.
			setState(findState(eval(stateJson), location));
			// keep track that this is a state arrived at by IP
			isIpDetection = true;
		}

		// reset result table header according to the data which come from email 
		updateSearchResultHeader();
		
		// initialize input value
		processInputVal();
		
		// initialize specific drug information
		queryPrimaryDrug();
		
	});
	
	//=======================================================================
	// Event handler methods
	//=======================================================================
	
	/**
	 * Primary drug selector handler.
	 */
	function primaryDrugSelectorHandler() {
		
		getBrandIsi();
		cleanEformularyData();
		processInputVal();
		queryPrimaryDrug(true);
		}
	
	/**
	 * State selector handler.
	 */
	function stateSelectorHandler() {
		cleanEformularyData();
		processInputVal();
	}
	
	/**
	 * Share results button handler.
	 */
	function shareResultsHandler() {
		$("#email-pop").css("display", "block");
		$("#fade1").css("display", "block");
		$("#fade1").css("height", $("#wrap").height());
		$("select").css("visibility", "hidden");
	}
	
	/**
	 * Print results button handler.
	 */
	function printResultsHandler() {
		$("#print-page").attr("href", ctx + "/styles/print.css");
		//$('#print_border').css("display", "block");
		/*hidden findrep print body*/
		$("#findrep").css("display","none");
		processInputVal();
		print();
	}
	
	/**
	 * Show plans popup.
	 */
	function showSelectPlans() {
		hidePopupCompare();
		if (!checkDrugSelected() || !checkStateSelected()) {
			return false;
		}
		var overlay = $('.formulary-popup-overlay');
		var p = overlay.parent();
		overlay.show().width(p.width()).height(p.height()).bgiframe();
		$('.formulary-popup').show();
		
		// set header in panel
		$("#headerSelectPlansInState").html("Select Plans in " + $("#eformularyState option:selected").text());
		
		$(planTypeCategories).each(function() {
			$(".listcont #type" + this).html("");
		});
		$(".toolbar .red").text("");
		getAllPlansByCategories();
	}
	
	/**
	 * Hide plans popup.
	 */
	function hideSelectPlans() {
		$('.formulary-popup').hide();
		$('.formulary-popup-overlay').hide();
	}
	
	/**
	 * change plan type category.
	 */
	function changePlanType(evt) {
		$('.formulary-popup .contTop label').removeClass('select');
		$(this).children('label').addClass('select');
		$('.formulary-popup .list').hide();
		$(this).children('input').attr('checked','checked');
		var show = $('#' + $(this).children('input').attr('rel'));
		show.show();
		calculateSelectedPlansAndResetLabel();
	}
	
	/**
	 * Bind show popup compare event to compare buttons.
	 */
	function bindShowEventToCompareButtons() {
		$('td.leftCompare h6, td.leftCompare span, td.leftCompare .btn-compare-fml, td.rightCompare h6, td.rightCompare span, td.rightCompare .btn-compare-fml', '#table-header').click(showPopupCompare);
		$('.popupCompare .cont').click(function(evt) {evt.stopPropagation();});
		// re-init the tracking framework
		trackingInit();
	}
	
	/**
	 * Show popup compare.
	 */
	function showPopupCompare() {
		hidePopupCompare();
		var t = $(this);
		var td = t.parent();
		var pos = td.offset();
		pos.top += 5;
		var cls;
		var p = $('.popupCompare');
		if(td.hasClass('rightCompare')){
			cls = 'rightCompare';
			p.addClass('rightCompare');
			pos.left -= 122;
		}else{
			cls = 'leftCompare';
			p.removeClass('rightCompare');
			pos.left -= 4;
		}
		p.attr('compareTitle', '.' + cls);
		td.children('*').css({visibility: 'hidden'});
		
		// set global competing tag no
		if (t.parent().attr("id") == "competingNo-1") {
			competingNo = 1;
		} else if (t.parent().attr("id") == "competingNo-2") {
			competingNo = 2;
		}
		
		p.show().css({left:pos.left, top:pos.top});
		setTimeout(function() {
			$('body').bind('click', hidePopupCompare);
		}, 50);
		getCompetingDrug();
	}
	
	/**
	 * Hide popup compare.
	 */
	function hidePopupCompare() {
		var p = $('.popupCompare');
		if(! p.is(':visible')) return;
		var td = $(p.attr('compareTitle'), '#table-header');
		p.hide();
		td.children('*').css({visibility: 'visible'});
		$('body').unbind('click', hidePopupCompare);
		
		//Leslie add to fix AZCDI-483
		$('td.leftCompare h6, td.leftCompare span, td.leftCompare .btn-compare-fml, td.rightCompare h6, td.rightCompare span, td.rightCompare .btn-compare-fml', '#table-header').click(showPopupCompare);

	}
	
	//=======================================================================
	// Select primary drug methods
	//=======================================================================

	/**
	 * Query primary drug information.
	 */
	function queryPrimaryDrug(isChangeBrand) {
		processInputVal();
		$("#eformularySearchForm").attr("action", ctx + "/eformulary/getDrug.json");
		var options = {
			beforeSubmit: function() {
			},
			success: function(result) {
				// update brand url
				if (result.eformularyDrug.drugUrl == null || result.eformularyDrug.drugUrl == "") {
					
					// clear for no url
					$("#event-link").html("");
					$("#shareResultsPrimaryDrug").html("");
					$("#shareResultsPrimaryDrugUrl").html("");
				} else {
					
					// display and set url to href
					$("#event-link").html('For more information about prescribing ' + result.eformularyDrug.drugName.replace("&reg;", "") + ', please visit <a id="eformularyBrandLink" href="' + result.eformularyDrug.drugUrl + '" target="_blank">' + result.eformularyDrug.drugUrl + '</a>.');
					if (result.eformularyDrug.chemicalName != "" && result.eformularyDrug.chemicalName != "undefined") {
						$("#shareResultsPrimaryDrug").html(" for " + result.eformularyDrug.drugName + " (" + result.eformularyDrug.chemicalName + ")");
					}else{
						$("#shareResultsPrimaryDrug").html(" for " + result.eformularyDrug.drugName);
					}
					$("#shareResultsPrimaryDrugUrl").html("Please visit <a id='mail_brand_href' href='http://www.azprivacystatement.com' target='_blank'>www.azprivacystatement.com</a> to review our Privacy Statement.");
				}

				// update pi link
				if (result.eformularyDrug.piUrl == null || result.eformularyDrug.piUrl == "") {
					// hide for no url
					$("#piPdfLink").css("display", "none");
				} else {
					// display and set url to href
					$("#piPdfLink").attr("href", result.eformularyDrug.piUrl);
					$("#piPdfLink").css("display", "block");
				}

				// update mail info
				if (result.eformularyDrug.chemicalName != "" && result.eformularyDrug.chemicalName != "undefined") {
					$("#mail_thank_brand").html(result.eformularyDrug.drugName + ' (' + result.eformularyDrug.chemicalName + ').');
				} else {
					$("#mail_thank_brand").html(result.eformularyDrug.drugName + '.');
				}
				
				if (isChangeBrand) {
					cleanEformularyData();
				}
				
				// finally, re-init the tracking framework
				trackingInit();
			},
			error: function(xhr, status) {
				if (xhr.status > 200 && xhr.status <= 500) {
					alert("error comminucation.");
				}
			},
			dataType: "json"
		};
	    $("#eformularySearchForm").ajaxSubmit(options);
	}
	
	//=======================================================================
	// Choose plans methods
	//=======================================================================
	
	/**
	 * Get all plans by plan type categories.
	 */
	function getAllPlansByCategories() {
		processInputVal();
		$("#eformularySearchForm").attr("action", ctx + "/eformulary/getAllPlansByCategories.json");
		var options = {
			beforeSubmit: function() {
				$(".formulary-popup .listcont div:first").before("<div class='loading'>&nbsp;</div>");
			},
			success: function(result) {
				$(".formulary-popup .loading").remove();
				trackingUnbind();
				
				// load each plan list
				$(planTypeCategories).each(function() {
					loadCategoryPlans(this, eval("result." + this.toLowerCase() + "PlanList"));
				});
				
				// reset selected check plans count label
				calculateSelectedPlansAndResetLabel();

				// for enter keyboard submit
				$('.formulary-popup .listcont input').each( function() {
					$(this).keypress( function(e) {
						var key = window.event ? e.keyCode : e.which;
						if (key.toString() == "13") {
							$('.formulary-popup a.bg-viewResults').click();
						}
					});
				});
				
				// bind click on checkbox
				$('.formulary-popup .listcont input').click(function() {
					if (checkSelectedPlans()) {
						
						// valid selected count
						calculateSelectedPlansAndResetLabel();
						$(".toolbar .red").text("");
					} else {
					
						// invalid selected count
						$(".toolbar .red").text("Only up to 10 plans may be selected at a time.");
						$(this).attr("checked", null);
					}
				});
				trackingInit();
			},
			error: function(xhr, status) {
				if (xhr.status > 200 && xhr.status <= 500) {
					alert("error comminucation.");
					$(".formulary-popup .loading").remove();
				}
			},
			dataType: "json"
		};
		$("#eformularySearchForm").ajaxSubmit(options);
	}
	
	/**
	 * Load plans for a specific category.
	 */
	function loadCategoryPlans(category, planList) {
		var loadContainerSelector = ".listcont #type" + category;
		var planListStr = "";
		$(loadContainerSelector).html("");
		if (planList.length > 0) {
			planListStr += '<ul>';
			for (var i = 0; i < planList.length; i++) {
				planListStr += '<li>';
				var planBean = planList[i];
				if (planBean.selected) {
					planListStr += '<input checked="checked" type="checkbox" planid="' + planBean.planId + '" id="checkbox_choosePlan_' + planBean.planId + '" name="plans" value="' + planBean.planId + '" />';
				} else {
					planListStr += '<input type="checkbox" planid="' + planBean.planId + '" id="checkbox_choosePlan_' + planBean.planId + '" name="plans" value="' + planBean.planId + '" />';
				}
				planListStr += '<label for="checkbox_choosePlan_' + planBean.planId + '">' + planBean.planName + '</label>';
				planListStr += '</li>';
			}
			planListStr += '</ul>';
		} else {
			planListStr +="There are currently no " + category +" plans in the state you have selected. You can try searching for a different type of plan in the state you selected. Or if you would like to speak to an AstraZeneca representative about formulary information, call <span class='strong'>1-888-692-9737, Monday through Friday, 8:30 <span class='ampm'>am</span> to 8:30 <span class='ampm'>pm</span> ET, excluding holidays.";
		}
		$(loadContainerSelector).append(planListStr);
	}
	
	/**
	 * Calculate selected plans and reset label value.
	 */
	function calculateSelectedPlansAndResetLabel() {
		// the code below is for each list, so please don't remove in case we use it later
//		var n = $('.formulary-popup .list:visible input:checked').length;
//		$('.formulary-popup .list:visible').attr('selectedNum', n);
//		$('.formulary-popup .toolbar .selectedNum').text(n);
		
		var n = $('.formulary-popup .list input:checked').length;
		updateSelectedPlansNum(n);
	}
	
	/**
	 * Update selected plans num.
	 */
	function updateSelectedPlansNum(n) {
		$('.formulary-popup .toolbar .selectedNum').text(n);
	}
	
	/**
	 * Submit choose plans.
	 */
	function choosePlansSubmit() {
		processInputVal();
		
		// if brand has been selected and plans have been selected, then query formulary data
		if ($("#primaryDrug").val() != "" && checkPlanSelected()) {
			queryPrimaryDrug();
			getSearchResult();
			$("#choose-plan").css("display", "none");
			$("#fade1").css("display", "none");
			$("select").css("visibility", "visible");
			hideSelectPlans();
		} else {
			$(".toolbar .red").text("Please select at least one plan to view formulary results.");
		}
	}
	
	/**
	 * Cancel choose plans.
	 */
	function choosePlansCancel() {
		planCommitState = false;
		hideSelectPlans();
	}
	
	//=======================================================================
	// Query search result methods
	//=======================================================================
	
	/**
	 * Get Search result for eformulary data.
	 */
	function getSearchResult(noLoadingEffect) {
		$("#eformularySearchForm").attr("action", ctx + "/eformulary/getSearchResult.json");
		loadMessage = "&nbsp;";
		var options = {
			beforeSubmit: function() {
				showDataTable();
				if (noLoadingEffect == null || !noLoadingEffect) {
					$("#eformularySearchTable tbody").html("<tr><td><div class='loading'>" + loadMessage + "</div></td></tr>");
				}
			},
			success: function(result) {
				updateSearchResultHeader(result);
				createSearchResultTable(result);
				createSearchResultFootnote(result);
				processInputVal();
			},
			error: function(xhr, status) {
				loadMessage = "error comminucation.";
				if (noLoadingEffect == null || !noLoadingEffect) {
					$("#eformularySearchTable tbody").html("<tr><td><div class='loading'>" + loadMessage + "</div></td></tr>");
				}
			},
			dataType: "json"
		};
		$("#eformularySearchForm").ajaxSubmit(options);
	}
	
	/**
	 * Update search result table's header.
	 */
	function updateSearchResultHeader(result) {
		// set plan type name
		var label = "";
		var selectedCategoriesCount = 0;
		$(planTypeCategories).each(function() {
			if (checkPlanSelectedByType("#type" + this)) {
				label += " " + this + " and";
				selectedCategoriesCount++;
			}
		});
		if (label == null || label == "") {
			label = labelPlanName;
		} else {
			label = $.trim(label.substring(0, label.length - 3));
		}
		if (selectedCategoriesCount > 2) {
			label = label.replace(/ and/g, ",");
			var i = label.lastIndexOf(",");
			label = label.substring(0, i + 1) + " and" + label.substring(i + 1, label.length);
		}
		if (selectedCategoriesCount > 0) label += " Plans";
		$("#tableHeaderPlanName").html("<h6>" + label + "</h6>");
		
		// set primary drug
		var showCompareBtn = false;
		if (checkDrugSelected()) {
			var drugOption = $("#primaryDrug option[value=" + $("#searchEformularyParameter_drug").val() + "]");
			if (drugOption != null) {
				var drugName = $(drugOption).attr("drugName");
				var chemicalName = $(drugOption).attr("chemicalName");
				if (chemicalName != null && chemicalName != "" && chemicalName != "undefined") {
					$("#tableHeaderDrugName").html('<h6>' + drugName + '</h6><span>(' + chemicalName + ')</span>');
				} else {
					$("#tableHeaderDrugName").html('<h6>' + drugName + '</h6>');
				}
			}
			showCompareBtn = true;
		}
		
		// set compare header one
		if (showCompareBtn) {
			if (checkFirstCompetingDrugSelected()) {
				var firstCompetingDrugId = $("#searchEformularyParameter_firstCompetingBrand").val();
				var firstCompetingDrugName = $("li[competingDrugId=" + firstCompetingDrugId + "]").attr("competingDrugName");
				var firstCompetingDrugChemicalName = $("li[competingDrugId=" + firstCompetingDrugId + "]").attr("competingChemicalName");
				if (firstCompetingDrugChemicalName != "" && firstCompetingDrugChemicalName != "undefined") {
					if (isNotHaveWpace(firstCompetingDrugName) && firstCompetingDrugName.indexOf("<sup>") < 0 && firstCompetingDrugName.length > 16) {
						$("#competingNo-1").html('<h6>' + firstCompetingDrugName.replace(/\//g, "/ ") + '</h6><span>(' + firstCompetingDrugChemicalName + ')</span>');
					} else {
						$("#competingNo-1").html('<h6>' + firstCompetingDrugName + '</h6><span>(' + firstCompetingDrugChemicalName + ')</span>');
					}
				} else {
					if (isNotHaveWpace(firstCompetingDrugName) && firstCompetingDrugName.indexOf("<sup>") < 0 && firstCompetingDrugName.length > 16) {
						$("#competingNo-1").html('<h6>' + firstCompetingDrugName.replace(/\//g, "/ ") + '</h6>');
					} else {
						$("#competingNo-1").html('<h6>' + firstCompetingDrugName + '</h6>');
					}
				}
			} else {
				$("#competingNo-1").html('<a class="btn-compare-fml" href="javascript:void(0);">Compare</a>');
			}
		}
		
		// set compare header two
		if (showCompareBtn) {
			if (checkSecondCompetingDrugSelected()) {
				var secondCompetingDrugId = $("#searchEformularyParameter_secondCompetingBrand").val();
				var secondCompetingDrugName = $("li[competingDrugId=" + secondCompetingDrugId + "]").attr("competingDrugName");
				var secondCompetingDrugChemicalName = $("li[competingDrugId=" + secondCompetingDrugId + "]").attr("competingChemicalName");
				if (secondCompetingDrugChemicalName != "" && secondCompetingDrugChemicalName != "undefined") {
					if (isNotHaveWpace(secondCompetingDrugName) && secondCompetingDrugName.indexOf("<sup>") < 0 && secondCompetingDrugName.length > 16) {
						$("#competingNo-2").html('<h6>' + secondCompetingDrugName.replace(/\//g, "/ ") + '</h6><span>(' + secondCompetingDrugChemicalName + ')</span>');
					} else {
						$("#competingNo-2").html('<h6>' + secondCompetingDrugName + '</h6><span>(' + secondCompetingDrugChemicalName + ')</span>');
					}
				} else {
					if (isNotHaveWpace(secondCompetingDrugName) && secondCompetingDrugName.indexOf("<sup>") < 0 && secondCompetingDrugName.length > 16) {
						$("#competingNo-2").html('<h6>' + secondCompetingDrugName.replace(/\//g, "/ ") + '</h6>');
					} else {
						$("#competingNo-2").html('<h6>' + secondCompetingDrugName + '</h6>');
					}
				}
			} else {
				$("#competingNo-2").html('<a class="btn-compare-fml" href="javascript:void(0);">Compare</a>');
			}
		}
		
		// for ie lazy load, wait 200 ms
		setTimeout(bindShowEventToCompareButtons, 200);
	}
	
	/**
	 * Create formulary data search result table.
	 */
	function createSearchResultTable(result) {
		$("#eformularyTabelContainer").children().remove();
		tableHtml = '<table id="eformularySearchTable" width="100%" cellspacing="0" cellpadding="0" border="0" name="eformularySearchTable" >';
		if (result.eformularDataList.length > 0) {
			for (var i = 0; i < result.eformularDataList.length; i++) {
				if (i < 10) {
					tableHtml += '<tr id="formularyId-' + result.eformularDataList[i].planName + '"';
					if (i % 2 == 0) {
						tableHtml += ' bgcolor="#ffffff">';
					} else {
						tableHtml += ' bgcolor="#e3deda">';
					}
					tableHtml += '<td class="data-list1">&nbsp;</td>' + '<td class="data-list2">' + result.eformularDataList[i].planName + '&nbsp;</td>' + '<td class="data-list3">'
					+ result.eformularDataList[i].tierName + '&nbsp;&nbsp;' + result.eformularDataList[i].restrictions + '&nbsp;</td>' + '<td class="data-list4">' + result.eformularDataList[i].firstCompetingTierName + '&nbsp;&nbsp;'
					+ result.eformularDataList[i].firstCompetingRestrictions + '&nbsp;</td>' + '<td class="data-list5">' + result.eformularDataList[i].secondCompetingTierName + '&nbsp;&nbsp;'
					+ result.eformularDataList[i].secondCompetingRestrictions + '&nbsp;</td>';
					tableHtml += '</tr>';
				}
			}
			
		} else {
			tableHtml += '<tr><td colspan="4" hight="200" align="center">Please select a state, plan type, and then select a specific plan to review results.</td></tr>';
		}
		tableHtml += '</table>';
		$("#eformularyTabelContainer").append(tableHtml);
	}
	
	/**
	 * Create formulary data search result foot note.
	 */
	function createSearchResultFootnote(result) {
		$("#footnoteTier").html("");
		$("#footnoteQualifiers").html("");
		$("#footnoteDrug").html("");
		if (result.footnoteTier.length > 0) {
			for (var i = 0; i < result.footnoteTier.length; i++) {
				if (i < result.footnoteTier.length - 1) {
					$("#footnoteTier").append(result.footnoteTier[i].tierName + ' = ' + result.footnoteTier[i].tierDescription + ';');
				} else {
					$("#footnoteTier").append(result.footnoteTier[i].tierName + ' = ' + result.footnoteTier[i].tierDescription + '.');
				}
			}
		}
		if (result.footnoteQualifier.length > 0) {
			for ( var i = 0; i < result.footnoteQualifier.length; i++) {
				if (i < result.footnoteQualifier.length - 1) {
					$("#footnoteQualifiers").append(result.footnoteQualifier[i].qualifierCode + ' = ' + result.footnoteQualifier[i].qualifierDescription + ';');
				} else {
					$("#footnoteQualifiers").append(result.footnoteQualifier[i].qualifierCode + ' = ' + result.footnoteQualifier[i].qualifierDescription + '.');
				}
			}
		}
		if (result.footnoteDrug.length > 0) {
			for ( var i = 0; i < result.footnoteDrug.length; i++) {
				if (result.footnoteDrug[i].drugDescription != null && result.footnoteDrug[i].drugDescription != "") {
					$("#footnoteDrug").append(result.footnoteDrug[i].drugDescription + "</br>");
				}
			}
		}
	}
	
	//=======================================================================
	// show brand isi when choose competing drug methods
	//=======================================================================
	
	/**
	 * Get brand isi.
	 */
	function getBrandIsi() {
		$("#mainContent #isi").html("");
		$("#print-content #isi").html("");
		var drugId = $("#primaryDrug").val();
		if(drugId != 767){
			return;
		}
		$("#eformularySearchForm").attr("action", ctx + "/eformulary/getBrandIsi.json?drugId=" + drugId);
		var options = {
			beforeSubmit: function() {
				$("#mainContent #isi").html("<div class='loading'>&nbsp;</div>");
			},
			success: function(result) {
				$("#mainContent #isi").html("");
				if (result.brandIsi.length > 0) {
					$("#mainContent #isi").html(result.brandIsi);
					$("#print-content #isi").html(result.brandIsi);
				}
			},
			error: function(xhr, status) {
				if (xhr.status > 200 && xhr.status <= 500) {
					alert("error comminucation.");
					$("#mainContent #isi").html("<div class='loading'>&nbsp;</div>");
				}
			},
			dataType: "json"
		};
		$("#eformularySearchForm").ajaxSubmit(options);
	}
	
	/**
	 * Get competing drugs.
	 */
		function getCompetingDrug() {
			processInputVal();
			$("#eformularySearchForm").attr("action", ctx + "/eformulary/getCompetingDrug.json");
			var options = {
				beforeSubmit: function() {
					$("#compareList").html("<div class='loading'>&nbsp;</div>");
				},
				success: function(result) {
					$("#compareList").html("");
					if (result.competingDrugList.length > 0) {
						var row = '<ul>';
						for (var i = 0; i < result.competingDrugList.length; i++) {
							var drugId = result.competingDrugList[i].drugId;
							var drugName = result.competingDrugList[i].drugName;
							var chemicalName = result.competingDrugList[i].chemicalName;
							if (result.competingDrugList[i].selected) {
								row += '<li class="selected" competingDrugId="' + drugId + '" competingDrugName="' + drugName + '" competingChemicalName="' + chemicalName + '"><b>' + drugName + '</b><br />('+ chemicalName +')</li>';
							} else {
								row += '<li competingDrugId="' + drugId + '" competingDrugName="' + drugName + '" competingChemicalName="' + chemicalName + '"><a href="javascript:void(0);" drugId="' + drugId + '"><b>' + drugName + '</b><br />('+ chemicalName +')</a></li>';
							}
							/*
							row += '<li><input type="checkbox" comparedrugid="' + result.competingDrugList[i].drugId + '" comparedrugname="' + result.competingDrugList[i].drugName + '" chemicalname="' + result.competingDrugList[i].chemicalName
							+ '" id="checkbox_compareBrand_' + result.competingDrugList[i].drugId + '" name="competingBrand" value="' + result.competingDrugList[i].drugId + '"/><label for="checkbox_compareBrand_'
							+ result.competingDrugList[i].drugId + '">' + result.competingDrugList[i].drugName + '</label></li>';
							*/
						}
						row += "</ul>";
						$("#compareList").append(row);
						$("#compareList li a").click(competingDrugHandler);
						$("#clearCompareBtn").click(clearCompetingDrugHandler);
					}

					// for enter keyboard submit
					$("#eformularyCompareBrandDiv :checkbox").each( function() {
						$(this).keypress( function(e) {
							var key = window.event ? e.keyCode : e.which;
							if (key.toString() == "13") {
								$("#competingDrugSubmit").click();
							}
						});
					});
					
					// also, re-init the tracking framework
					trackingInit();
				},
				error: function(xhr, status) {
					if (xhr.status > 200 && xhr.status <= 500) {
						alert("error comminucation.");
						$("#compareList").html("<div class='loading'>&nbsp;</div>");
					}
				},
				dataType: "json"
			};
			$("#eformularySearchForm").ajaxSubmit(options);
		}
		
		
	/**
	 * Competing drug select handler.
	 */
	function competingDrugHandler() {
		hidePopupCompare();
		competingDrugSubmit(competingNo, $(this).attr("drugId"));
	}
	
	/**
	 * Clear competing drug select handler.
	 */
	function clearCompetingDrugHandler() {
		hidePopupCompare();
		competingDrugSubmit(competingNo, 0);
	}
	
	/**
	 * Submit competing brand query.
	 */
	function competingDrugSubmit(competingNo, drugId) {
		processInputVal();
		initCompetingDrugInput(competingNo, drugId);
		if ($("#primaryDrug").val() != "") {
			getSearchResult(true);
		}
		$("#compare-medication").css("display", "none");
		$("#fade1").css("display", "none");
		$("select").css("visibility", "visible");
	}

	/**
	 * Initialize competing drug input.
	 */
	function initCompetingDrugInput(competingNo, drugId) {
		if (competingNo == 1) {
			$("#searchEformularyParameter_firstCompetingBrand").val(drugId);
		} else if (competingNo == 2) {
			$("#searchEformularyParameter_secondCompetingBrand").val(drugId);
		} else {
			$("#searchEformularyParameter_firstCompetingBrand").val("0");
			$("#searchEformularyParameter_secondCompetingBrand").val("0");
		}
		return true;
	}
	
	//=======================================================================
	// Common process methods
	//=======================================================================
	
	/**
	 * Process input value.
	 */
	function processInputVal() {
		if ($("#primaryDrug").val() != "") {
			$("#searchEformularyParameter_drug").val($("#primaryDrug").val());
		} else {
			$("#searchEformularyParameter_drug").val("");
			$("#primaryDrugTab").html("");
		}

		if ($("#eformularyState").val() != "") {
			$("#searchEformularyParameter_state").val($("#eformularyState").val());
		} else {
			$("#searchEformularyParameter_state").val("");
		}

		//if($("#searchEformularyParameter_regex").val()==""){
		//	$("#searchEformularyParameter_regex").val("ALL");
		// }

		if ($("#eformularyPlanType").val() != "") {
			$("#searchEformularyParameter_planType").val($("#eformularyPlanType").val());
		} else {
			$("#searchEformularyParameter_planType").val("");
		}
		
		// sync print data
		processPrintVal();
		
		// determine whether it will show print button or not
		showShareAndPrintLayout();
		
		$("#comparebrand-error").css("visibility", "hidden");
		$("#plan-error").css("visibility", "hidden");
	}
	
	/**
	 * Clean formulary data.
	 */
	function cleanEformularyData() {
		cleanSearchResult();

		$("#hidden_plans_div").html("");
		$("#searchEformularyParameter_firstCompetingBrand").val("");
		$("#searchEformularyParameter_secondCompetingBrand").val("");

		$("#choosePlanTable tbody").html("");
		$("#eformularyCompareBrandDiv").html("");
		$("#primaryDrugTab").html("");
		$("#firstCpmpetingBrandTab").html("");
		$("#secondCpmpetingBrandTab").html("");
		
		$("#tableHeaderPlanName").html("<h6>" + labelPlanName + "</h6>");
		$("#tableHeaderDrugName").html("");
		$("#competingNo-1").html("");
		$("#competingNo-2").html("");
		
		updateSelectedPlansNum(0);
		
		processPrintVal();
	}
	
	/**
	 * Clean forumlary data search result table.
	 */
	function cleanSearchResult() {
		$("#eformularyTabelContainer").html("");
		tableBody = '<table id="eformularySearchTable" width="100%" cellspacing="0" cellpadding="0" border="0" name="eformularySearchTable">';
		tableBody += '<tr>';
		tableBody += '<td colspan="4" hight="200" align="center">Please select a state, plan type, and then select a specific plan to review results.</td>';
		tableBody += '</tr>';
		tableBody += '</table>';
		$("#eformularyTabelContainer").append(tableBody);
	}
	
	/**
	 * Process print value.
	 */
	function processPrintVal() {
		if ($("#primaryDrug").val() != "") {
			$("#print_brand_name").html($("#primaryDrug").getSelectedText());
			$("#print-brand").html($("#primaryDrug").getSelectedText());
		} else {
			$("#print_brand_name").html("");
			$("#print-brand").html("");
		}
		
		if ($("#eformularyState").val() != "") {
			$("#print-state").html($("#eformularyState").getSelectedText());
		} else {
			$("#print-state").html("");
		}

		if ($("#tableHeaderPlanName").text() != labelPlanName) {
			$("#print-planType").html($("#tableHeaderPlanName").text());
		} else {
			$("#print-planType").html("");
		}

		$("#print-table-header").html($("#table-header").html());
		$("#print-table-content").html($("#content-table").html());
		$("#print-footnote").html($("#footnote").html());
		
		// finalize table header
		if ($("#print-table-header #competingNo-1").text() == "Compare")
			$("#print-table-header #competingNo-1").html("");
		if ($("#print-table-header #competingNo-2").text() == "Compare")
			$("#print-table-header #competingNo-2").html("");
	}
	
	/**
	 * Show share and print layout.
	 */
	function showShareAndPrintLayout() {
		if (checkPlanDisplayed()) {

			// enable buttons
			$("#printFinderPlans").removeClass("disable");
			
			// bind share results event
			$("#emailpop").click(shareResultsHandler);
			
			// bind print button event
			$("#eformulary-print").click(printResultsHandler);
			
			// show data table
			showDataTable();
		} else {
			
			// disable buttons
			$("#printFinderPlans").addClass("disable");
			
			// unbind share results event
			$("#emailpop").unbind("click", shareResultsHandler);
			
			// unbind print button event
			$("#eformulary-print").unbind("click", printResultsHandler);
			
			// hide data table
			hideDataTable();
		}
	}
	
	/**
	 * Show data table.
	 */
	function showDataTable() {
		// show data table
		$("#beforeSearch").css("display", "none");
		$("#table-header").css("display", "block");
		$("#content-table").css("display", "block");
		$("#contentform-footer").css("display", "block");
	}
	
	/**
	 * Hide data table.
	 */
	function hideDataTable() {
		// hide data table
		$("#beforeSearch").css("display", "block");
		$("#table-header").css("display", "none");
		$("#content-table").css("display", "none");
		$("#contentform-footer").css("display", "none");
	}
	
	/**
	 * Check whether any drug has been selected or not.
	 */
	function checkDrugSelected() {
		if ($("#searchEformularyParameter_drug").val() != null 
				&& $("#searchEformularyParameter_drug").val() != ""
				&& $("#searchEformularyParameter_drug").val() > 0)
			return true;
		else
			return false;
	}
	
	/**
	 * Get selected drug name.
	 */
	function getSelectedDrugName() {
		if (checkDrugSelected()) {
			var drugOption = $("#primaryDrug option[value=" + $("#searchEformularyParameter_drug").val() + "]");
			if (drugOption != null) {
				var drugName = $(drugOption).attr("drugName");
				var chemicalName = $(drugOption).attr("chemicalName");
				if (chemicalName != null && chemicalName != "" && chemicalName != "undefined") {
					return drugName + ' (' + chemicalName + ')';
				} else {
					return drugName;
				}
			}
		}
		return "";
	}
	
	/**
	 * Check whether any state has been selected or not.
	 */
	function checkStateSelected() {
		if ($("#searchEformularyParameter_state").val() != null 
				&& $("#searchEformularyParameter_state").val() != ""
				&& $("#searchEformularyParameter_state").val() > 0)
			return true;
		else
			return false;
	}
	
	/**
	 * Check whether the first competing drug has been selected or not.
	 */
	function checkFirstCompetingDrugSelected() {
		if ($("#searchEformularyParameter_firstCompetingBrand").val() != null 
				&& $("#searchEformularyParameter_firstCompetingBrand").val() != ""
				&& $("#searchEformularyParameter_firstCompetingBrand").val() > 0)
			return true;
		else
			return false;
	}
	
	/**
	 * Check whether the second competing drug has been selected or not.
	 */
	function checkSecondCompetingDrugSelected() {
		if ($("#searchEformularyParameter_secondCompetingBrand").val() != null 
				&& $("#searchEformularyParameter_secondCompetingBrand").val() != ""
				&& $("#searchEformularyParameter_secondCompetingBrand").val() > 0)
			return true;
		else
			return false;
	}
	
	/**
	 * Check whether any plan is shown is the result table.
	 */
	function checkPlanDisplayed() {
		if ($("[id^='formularyId-']").length > 0)
			return true;
		else
			return false;
	}
	
	/**
	 * Check whether any plan has been selected.
	 */
	function checkPlanSelected() {
		initPlansInput();
		if ($("input[id^='searchEformularyParameter_plans_']").length > 0)
			return true;
		else
			return false;
	}
	
	/**
	 * Check whether a specific plan has been selected.
	 */
	function checkPlanSelectedById(id) {
		initPlansInput();
		for (var i = 0; i < $("input[id^='searchEformularyParameter_plans_']").length; i++) {
			if (id == $("#searchEformularyParameter_plans_" + i).val()) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Check whether any plan has been selected by type category.
	 */
	function checkPlanSelectedByType(category) {
		initPlansInput();
		if ($(category + " input[id^='checkbox_choosePlan_'][checked]").length > 0)
			return true;
		else
			return false;
	}
	
	/**
	 * Initialize choose plans input into form.
	 */
	function initPlansInput() {
		var selectSize = 0;
		$("#hidden_plans_div").html("");
		var hiddenDivStr = "";
		$("input[id^='checkbox_choosePlan_'][checked]").each( function() {
			hiddenDivStr += '<input type="hidden" id="searchEformularyParameter_plans_' + selectSize + '" name="plans" value="' + $(this).attr('planid') + '"/>';
			selectSize++;
		});
		if (selectSize > 10) {
			return false;
		} else {
			$("#hidden_plans_div").append(hiddenDivStr);
		}
		return true;
	}
	
	/**
	 * Check selected plans num.
	 */
	function checkSelectedPlans() {
		var selectSize = $("input[id^='checkbox_choosePlan_'][checked]").length;
		if (selectSize > 10) {
			return false;
		}
		return true;
	}
	
	/**
	 * Check whether a string has white space.
	 */
	function isNotHaveWpace(str) {
		var whitespace = " \t\n\r";
		var i;
		for (i = 0; i < str.length; i++) {
			var c = str.charAt(i);
			if (whitespace.indexOf(c) >= 0) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * For debug.
	 */
	function debugFormInput() {
		var infoStr = "searchEformularyParameter_drug: " + $("#searchEformularyParameter_drug").val() + "\r\n";
		infoStr += "searchEformularyParameter_state: " + $("#searchEformularyParameter_state").val() + "\r\n";
		infoStr += "searchEformularyParameter_regex: " + $("#searchEformularyParameter_regex").val() + "\r\n";
		infoStr += "searchEformularyParameter_planType: " + $("#searchEformularyParameter_planType").val() + "\r\n";
		infoStr += "searchEformularyParameter_firstCompetingBrand: " + $("#searchEformularyParameter_firstCompetingBrand").val() + "\r\n";
		infoStr += "searchEformularyParameter_secondCompetingBrand: " + $("#searchEformularyParameter_secondCompetingBrand").val() + "\r\n";
		infoStr += "searchEformularyParameter_seaderName: " + $("#searchEformularyParameter_seaderName").val() + "\r\n";
		infoStr += "searchEformularyParameter_seaderMail: " + $("#searchEformularyParameter_seaderMail").val() + "\r\n";
		infoStr += "searchEformularyParameter_receiverName: " + $("#searchEformularyParameter_receiverName").val() + "\r\n";
		infoStr += "searchEformularyParameter_receiverMail: " + $("#searchEformularyParameter_receiverMail").val() + "\r\n";
		infoStr += "searchEformularyParameter_planTypeCategories: " + $("#searchEformularyParameter_planTypeCategories").val() + "\r\n";
		alert(infoStr);
	}
	
	/**
	 * Set the dropdown to a specific state.
	 */
	function setState(state) {
		$("#eformularyState").setSelectedValue(state);
	}

	/**
	 * Find state by google location region.
	 */
	function findState(eformularyStateArray, googleLocation) {
		if (eformularyStateArray.length > 0) {
			for ( var i = 0; i < eformularyStateArray.length; i++) {
				if (eformularyStateArray[i].stateAbbr == googleLocation) {
					return eformularyStateArray[i].stateId;
				}
			}
		}
		return "";
	}

})(jQuery);
