/* Core AJAX Functions.
 * based on the code from the mozilla developer site
 */ 
function getObject()//creates the XMLHttpRequest Object
{
	var http_request = false;
    if (window.XMLHttpRequest)  // for Gecko Browsers
    { 
    	http_request = new XMLHttpRequest();
    	if (http_request.overrideMimeType) 
		{
    		http_request.overrideMimeType('text/xml');
        }
	} 
    else if (window.ActiveXObject) 
	{ // IE
    	try 
		{
    		http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
    	catch (e) 
		{
    		try 
			{
    			http_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
    		catch (e) 
    		{
    			alert("could not create an XMLHttpRequest Object!");
    		}
		}
	}
    return http_request;
}
function sendAjaxRequest(url,params,functionName) 
{
    var http_request = getObject();
    if (!http_request) // This never appears to be true
	{
    	alert('We cannot connect to the server at this time.');
    	return false;
	}
    else
	{
		http_request.onreadystatechange = function() 
		{
			eval(functionName)(http_request);//<=All Praise Cthulhu!
		};
	    http_request.open('GET',(url + "?" +params), true);
        http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        http_request.send(null);  
	}  
}
function sendSjaxRequest(url,params,functionName) 
{
	var http_request = getObject();
	if (!http_request) // This never appears to be true
	{
	  	alert('We cannot connect to the server at this time.');
	  	return false;
	}
	else
  	{
		try
		{
       	    http_request.open('POST', url, false);
	        http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	        http_request.send(params);
		}
		catch(err)
		{
			alert("Experiencing network difficulties.");  // Test by loading the page and stopping the web server.
			return false;
		}
  	}
	return http_request;
}

//===== Begin Ajax Return Functions =======================================================================================
function fillContentContainer(http_request)
{
	var ready = http_request.readyState;
//	var status = http_request.status;  && status == 200   this doesn't work in IE6... suprise suprise... skip it!
	if(ready == 4 )
	{
		document.getElementById("subContentContainer").innerHTML=http_request.responseText;
		if(document.getElementById("homeCol1"))
		{
			var twitterDivToPlace = document.getElementById("twitterFeed").cloneNode(true);
			document.getElementById("homeCol1").innerHTML = twitterDivToPlace.innerHTML;
		}
	}			
}

var pageHome = 1;
var pagePortals = 2;
var pageTricare = 3;
var pagePatient = 4;
var pageProvider = 5;
var pagePayor = 6;
var pageRegulatory = 7;
var pageContactus = 8;
var pageAboutus = 9;
var pagePrivacypolicy = 10;
var pageTermsofuse = 11;
var pageWhyEmma = 12;
var myButtons = new Array("homeButton","portalsButton","tricareButton","patientButton","providerButton","payorButton","regulatoryButton","contactButton","","","","whyEmmaButton");
/**
 * This function will call the necessary ajax to change the subContentContainer div.
 * 
 * @param pageToDisplay -- page number to display, dictated by the page<pagename> vars
 */
function changeContentContainer(pageToDisplay)
{
	/* make sure what we get is an int... */
	pageToDisplay = parseInt(pageToDisplay);
	/* If we do not have the page in our array default to home page */
	if(!pageToDisplay || pageToDisplay < 1 || pageToDisplay > 12)
		{pageToDisplay = 1;}
	lastPageLoaded = pageToDisplay;
	var pageToDisplayUrl = "";
	/* Make our AJAX call to load the page... */
	switch(pageToDisplay)
	{
		case 1:
			pageToDisplayUrl = "home.html";
			break;
		case 2:
			pageToDisplayUrl = "portal.php";
//				{window.open("http://reports.emmarx.com:8080");}
			break;
		case 3:
			pageToDisplayUrl = "tricare.html";
			break;
		case 4:
			pageToDisplayUrl = "patient.html";
			break;
		case 5:
			pageToDisplayUrl = "provider.html";
			break;
		case 6:
			pageToDisplayUrl = "payor.html";
			break;
		case 7:
			pageToDisplayUrl = "regulatory.html";
			break;
		case 8:
			pageToDisplayUrl = "contactUs.html";
			break;
		case 9:
			pageToDisplayUrl = "aboutUs.html";
			break;
		case 10:
			pageToDisplayUrl = "privacyPolicy.html";
			break;
		case 11:
			pageToDisplayUrl = "termsOfUse.html";
			break;
		case 12:
			pageToDisplayUrl = "whyEmma.html";
			break;
		default:
			pageToDisplayUrl = "home.html";
			break;
	}
	sendAjaxRequest("/includes/"+pageToDisplayUrl,"","fillContentContainer");
	window.location.hash = pageToDisplay;
	
	/* Revert all of our buttons... */
	for(i = 0; i < myButtons.length; i++)
	{
		if(document.getElementById(myButtons[i]+"Alt"))
			document.getElementById(myButtons[i]+"Alt").id = myButtons[i];
	}
	
	/* Switch only the button we want... */
	if(document.getElementById(myButtons[pageToDisplay-1]))
		{document.getElementById(myButtons[pageToDisplay-1]).id = myButtons[pageToDisplay-1]+"Alt";}
}

//===== Other Javascript Functions ========================================================================================
var lastPageLoaded = ""
function setPageOnLoad()
{
	var pageToLoad = window.location.hash;
	if(!pageToLoad)
		{pageToLoad = "#1";}
	pageToLoad = pageToLoad.substring(1);
	if(lastPageLoaded != pageToLoad)
		{changeContentContainer(pageToLoad);}
}
function javascriptSubmitDirectionsForm()
{
	document.directionsForm.submit();
}
function getGetVars()
{ // Import GET Vars
   document.$_GET = [];
   var urlHalves = String(document.location).split('?');
   if(urlHalves[1])
   {
      var urlVars = urlHalves[1].split('&');
      for(var i=0; i<=(urlVars.length); i++)
      {
         if(urlVars[i])
         {
            var urlVarPair = urlVars[i].split('=');
            document.$_GET[urlVarPair[0]] = urlVarPair[1];
         }
      }
   }
};
function runScripts(divToRun) {
	if (divToRun.nodeType != 1) return; //if it's not an element node, return
 
	if (divToRun.tagName.toLowerCase() == 'script')
	{
		eval(divToRun.text); //run the script
	}
	else 
	{
		var n = divToRun.firstChild;
		while ( n ) 
		{
			if ( n.nodeType == 1 ) runScripts( n ); //if it's an element node, recurse
			n = n.nextSibling;
		}
	}
}

//===== Javascript for switching biographies in About Us ==================================================================
var aboutUsManagementOverviewDiv = 1;
var aboutUsManagementSpecificCbossi = 2;
var aboutUsManagementSpecificMdrummey = 3;
var aboutUsManagementSpecificCcaracciolo = 4;
var aboutUsManagementSpecificMmcginnis = 5;
var aboutUsManagementSpecificNcimino = 6;
var aboutUsManagementSpecificGrevolorio = 7;
var aboutUsArray = new Array("aboutUsManagementOverviewDiv","aboutUsManagementSpecificCbossi","aboutUsManagementSpecificMdrummey","aboutUsManagementSpecificCcaracciolo","aboutUsManagementSpecificMmcginnis","aboutUsManagementSpecificNcimino","aboutUsManagementSpecificGrevolorio");
function displayAboutUsSection(divToDisplay)
{
	/* Check to see if out div to display is valid... */
	if(!divToDisplay || divToDisplay < 1 || divToDisplay > 7)
		{divToDisplay = 1;}
	/* Hide all of our divs... */
	for(i = 0; i < aboutUsArray.length; i++)
	{
		document.getElementById(aboutUsArray[i]).style.display = "none";
	}
	/* Now display the one we really care about... */
	if(document.getElementById(aboutUsArray[divToDisplay-1]))
		{document.getElementById(aboutUsArray[divToDisplay-1]).style.display = "block";}
}

//===== Javascript for Portal Access Request Form =========================================================================
var portalLogin = 0;
var portalPopup = 1;
var portalConfirm = 2;
function switchDiv(divToDisplay)
{
	var portalDivs = Array("portalLogin","portalPopup","portalConfirm");
	
	document.getElementById(portalDivs[0]).style.display = "none";
	document.getElementById(portalDivs[1]).style.display = "none";
	document.getElementById(portalDivs[2]).style.display = "none";
	
	document.getElementById(portalDivs[divToDisplay]).style.display = "block";
}
function processPARForm()
{
	if(validatePARForm() == true)
	{
		//Form is valid. we need to kick off our ajax request...
		var userType = null;
		var radioArray = new Array("radio1","radio2","radio3","radio4");
		var radioTypeArray = new Array("Nurse","Pharmacist","Physician","SquadLeader");
		for(i = 0; i < 4; i++)
		{
			if(document.getElementById(radioArray[i]).checked)
				{userType = radioTypeArray[i];}
		}
		var params = "title="+document.getElementById("formTitle").value;
		params += "&firstName="+document.getElementById("firstName").value;
		params += "&lastName="+document.getElementById("lastName").value;
		params += "&locationName="+document.getElementById("locationName").value;
		params += "&address1="+document.getElementById("address1").value;
		params += "&address2="+document.getElementById("address2").value;
		params += "&city="+document.getElementById("city").value;
		params += "&state="+document.getElementById("state").value;
		params += "&zip="+document.getElementById("zip").value;
		params += "&phoneNumber="+document.getElementById("phoneNumber").value;
		params += "&emailAddress="+document.getElementById("emailAddress").value;
		params += "&referredBy="+document.getElementById("referredBy").value;
		params += "&userType="+userType;
		params += "&doEmail=true";
		sendAjaxRequest("ajax/sendRequest.php",params,"processPARFormAJAXRETURN")
	}
}
function processPARFormAJAXRETURN(http_request)
{
	var ready = http_request.readyState;
	if(ready == 4)
	{
		if(http_request.responseText == "true")
		{switchDiv(2);}
		else
			{alert("An error has occured! Your request has NOT been processed! Please try again later.");}
	}
}
function validatePARForm()
{
	var valid = true;	// optimistic!
	var states = new Array(	"AL","AK","AZ","AR","CA","CO","CT","DE","DC","FL",
							"GA","HI","ID","IL","IN","IA","KS","KY","LA","ME",
							"MD","MA","MI","MN","MS","MO","MT","NE","NV","NH",
							"NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI",
							"SC","SD","TN","TX","UT","VT","VA","WA","WV","WI",
							"WY"); //50 states plus wash.DC
	var errorString = "";
	var errorColor = "#FF7777";
	var normalColor = "#FFFFFF";
	// Easy checks...
	if(document.getElementById("firstName").value.length <= 1){valid = false;document.getElementById("firstName").style.backgroundColor=errorColor;}else{document.getElementById("firstName").style.backgroundColor=normalColor;}
	if(document.getElementById("lastName").value.length <= 1){valid = false;document.getElementById("lastName").style.backgroundColor=errorColor;}else{document.getElementById("lastName").style.backgroundColor=normalColor;}
//	if(document.getElementById("locationName").value.length <= 1){valid = false;document.getElementById("locationName").style.backgroundColor=errorColor;}else{document.getElementById("locationName").style.backgroundColor=normalColor;}
//	if(document.getElementById("address1").value.length <= 1){valid = false;document.getElementById("address1").style.backgroundColor=errorColor;}else{document.getElementById("address1").style.backgroundColor=normalColor;}
//	if(document.getElementById("city").value.length <= 1){valid = false;document.getElementById("city").style.backgroundColor=errorColor;}else{document.getElementById("city").style.backgroundColor=normalColor;}
	if(document.getElementById("referredBy").value.length <= 1){valid = false;document.getElementById("referredBy").style.backgroundColor=errorColor;}else{document.getElementById("referredBy").style.backgroundColor=normalColor;}
	// More involved checks... 
//	var stateValid = inArray(document.getElementById("state").value,states);
//	if(stateValid == false){valid = false;document.getElementById("state").style.backgroundColor=errorColor;}else{document.getElementById("state").style.backgroundColor=normalColor;}
//	if(!isZipcode(document.getElementById("zip").value)){valid = false;document.getElementById("zip").style.backgroundColor=errorColor;}else{document.getElementById("zip").style.backgroundColor=normalColor;}
//	if(!validatePhoneNumber(document.getElementById("phoneNumber").value)){valid = false;document.getElementById("phoneNumber").style.backgroundColor=errorColor;}else{document.getElementById("phoneNumber").style.backgroundColor=normalColor;}
	if(!validateEmail(document.getElementById("emailAddress").value)){valid = false;document.getElementById("emailAddress").style.backgroundColor=errorColor;}else{document.getElementById("emailAddress").style.backgroundColor=normalColor;}
//	if(document.getElementById("radio1").checked ||
//	   document.getElementById("radio2").checked ||
//	   document.getElementById("radio3").checked ||
//	   document.getElementById("radio4").checked)
//	{}else{valid = false;errorString += "You must select a user type!\n";}
	if(errorString.length >0)
		{alert("You must fix these errors before continuing:\n" + errorString);}

	return valid;
}


// ===== UTILITY STUFFS ========================================================
function inArray(needle, haystack)
{
    var length = haystack.length;
    needle = needle.toUpperCase();
    for(var i = 0; i < length; i++)
    	{if(haystack[i] == needle) return true;}
    return false;
}
function validatePhoneNumber(phoneNumber)
{
	var phoneNumberRegex = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
	return phoneNumberRegex.test(phoneNumber);
}
function isNumeric(number)
{
  return !isNaN(parseFloat(number)) && isFinite(number);
}
function isZipcode(zipcode)
{
	if(isNumeric(zipcode))
	{
		if(zipcode.length == 5)
		{
			return true;
		}
	}
	return false;
}
function validateEmail(email)
{
	var emailRegex = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return emailRegex.test(email);
}
