YAHOO.namespace('mqHumana');

//Function used for Image rotation on Humana home page
YAHOO.mqHumana.transition = function() {

	//It's the home page if it has an id of "transition-images"
	var homePage = document.getElementById('transition-divs');
	
	if(homePage) {
		
		var transitionDivCol = new Array();

		//Transition Item Object
		function Div(divObj,imageId,divContent) {
			this.divObj = divObj;
			this.imageId = imageId;
			this.divContent = divContent;
		}

		//Get Collection of Transition Items
		var transitionDivs = YAHOO.util.Dom.getChildren('transition-divs');

		//Instantiate a Transition Item
		for(div in transitionDivs){
			var transitionDiv = transitionDivs[div];
			var transitionDivImg = YAHOO.util.Dom.getFirstChild(transitionDivs[div]);
			transitionDivImg.id = "transition-image-"+div;
			var transitionDivContent = YAHOO.util.Dom.getNextSibling(transitionDivImg);
			var divObj = new Div(transitionDiv,transitionDivImg.id,transitionDivContent);
			transitionDivCol.push(divObj);
		}//end for

		//Initialize variables
		var count = 0;
		var replay = 0;
		var currentDivImg = document.getElementById('transition-image-0');

		//Recursively call this function to rotate images		
		YAHOO.mqHumana.rotateItems = function() {
			if(count < transitionDivCol.length){
				if (count>0) {
					//Hide the previous slide
					YAHOO.util.Dom.setStyle(transitionDivCol[count-1].divObj, 'opacity', 0);

					//Show the current slide
					transitionDivCol[count-1].divObj.style.left = "-3000px";
					transitionDivCol[count-1].divObj.style.display = "none";
					transitionDivCol[count].divObj.style.left = "0px";
				}
				if (replay > 0 && count <3){

					var currentSlide = document.getElementById(transitionDivCol[count].divObj.id);
					currentSlide.style.display = "block";
					YAHOO.util.Dom.setStyle(currentSlide, 'opacity', 0);
					var currentDivImgEffect = new YAHOO.util.Anim(currentSlide);
					currentDivImgEffect.attributes.opacity = {to: 1};
					currentDivImgEffect.attributes.duration = 20.8;
					currentDivImgEffect.animate();
					count++;

				} else {
					//Let's implement a fade effect for the image
					// currentDivImg = document.getElementById('transition-image-' + (count));
					var currentSlide = document.getElementById(transitionDivCol[count].divObj.id);
					currentSlide.style.display = "block";
					YAHOO.util.Dom.setStyle(currentSlide, 'opacity', 0);
					var currentDivImgEffect = new YAHOO.util.Anim(currentSlide);
					currentDivImgEffect.attributes.opacity = {to: 1};
					currentDivImgEffect.attributes.duration = 20.8;
					currentDivImgEffect.animate();
					count++;	
				}

			} 
			if(count != 3) {
				t = setTimeout("YAHOO.mqHumana.rotateItems()", 6000);	
			} 
			if(count == 3){
				//Replay link
				var replayLink = document.getElementById('replay');
				replayLink.onclick = function(){
					count=0;
					replay=0;
					for(div in transitionDivs){
						if(div == 0) {
							transitionDivs[div].style.left = "0px";
							transitionDivs[div].style.display = "block";
							YAHOO.util.Dom.setStyle(transitionDivs[div], 'opacity', 0);
							var firstDivImgEffect = new YAHOO.util.Anim(transitionDivs[div]);
							firstDivImgEffect.attributes.opacity = {to: 1};
							firstDivImgEffect.attributes.duration = 20.8;
							firstDivImgEffect.animate();
							replay++;
						} else {
							transitionDivs[div].style.left = "-3000px";
						}
					}//end for
					t = setTimeout("YAHOO.mqHumana.rotateItems()", 0);
					// YAHOO.mqHumana.rotateItems();
				}
			}

		}//end function
		
		YAHOO.mqHumana.rotateItems();
			
	}
		
}


//Replay the slide show on the home page
YAHOO.mqHumana.replaySlideShow = function(){
	
	var homePage = document.getElementById('home-page');
	var replayLink = document.getElementById('replay');
	
	if(homePage && replayLink){
		replayLink.onclick = function(){

			YAHOO.mqHumana.transition();
		}
	}
	
}

function checkKey()
{
	if (window.event.keyCode == 13)
	{
		//alert("you hit return!");
		getProviders() ;
    }
}
//Clear Search box when in focus
YAHOO.mqHumana.showHideDiv = function(el, caller, targetHeight) {
	
	if (typeof targetHeight === 'undefined') {
		var stopHeight = 0;
	} else {
		var stopHeight = targetHeight;
	}
	
	var elReg = YAHOO.util.Dom.getRegion(el);
	var height = (elReg.bottom - elReg.top);
	var elId = YAHOO.util.Dom.get(el).id.replace('-','');

	var toggleArrow = function() {
		if (YAHOO.util.Dom.hasClass(caller, 'collapsed')) {
			YAHOO.util.Dom.removeClass(caller, 'collapsed');
		} else {
			YAHOO.util.Dom.addClass(caller, 'collapsed');
		}
	};

	if (height == stopHeight) {
		var origHeight = eval('YAHOO.mqHumana.orig' + elId + 'Value;');
		var myAnim = new YAHOO.util.Anim(el, { height: { to: origHeight } }, 0.67, YAHOO.util.Easing.easeOut);
		myAnim.onStart.subscribe(toggleArrow);
	} else {
		eval('YAHOO.mqHumana.orig' + elId + 'Value = ' + height + ';');
		var myAnim = new YAHOO.util.Anim(el, { height: { to: stopHeight } }, 0.67, YAHOO.util.Easing.easeOut); 
		myAnim.onComplete.subscribe(toggleArrow);
	}
	
	myAnim.animate();
	
}

//Clear Search box when in focus
YAHOO.mqHumana.clearTextOnFocus = function() {
	
	var clearText = function() {
		var searchQuery = document.getElementById('search-query');
		searchQuery.value = '';
	}
	
	YAHOO.util.Event.addListener('search-query','click',clearText);

}

//Contextual Definition Box function
YAHOO.mqHumana.contextualBox = function() {

	var generalContentPage = document.getElementById('general-content');
	
	if(generalContentPage) {
		
		var defTerms = YAHOO.util.Dom.getElementsByClassName('definition-term');
		var defContainer = document.getElementById('definition-info'); //This is the hidden div containing the body of the contextual popup box
		var defTerms = YAHOO.util.Dom.getElementsByClassName('definition-term'); //These are all the terms that will have a contextual popup box

		//Onclick the popup box closes
		var closeBox = document.getElementById('close');
		closeBox.onclick = function () {
			defContainer.style.display = "none";
		}
		
		var showPopup = function(term) {

			var definition = YAHOO.util.Dom.getNextSibling(term); //Get next sibling of each definition term, which will contain the definition
			defContainer.style.display = "block"; //Show the popup box
			
			defTerms[defTerm].id = "definition-term-"+defTerm;
			var defContainerChildren = YAHOO.util.Dom.getChildren('definition-list'); //Get the dl
			defContainerChildren[0].innerHTML = term.innerHTML; // Populate the title of the contextual popup box
			defContainerChildren[1].innerHTML = definition.innerHTML; //Populate the body of the contextual popup box
			
			var defObj = null;
			defObj = document.getElementById(defTerms[defTerm].id);
			
			var definition = null;
			definition = YAHOO.util.Dom.getNextSibling(defObj);
			
			//Apply onclick event
			defTerms[defTerm].onclick = function () {
				
				//Get the markup that holds the popup box and show it
				var defContainer = document.getElementById('definition-info');
				defContainer.style.display = "block";
				
				//Get the markup for the children of the markup that holds the popup - it's a <dl>
				var defContainerChildren = YAHOO.util.Dom.getChildren('definition-list');
				defContainerChildren[0].innerHTML = defObj.innerHTML;
				defContainerChildren[1].innerHTML = definition.innerHTML; 	
				
				//Get the xy coordinations of the definition term so we know where to place the popup
				var pos = YAHOO.util.Dom.getXY(this);
				var xPos = pos[0];
				var yPos = pos[1];
				
				//Reposition the popup box according the xy coordinations of the definition term
				var posNew = new Array();
				posNew[0] = xPos + 85;
				posNew[1] = yPos - 28;
				YAHOO.util.Dom.setXY(defContainer, posNew);
			}
			
			var pos = YAHOO.util.Dom.getXY(term);  //Get the xy coordinations of the definition term so we know where to place the popup
			var xPos = pos[0];
			var yPos = pos[1];

			var posNew = new Array(); //Reposition the popup box according the xy coordinations of the definition term
			posNew[0] = xPos + 85;
			posNew[1] = yPos - 28;
			YAHOO.util.Dom.setXY(defContainer, posNew);
		}//end showPopup function
		
		//For all the definition terms in the page, do the following
		for(defTerm in defTerms) {	
			
			defTerms[defTerm].onclick = function(){
				showPopup(this);
			}					
		}//end for
		
	}//end if
	
}//end function

//Animate the top Menu
YAHOO.mqHumana.yuiMenu = function(){

	var yuiMenuItems = YAHOO.util.Dom.getElementsByClassName('yuimenuitem'); 
	
	if(yuiMenuItems){
		
		for(var i=0;i<yuiMenuItems.length;i++){
			var obj = yuiMenuItems[i];
			obj.onmouseover = function(){
				this.parentNode.parentNode.parentNode.parentNode.firstChild.style.backgroundImage="url(../img/gradients/grad-menu-hover.png)";
				this.parentNode.parentNode.parentNode.parentNode.firstChild.style.backgroundPositionX = "0px";
				this.parentNode.parentNode.parentNode.parentNode.firstChild.style.backgroundPositionY = "0px";
			}
			obj.onmouseout = function(){
				this.parentNode.parentNode.parentNode.parentNode.firstChild.style.backgroundImage="";
			}

		}
		
	}
	
    var oMenuBar = new YAHOO.widget.MenuBar("main-menu", { 
                                                   autosubmenudisplay: true, 
                                                   hidedelay: 0, 
                                                   lazyload: false });

       /*
            Call the "render" method with no arguments since the 
            markup for this MenuBar instance is already exists in 
            the page.
       */

       oMenuBar.render();

}

YAHOO.mqHumana.genericModalFromMarkup = function(div, formId) {
	
	YAHOO.util.Dom.setStyle(div, 'display', 'block');
	var form = YAHOO.util.Dom.get(formId);
	
	var handleSuccess = function(o) {
		var response = o.responseText;
		response = response.split("<!")[0];
		document.getElementById("resp").innerHTML = response;
	};
	var handleFailure = function(o) {
		alert("Submission failed: " + o.status);
	};

	var handleClose = function() {
		this.hide();
	};
	
	//initialize simple dialog defaults
	var myDialog = new YAHOO.widget.Dialog(div, { 
		width: '682px', 
		fixedcenter: false,
		y: 12,
		x: parseInt((YAHOO.util.Dom.getViewportWidth()/2)-341),
		effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.25}, 
		modal:true,
		visible:false,
		draggable:false
	});
	
	//Validate the entries in the form to require that both first and last name are entered
	myDialog.validate = function() {
		var data = this.getData();
	};

	// Wire up the success and failure handlers
	myDialog.callback = { success: handleSuccess,
						  failure: handleFailure 
						 };

	myDialog.render(document.body); 
	myDialog.show();					

}//end function

//Cancel Form Submission
YAHOO.mqHumana.cancelForm = function(){
/*	var contactUsPage = document.getElementById('contact-us');
	if(contactUsPage){
		var cancelLink = document.getElementById('cancel');	
		cancelLink.onclick = function(){
			var form = document.getElementById('form');
			var formElements = form.getElementsByTagName('input');
			var textArea = form.getElementsByTagName('textarea');
			textArea[0].value = "";
			document.forms['form'].cbReceiveUpdate.checked = false; //Reset the checkbox
			document.forms['form'].drpSubjectType.selectedIndex = 0; //Reset the selectbox
			for(elem in formElements){
				formElements[elem].value = "";
			}
			
		}
	}*/
}//end function

function ContactFormCancel(){
	var contactUsPage = document.getElementById('contact-us');
	if(contactUsPage){
		var form = document.getElementById('form');
			var formElements = form.getElementsByTagName('input');
			var textArea = form.getElementsByTagName('textarea');
			textArea[0].value = "";
			document.forms['form'].cbReceiveUpdate.checked = true; //Reset the checkbox 
			document.forms['form'].drpSubjectType.selectedIndex = 0; //Reset the selectbox
			 
			var theFormElements =  document.forms['form'].elements;
			 
			var field_type ='';
			for(i=0; i<theFormElements.length; i++) {
				field_type = theFormElements[i].type.toLowerCase();

				switch(field_type) {
					case "text":
						theFormElements[i].value = "";
						break;

					default:
					break;	
				}
			}

			//for(elem in formElements){
			//	 	formElements[elem].value = "";
			//}
	}
}


//Let's load 'em all up
YAHOO.util.Event.onContentReady('main-menu',function() {
	YAHOO.mqHumana.yuiMenu();
	YAHOO.mqHumana.transition();
	YAHOO.mqHumana.clearTextOnFocus();
	YAHOO.mqHumana.contextualBox();
	YAHOO.mqHumana.cancelForm(); 		
});


//**************************************** Begin Provider Search Modal Code **************************************


YAHOO.mqHumana.providersSearchModal = function(strPlanCode, strAppId, enroll, mbrId) {
    debugger;
    //alert('Hi');
    var planCode = '';
    var memberId = '';
    if (strPlanCode != null && strPlanCode != "") {
        planCode = strPlanCode;

        //disablePlanSelection();
    }
    var applicationId = '';
    if (strAppId != null && strAppId != "") {
        applicationId = strAppId;
    }
    var fmEnroll = '';
    if (enroll != null && enroll != "") {
        //updateExistingEnrollmentPanel();
        fmEnroll = enroll;
        if (mbrId != null && mbrId != "") {
            memberId = mbrId;
        }

    }

    YAHOO.namespace("providersearch.container");

    var handleSuccess = function(o) {

    };
    var handleFailure = function(o) {
        alert("Submission failed: " + o.status);
    };

    var handleClose = function() {
        //******************** BEGIN TERENCES CHANGES *****************************************
        // Before we hide the modal, we need to show all dropdowns on the parent (only for IE6)
        if (YAHOO.env.ua.ie == 6) {
            changeDisplayOnParentSelects('');
        }
        //******************** END TERENCES CHANGES *****************************************
        this.hide();
    };
    debugger;
    if (YAHOO.providersearch.container.search_area == null) {
        //initialize simple dialog defaults
        YAHOO.providersearch.container.search_area = new YAHOO.widget.Dialog("search-area", {
            width: '682px',
            minHeight: '680px',
            fixedcenter: false,
            y: 12,
            x: parseInt((YAHOO.util.Dom.getViewportWidth() / 2) - 341),
            effect: { effect: YAHOO.widget.ContainerEffect.FADE, duration: 0.25 },
            modal: true,
            visible: false,
            constraintoviewport: true,
            autofillheight: "body"
        });
        alert('Search_area');
        //******************** BEGIN TERENCES CHANGES *****************************************
        // Add code to handle close event
        YAHOO.providersearch.container.search_area.hideEvent.subscribe(handleClose);
        //******************** END TERENCES CHANGES *****************************************

        // Set up keystroke handler for "enter" key		
        var kl = new YAHOO.util.KeyListener(document, { keys: 13 },
							      { fn: getProviders,
							          scope: YAHOO.providersearch.container.search_area,
							          correctScope: true
							      });

        YAHOO.providersearch.container.search_area.cfg.queueProperty("keylisteners", kl);
    }
    else {
        // Set the height of the panel back to the minHeight
        YAHOO.providersearch.container.search_area.cfg.setProperty("height", "760px");
    }
    // fix for FireFox bug

    if (YAHOO.env.ua.gecko) {
        YAHOO.providersearch.container.search_area.cfg.setProperty("height", "760px");
    }
    //alert();
    //Validate the entries in the form to require that both first and last name are entered
    YAHOO.providersearch.container.search_area.validate = function() {
        var data = this.getData();
    };

    // Wire up the success and failure handlers
    YAHOO.providersearch.container.search_area.callback = { success: handleSuccess,
        failure: handleFailure
    };
    //******************** BEGIN TERENCES CHANGES *****************************************							 
    // Before we show the modal, we need to hide all dropdowns on the parent (only for IE6)
    if (YAHOO.env.ua.ie == 6) {
        changeDisplayOnParentSelects('none');
    }
    //******************** END TERENCES CHANGES *****************************************						 

    YAHOO.providersearch.container.search_area.setBody("");
    YAHOO.providersearch.container.search_area.render();
    YAHOO.providersearch.container.search_area.show();

    getSearchArea(planCode, applicationId, fmEnroll, memberId);


}   //end function


function successHandler(o){
	YAHOO.log("Success handler called; handler will parse the retrieved XML and insert into DOM.", "info", "example");
	//alert("RL2");

	var searchAreaDiv = findDiv(o.responseXML, "search-area");
	var resultsNode = document.getElementById("search-area");
	
	var innerContent = '';
	
	// Must check for browser here since IE handles this differently than FireFox
	if(YAHOO.env.ua.ie) {
		innerContent = searchAreaDiv.xml;
	}
	else
	{
		var newDiv = document.createElement("div");
		newDiv.setAttribute("id", "foo");
		// Begin Terence's Fix for Safari
		var importNode = searchAreaDiv.cloneNode(true);
		newDiv.appendChild(importNode);
		// End Terence's Fix for Safari
		innerContent = newDiv.innerHTML;		
	}
	/*alert(innerContent.substring(1,255));
	alert(innerContent.substring(256,511));
	alert(innerContent.substring(511,766));*/
	resultsNode.childNodes[1].innerHTML = innerContent;
	
	// Expand the "More Options" link
	//YAHOO.mqHumana.showHideDiv('more-options', YAHOO.util.Dom.get('more-options-link'), 185);
	
	// Set the default focus to the ZIP code field
	var searchProviders = document.getElementById('searchProviders');

	if (searchProviders != null)
	{	
		searchProviders.txtZipCode.focus();
	}
	if (searchProviders.planSelected.value == "true"){
		disablePlanSelection();
	}
	YAHOO.log("Success handler is complete.", "info", "example");
}

function failureHandler(o){
	YAHOO.log("Failure handler called; http status: " + o.status, "info", "example");
	alert(o.statusText);
	div.innerHTML = o.status + " " + o.statusText;
}

function getSearchArea(planCode,appId,fmEnr,mId){
	//alert("PlanCode:"+planCode);

	var entryPoint = '/Public/Search/search-providers-ajax-final.aspx?calledFromModal=T';
	if(planCode != ''){
		entryPoint= entryPoint+"&planA="+planCode;
		
	}
	if(appId != ''){
		entryPoint= entryPoint+"&customerId="+appId;
	}
	
	if(fmEnr != ''){
		entryPoint= entryPoint+"&fromEnroll="+fmEnr;
	}
	if(mId != ''){
		entryPoint= entryPoint+"&memberId="+mId;
	}
	//alert("entryPoint:"+entryPoint);	
	var sUrl = entryPoint;

	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success:successHandler, failure:failureHandler });
	//alert (request );
}

function findDiv(respXML, divId)
{
	var divs = respXML.getElementsByTagName('div');
	var foundDiv = null;

	for ( i = 0; i < divs.length; i ++ ) {
	  if ( divs.item(i).getAttribute('id') == divId ) {
	    foundDiv = divs.item(i);
	    break;
	  }
	}
	return foundDiv;
}

//******************** BEGIN TERENCES CHANGES *****************************************
function changeDisplayOnParentSelects(displayValue)
{
	var selects = document.getElementsByTagName("select");

	for ( i = 0; i < selects.length; i ++ ) {
		selects[i].style.display=displayValue;
	}
}
//******************** END TERENCES CHANGES *****************************************


//**************************************** End Provider Search Modal Code **************************************


//**************************************** Begin Provider Search AJAX **************************************

getResultsPage = function(strPageInfo) {
	getProviders('pagingInfo=' + strPageInfo);
}

sortResults = function(strSortBy) {
	getProviders('sortBy=' + strSortBy);
}


viewAllProviders = function(strPageSize) {
	if (strPageSize == null || strPageSize == "")
	{
		// Default this just in case
		strPageSize = 10;
	}
	getProviders('viewAllRecords=T&pageSize=' + strPageSize);
}


getProviders = function(strArgs) {
	//alert("RL1");
	YAHOO.namespace("YAHOO.providersearch.container");
	// Get a handle to the form
	var searchProviders = document.getElementById('searchProviders');

	// clear any existing validation errors
	clearExistingErrors();
	var selectedPlanNew = searchProviders.drpPlan[searchProviders.drpPlan.selectedIndex].value;
	var selectedProviderTypeNew = getRadioValue('rblProviderType');
	
	if(selectedProviderTypeNew == "V" && selectedPlanNew == "FOCUS"){
		var selectedZIP = searchProviders.txtZipCode.value;
		 
			EyemedPopup(selectedZIP);	
			return;
	}

	// Validate it
	if(FIC_checkForm(searchProviders, true))
	{		
		if (!YAHOO.providersearch.container.wait)
		{
			YAHOO.providersearch.container.wait =  
					new YAHOO.widget.Panel("wait",   
					    { width:"150px",  
					      fixedcenter:true,  
					      close:false,  
					      draggable:false,  
					      zindex:6, 
					      modal:true, 
					      visible:false,
					      height:"55px",
					      underlay:"none"
					    }  
					); 
		}
	

		YAHOO.providersearch.container.wait.setBody('<div class="copy">Please wait&nbsp;&nbsp; <img src="/Public/ImagePath/img/icons/ajax-loader.gif" /></div>'); 
		YAHOO.providersearch.container.wait.render(document.body);	
		var callback = { 
				    success : function(o) { 
					//var searchResultsDiv = findDiv(o.responseXML.documentElement, "search-results");
					 
					var resultsNode = document.getElementById("search-results-container");
					//var resultsNode = document.getElementById("empty-results");
					
					resultsNode.innerHTML = o.responseText;					
					jumpToTopOfResults();
					
					// Only call this code in the modal
					if (YAHOO.providersearch.container.search_area != null)
					{
						document.getElementById("search-area").childNodes[1].style.height=resultsNode.scrollHeight + 150;
						// Fix for FireFox bug
						// Begin Terence's Fix for Safari
						if (o.responseText.length > 3000) {
						    if (YAHOO.env.ua.gecko || YAHOO.env.ua.webkit) {
						        YAHOO.providersearch.container.search_area.cfg.setProperty("height", "1400px");
						    }
						}
						// End Terence's Fix for Safari
						//IE fix for minimum height
						if (o.responseText.length < 3000) {
						    if (YAHOO.env.ua.ie >= 7 || YAHOO.env.ua.gecko || YAHOO.env.ua.webkit) {
						        YAHOO.providersearch.container.search_area.cfg.setProperty("height", "780px");
						    }

						}
						// End Terence's Fix for Safari
					}

					YAHOO.providersearch.container.wait.hide();
					
					if(document.getElementById("hrefDownload") != null && searchProviders.calledFromModal.value != 'T')
						document.getElementById("hrefDownload").style.visibility = 'visible';
					if(document.getElementById("lblToNoOfRecords") != null && searchProviders.calledFromModal.value != 'T')
						document.getElementById("lblToNoOfRecords").style.visibility = 'visible';	
					if(document.getElementById("lblLegislationText") != null )
					{
						document.getElementById("lblLegislationText").style.visibility = 'visible';
						document.getElementById("lblLegislationText").className='ShowLegislationText';
					}						
					if(document.getElementById("sortBy") != null)						
						document.getElementById("sortBy").value = data.substring(7,15);										
				    }, 
				    failure : function(o) { 
					// Uncomment this for debugging purposes
					alert("Failure: " + o.status + " Text: " + o.statusText);
					YAHOO.providersearch.container.wait.hide(); 
				    } 
				} 

		YAHOO.providersearch.container.wait.show(); 

		var entryPoint = '/Public/Search/search-providers-ajax-final-results.aspx';


		var sUrl = entryPoint;
		var data='';

		if (strArgs != null)
		{
			data = strArgs + "&";
		}

		var selectedZipCode = searchProviders.txtZipCode.value;
		data = data + "txtZipCode=" + selectedZipCode;
		enablePlanSelection();
		var selectedPlan = searchProviders.drpPlan[searchProviders.drpPlan.selectedIndex].value;
		data = data + "&drpPlan=" + selectedPlan;

		var selectedProviderLastName = searchProviders.txtProviderLastName.value;
		data = data + "&txtProviderLastName=" + selectedProviderLastName;

		var selectedProviderType = getRadioValue('rblProviderType');
		data = data + "&rblProviderType=" + selectedProviderType;

		var selectedRadius = searchProviders.drpRadius[searchProviders.drpRadius.selectedIndex].value;
		data = data + "&drpRadius=" + selectedRadius;

		var selectedSelectedSpecialty = searchProviders.drpSpeciality[searchProviders.drpSpeciality.selectedIndex].value;	
		data = data + "&drpSpeciality=" + selectedSelectedSpecialty;

		var calledFromModal = searchProviders.calledFromModal.value;	
		data = data + "&calledFromModal=" + calledFromModal;
		var acceptsNewPatients = getCheckBoxValue('acceptsNewPts');
		data = data + "&acceptsNewPts=" + acceptsNewPatients;
		var selectedFacilityId = searchProviders.txtFacilityID.value;
		data = data + "&txtFacilityID=" + selectedFacilityId;
		
		var selectedFacilityName = searchProviders.txtFacilityName.value;
		data = data + "&txtFacilityName=" + selectedFacilityName;
		
		if (searchProviders.fmEnroll.value != ""){
			data = data + "&fromEnroll=" + searchProviders.fmEnroll.value;
		} 
		
		var formObject = document.getElementById('searchProviders');
		 
		var request = YAHOO.util.Connect.asyncRequest('POST', sUrl, callback,data);
		 
	}

}
function getCheckBoxValue(cbName){
	var element = document.getElementById(cbName);	
	var result ='Y';
	if(!element.checked == true){
		result = 'N';
	}
	return result;
}

function getRadioValue(idOrName) {
        var value = null;
        var element = document.getElementById(idOrName);
        var radioGroupName = null;  
        
        radioGroupName = idOrName;
        
        if (radioGroupName == null) {
                return null;
        }
        var radios = document.getElementsByTagName('input');
        for (var i=0; i<radios.length; i++) {
                var input = radios[ i ];    
                if (input.type == 'radio' && input.name == radioGroupName && input.checked) {                          
                        value = input.value;
                        break;
                }
        }
        return value;
}

function clearExistingErrors()
{
		//clear any earlier validation
		var msgBoxes = YAHOO.util.Dom.getElementsByClassName('messages', 'ul');
		for(var y in msgBoxes) {
			msgBoxes[y].innerHTML = '';
		}

		var invalidRows = YAHOO.util.Dom.getElementsByClassName('invalid', 'div');
		for(var y in invalidRows) {
			removeClassName(invalidRows[y],'invalid');
		}

}
function jumpToTopOfResults (){window.location.hash="search-area";}

function providerSelected(providerId,facilityId,plan,acceptsChildren,minAge,appId)
{
	YAHOO.namespace("YAHOO.providersearch.container");
	 
	
	var callback1 = { 
				    success : function(o) { 
				    //alert ("Parent:"+o.)
					//var searchResultsDiv = findDiv(o.responseXML.documentElement, "search-results");
					//alert("RL11");
					
					if(o.responseText.indexOf("Success") != -1){
						//success
						//close the modal 
						//__doPostBack('', 'Reload');
						//updateParent('Reload');
						//window.opener.location.reload();
						//alert("Href:"+document.location.href);
						//YAHOO.providersearch.container.search_area.hide();
						//window.location.href = document.location.href; 
						//if(fromEnroll == 'Y'){
						updateEnrollPanel(providerId);
						YAHOO.providersearch.container.search_area.hide();
						//	redirectUser();
							//redirectUser1();
							//__doPostBack = newDoPostBack;
							
						//}
						//Refresh the current browser window.
						//window.location.reload(true);
						
						//window.opener.reload();
						//window.close();

						
					}else{
									
						var resultsNode1 = document.getElementById("provider-select-error");
					
						resultsNode1.innerHTML = o.responseText;

						jumpToTopOfResults();
					}
					
					// Only call this code in the modal
				/*	if (YAHOO.providersearch.container.search_area != null)
					{
						document.getElementById("search-area").childNodes[1].style.height=resultsNode.scrollHeight + 150;
						// Fix for FireFox bug
						if(YAHOO.env.ua.gecko) {	
							 YAHOO.providersearch.container.search_area.cfg.setProperty("height", "760px");
						}
					}
				*/	
					//YAHOO.providersearch.container.wait.hide();
					

				    }, 
				    failure : function(o) { 
					// Uncomment this for debugging purposes
					alert("Failure: " + o.status + " Text: " + o.statusText);
					//YAHOO.providersearch.container.wait.hide(); 
				    } 
				} 


	//var entryPoint = '/insurance-enrollment-1.aspx?';
	var entryPoint = '/Public/Search/search-providers-ajax-final-results.aspx';
	var data='';
	//data = data +"productId=132";
	//PlanCode={0}&ProviderID={1}&FacilityID={2}
	data = data + "providerId=" + providerId;
	data = data + "&facilityId=" + facilityId;
	data = data + "&minAge=" + minAge;
	data = data + "&acceptsChildren=" + acceptsChildren;
	
	var searchProviders = document.getElementById('searchProviders');
	if (searchProviders.custId.value != ""){
		data = data + "&Id=" + searchProviders.custId.value;
	} 
	
	
//	debugger;
	
	var request = YAHOO.util.Connect.asyncRequest('POST', entryPoint, callback1,data);
	//top.location= entryPoint+data;
	//return true;
	
}
function disablePlanSelection(){
	var selects = document.getElementsByTagName('select');
        for (var i=0; i<selects.length; i++) {
                var element = selects[ i ];   
                //alert("Name:"+element.name) ;
                if (element.name == "drpPlan" ) {                          
                    element.disabled = true; 
                    //element.readonly = true;   
                    //alert("Disabled")   ;
                    break;
                }
        }

 
	
}
function enablePlanSelection(){
	var selects = document.getElementsByTagName('select');
        for (var i=0; i<selects.length; i++) {
                var element = selects[ i ];   
                //alert("Name:"+element.name) ;
                if (element.name == "drpPlan" ) {                          
                    //element.disabled = false;  
                    element.readonly = true;  
                    //alert("Enabled")   ;
                    break;
                }
        }

} 

function redirectUser(){
	window.location = '/insurance-enrollment-1.aspx';
}	

function newDoPostBack(eventTarget, eventArgument)
{    var theForm = document.forms[0];  
  if (!theForm)    {  
      theForm = document.aspnetForm;    } 
    if (!theForm.onsubmit || (theForm.onsubmit() != false))    {  
      document.getElementById("__EVENTTARGET").value = eventTarget; 
       document.getElementById("__EVENTARGUMENT").value = eventArgument;  
      theForm.submit();    }
}
 

//**************************************** End Provider Search AJAX **************************************

function toggleVisibility(id) {
	var el;
	if (document.getElementById) 
	{
		el = document.getElementById(id);
	} 
	else if (document.all) 
	{
		el = document.all[id];
	}

	if (el && (el = el.style) && ('string' == typeof el.visibility)) 
	{
		el.visibility = ('hidden' == el.visibility ? 'visible' :'hidden');
	}
}

function updateEnrollPanel(pId)
{
	// find out the selected div
	var providerName = '';
	var selectedDiv =  document.getElementById(pId);
	//alert(pId);
	var form = document.forms[1];
	var depIdLabel = '';
	// extract the provider name
	if(selectedDiv != null){
		providerName = selectedDiv.innerHTML;
		
		if(form != null){
		//alert("Selected Provider:"+providerName + " form :" + form );
			var theFormElements =  document.forms[1].elements; 
			//get the member info to update the correct labels
			var searchProviders = document.getElementById('searchProviders');
			if(searchProviders != null){
				depIdLabel = searchProviders.memberLabelId.value;
			}
			//debugger;
			if (depIdLabel == "P")	{
				// It is the primary
				//Change the primary
				var btnVal = document.getElementById("applicantControl_btnSelectApplProvider");
				if (btnVal != null){
					//theFormElements["applicantControl_btnSelectApplProvider"].value = "Change";
					//document.getElementById("applicantControl_lblSelectApplProvider").innerHTML = "Change";
				}								
				var selectedSpan = document.getElementById("applicantControl_lblSelectApplProvider");
				if(selectedSpan != null){
					if(document.getElementById("isNewEnrollmentPage")!= null && document.getElementById("isNewEnrollmentPage").value == "True")					
						selectedSpan.innerHTML = providerName;												
					else					
						selectedSpan.innerHTML = providerName.substring(0, providerName.indexOf('<BR>')) ;
									
					document.getElementById("applicantControl_lblSelectApplProvider").text = providerName;					
					//theFormElements["applicantControl:selProviderId"].value = pId;
					document.getElementById("applicantControl_selProviderId").value = pId;	
					
					document.getElementById("applicantControl_lblSelectApplProvider").style.visibility = 'visible';
					//document.getElementById("applicantControl_btnChangeApplProvider").style.visibility = 'visible';
					//document.getElementById("applicantControl_btnSelectApplProvider").style.visibility = 'hidden';
					//document.getElementById("applicantControl_btnSelectApplProvider").style.backgroundImage = "url('../ImagePath/img/buttons/button-change.png')";
					document.getElementById("applicantControl_btnSelectApplProvider").className = 'changeProvider';
					
					
				}		
							 	
				//change the existing sp and deps also
				var selectedSpSpan = document.getElementById("applicantControl_sp1_lblSelectProviderSpDep");
				if(selectedSpSpan != null){
					//alert("Selected spouse span found:");
					if(document.getElementById("isNewEnrollmentPage")!= null && document.getElementById("isNewEnrollmentPage").value == "True")					
						selectedSpSpan.innerHTML = providerName;							
					else					
						selectedSpSpan.innerHTML = providerName.substring(0, providerName.indexOf('<BR>')) ;
					
					document.getElementById("applicantControl_sp1_lblSelectProviderSpDep").text = providerName;					
					theFormElements["applicantControl:sp1:btnSelectProviderSpDep"].value = "Change";
					
					theFormElements["applicantControl:sp1:selProviderId"].value = pId;
				}
				
				var selectedSpNSpan = document.getElementById("applicantControl_spCurr1_lblSelectProviderSpDep");
				
				if(selectedSpNSpan != null){
					//alert("Selected spouse span found:");
					document.getElementById("applicantControl_spCurr1_lblSelectProviderSpDep").style.visibility = 'visible';
					document.getElementById("applicantControl_spCurr1_btnSelectProviderSpDep").style.visibility = 'visible';
					//selectedSpNSpan.innerHTML = providerName;					
					if(document.getElementById("isNewEnrollmentPage")!= null && document.getElementById("isNewEnrollmentPage").value == "True")					
						selectedSpNSpan.innerHTML = providerName;												
					else					
						selectedSpNSpan.innerHTML = providerName.substring(0, providerName.indexOf('<BR>')) ;
						
					document.getElementById("applicantControl_spCurr1_lblSelectProviderSpDep").text = providerName;					
					document.getElementById("applicantControl_spCurr1_btnSelectProviderSpDep").value = "Change";										
					document.getElementById("applicantControl_spCurr1_selProviderId").value = pId;
				}
				for (depCount = 1; depCount < 7; depCount++){
					var spanId = "applicantControl_dep"+depCount+"_lblSelectProviderSpDep";					
					var selectedDepSpan = document.getElementById(spanId);
					if(selectedDepSpan != null){
						//alert("Selected dep span found:");
						//selectedDepSpan.innerHTML = providerName;
						if(document.getElementById("isNewEnrollmentPage")!= null && document.getElementById("isNewEnrollmentPage").value == "True")					
							selectedDepSpan.innerHTML = providerName;												
						else					
							selectedDepSpan.innerHTML = providerName.substring(0, providerName.indexOf('<BR>')) ;
							
						document.getElementById(spanId).text = providerName;
						//applicantControl:dep1:btnSelectProviderSpDep						
						theFormElements["applicantControl:dep"+depCount+":btnSelectProviderSpDep"].value = "Change";
						theFormElements["applicantControl:dep"+depCount+":selProviderId"].value = pId;
						
					}else{
						break;
					}		
				}
				for (depCount = 1; depCount < 7; depCount++){
					var spanId = "applicantControl_depCurr"+depCount+"_lblSelectProviderSpDep";					
					var selectedDepSpan = document.getElementById(spanId);
					if(selectedDepSpan != null){
						//alert("Selected dep span found:");
						document.getElementById("applicantControl_depCurr"+ depCount +"_lblSelectProviderSpDep").style.visibility = 'visible';
						document.getElementById("applicantControl_depCurr"+ depCount +"_btnSelectProviderSpDep").style.visibility = 'visible';
						//selectedDepSpan.innerHTML = providerName;
						if(document.getElementById("isNewEnrollmentPage")!= null && document.getElementById("isNewEnrollmentPage").value == "True")					
							selectedDepSpan.innerHTML = providerName;												
						else					
							selectedDepSpan.innerHTML = providerName.substring(0, providerName.indexOf('<BR>')) ;
						document.getElementById(spanId).text = providerName;						
						document.getElementById("applicantControl_depCurr"+ depCount +"_btnSelectProviderSpDep").value = "Change";											
						document.getElementById("applicantControl_depCurr"+ depCount +"_selProviderId").value = pId;						
					}else{
						break;
					}		
				}
				//window.location.reload( true );	 
				
			} else if(depIdLabel != ''){
				//spouse or deps
				var depSpanId = "applicantControl_"+depIdLabel+"_lblSelectProviderSpDep";				
				var selectedDepSpan = document.getElementById(depSpanId);
				if(selectedDepSpan != null){
					//alert("DepSpanid Found" + depSpanId);
					//selectedDepSpan.innerHTML = providerName;
					if(document.getElementById("isNewEnrollmentPage")!= null && document.getElementById("isNewEnrollmentPage").value == "True")					
						selectedDepSpan.innerHTML = providerName;												
					else					
						selectedDepSpan.innerHTML = providerName.substring(0, providerName.indexOf('<BR>')) ;
						
					document.getElementById(depSpanId).text = providerName;					
					document.getElementById("applicantControl_"+depIdLabel+"_btnSelectProviderSpDep").value = "Change";
					document.getElementById("applicantControl_"+depIdLabel+"_selProviderId").value = pId;										

				}
			}
			if (document.getElementById("applicantControl_txtZip") != null)
				theFormElements["applicantControl:txtZip"].focus();			
		}
		
		
		
		 
	}
	
	// update the panel
}

function updateExistingEnrollmentPanel()
{
	var form = document.forms[1];
	alert("Form1:"+ form);
	//var enrollForm = document.getElementById('general-content');
	if(form != null){
		 
		var theFormElements =  document.forms[1].elements; 
		/*for (i =0 ; i < theFormElements.length;i++)
		{
			alert("element"+i+":"+theFormElements[i].name);
		}*/
		var data='';
		if(theFormElements["applicantControl:txtFirstName"]!= null){
			data = data + "firstName="+theFormElements["applicantControl:txtFirstName"].value;
		}else{
			data = data + "firstName=";
		}
		if(theFormElements["applicantControl:txtLastName"]!= null){
			data = data + "&lastName="+theFormElements["applicantControl:txtLastName"].value;
		}
		if(theFormElements["applicantControl:txtMiddleInitial"]!= null){
			data = data + "&mi="+theFormElements["applicantControl:txtMiddleInitial"].value;
		}
		if(theFormElements["applicantControl:txtDOB"]!= null){
			data = data + "&dob="+theFormElements["applicantControl:txtDOB"].value;
		}
		if(theFormElements["applicantControl:ddlGender"]!= null){
			data = data + "&gender="+theFormElements["applicantControl:ddlGender"].value;
		}
		if(theFormElements["applicantControl:ddlMaritalStatus"]!= null){
			data = data + "&status="+theFormElements["applicantControl:ddlMaritalStatus"].value;
		}
		if(theFormElements["applicantControl:txtEmailAddress"]!= null){
			data = data + "&email="+theFormElements["applicantControl:txtEmailAddress"].value;
		}
		if(theFormElements["applicantControl:txtHomePhone"]!= null){
			data = data + "&hPhone="+theFormElements["applicantControl:txtHomePhone"].value;
		}
		
		if(theFormElements["applicantControl:txtWorkPhone"]!= null){
			data = data + "&oPhone="+theFormElements["applicantControl:txtWorkPhone"].value;
		}
		
		if(theFormElements["applicantControl:txtAddress1"]!= null){
			data = data + "&addr1="+theFormElements["applicantControl:txtAddress1"].value;
		}
		if(theFormElements["applicantControl:txtAddress2"]!= null){
			data = data + "&addr2="+theFormElements["applicantControl:txtAddress2"].value;
		}
		
		if(theFormElements["applicantControl:txtCity"]!= null){
			data = data + "&city="+theFormElements["applicantControl:txtCity"].value;
		}
		
		if(theFormElements["applicantControl:ddlState"]!= null){
			data = data + "&state="+theFormElements["applicantControl:ddlState"].value;
		}
		
		if(theFormElements["applicantControl:txtZip"]!= null){
			data = data + "&hPhone="+theFormElements["applicantControl:txtZip"].value;
		}
		
		var updateEntry = '/insurance-enrollment-1.aspx';
		
		var updCallback = { 
				    success : function(o) { 
					 
						alert("Update success");

				    }, 
				    failure : function(o) { 
					// Uncomment this for debugging purposes
					alert("Failure: " + o.status + " Text: " + o.statusText);
					 
				    } 
		} 
		var request = YAHOO.util.Connect.asyncRequest('POST', updateEntry, updCallback,data); 
	}
	
}
function onChangePlanSelection()
{
	var searchPanel = document.getElementById('searchProviders');
	var selPlan = searchPanel.drpPlan[searchPanel.drpPlan.selectedIndex].value;
	if(selPlan != "")
	{
		 if("VISION" == selPlan || "VCP" == selPlan || "FOCUS" == selPlan)
		 {
			//alert("VCP is selected");
			setRadioValue("V");
		 }
		 else
		 {
			setRadioValue("D"); 
		 }
	}
}
function setRadioValue(rValue)
{
	var radios = document.getElementsByTagName('input');
	for (var i=0; i<radios.length; i++) {
        var input = radios[ i ];    
        if (input.type == 'radio' && input.name == "rblProviderType" && input.value == rValue) {                          
                input.checked = true;
                break;
        }
	}
}

function EyemedPopup(ZIP){
	 
	var target = "EyeMedProviders";
	var windowAttributes = getWindowAttributes();
	var URL = "http://www.eyemedvisioncare.com/locator/ProviderLocator?ClientId=HUMANA";
	if (ZIP == null || ZIP == ""){
	}else{
	 URL = URL +"&zip=" +ZIP
	}
	 
	//var pWindow = window.open( "https://www.eyemedvisioncare.com/memweb/ProviderLocator?ClientId=HMNAAC", target,windowAttributes + ",width=820,height=500" );
	var pWindow = window.open( URL, target,windowAttributes + ",width=820,height=1260" );
	 
	return false;
	//pWindow.moveTo(0,0);

}

function VCPPopup(strURL) {

    var target = "EyeMedProviders";
    var windowAttributes = getWindowAttributes();
    var URL = strURL;

    //var pWindow = window.open( "https://www.eyemedvisioncare.com/memweb/ProviderLocator?ClientId=HMNAAC", target,windowAttributes + ",width=820,height=500" );
    var pWindow = window.open(URL, target, windowAttributes + ",width=820,height=1260");

    return false;
    //pWindow.moveTo(0,0);

}
 
function getWindowAttributes() {
	return "width=800,height=760,toolbar=no,location=no,status=yes,menubar=no,resizable=yes,scrollbars=yes"; //+ ",location=yes,status=yes";
}

