/// <reference path="LaunchNetClientBase.js"/>
/// <reference path="BrowserServices.js"/>
/// <reference path="ErrorServices.js"/>
/// <reference path="ClientProxyServices.js"/>
/// <reference path="LaunchNetClientContext.js"/>
/// <reference path="PlatformServices.js"/>


//the following are variables for which values are injected
//var __yourVariable;

function OrenciaServices()
{
  var commands = new LaunchNetServiceCommands();
  commands.Add("YourCommandName");
  commands.Add("OnValidateLaunchNetElements");
  commands.Add("UpdateDOB");
  commands.Add("UpdateCircleDOB");
   
  this.OnPageLoad = OnPageLoad;
  this.OnPageClick = OnPageClick;
  this.OnValidationRequiredCheck = OnValidationRequiredCheck;
  this.OnValidateLaunchNetElements = OnValidateLaunchNetElements;

  var ficoServices = new FicoServices();
  var platformServices = new PlatformServices();

  this.YourCommandName = YourCommandName;
  this.UpdateDOB = UpdateDOB;
  this.UpdateCircleDOB = UpdateCircleDOB;
/* ***********************************************************************************
-  Page Load Event
************************************************************************************ */

  function OnPageLoad()
  {
		//Consumer Registration
		//-----------------------------------------------------------------------------------------------------------		
		var yob=document.getElementById("year-c{Required}");
		if(yob!=null)
		{
		    var currentyear = new Date().getFullYear(); 
		    for (i = currentyear ; i-18 >=1900 ; i--)
            {
                adjustedYOB = i - 18;
                oOption=new Option();
                oOption.text=adjustedYOB;
                oOption.value=adjustedYOB;
                yob.options[yob.options.length]=oOption;
            }            
        }
		//------------------------------------------------------------------------------------------------------------
		
		var infusionYear = document.getElementById("circleInfusionYear<14000230,OPEN>");
	    if (infusionYear != null) {
	        var currentyear = new Date().getFullYear();
	        //During the month of dec 2009, we got an issue to include 2010.
	        if (currentyear < 2010)
	            currentyear = 2010;
	        for (i = currentyear; i > 2005; i--) {
	        	oOption = new Option();
	            oOption.text = i;
	            oOption.value = i;
	            infusionYear.options[infusionYear.options.length] = oOption;
	        }
	    }	    
  }

/* ***********************************************************************************
-  Page Click Event
************************************************************************************ */

  function OnPageClick(launchNetElementClicked, pageValid)
  {
    commands.HandlePageClick(this, launchNetElementClicked, pageValid);
  }

  function YourCommandName()
  {
    //your functionality here, performed on YourCommandName
  }

  function UpdateDOB(tc)
{
	var ddlMonth=document.getElementById("month{Required}");
	var ddlDay=document.getElementById("day{Required}");
	var ddlYear=document.getElementById("year-c{Required}");
	var dob=ddlMonth.value+"/"+ddlDay.value+"/"+ddlYear.value;
	document.getElementById("dob<10028037,OPEN>").value=dob ;
		
	SubmitByLink("Save[ParticipantSubmit('"+tc+"')]");
}

function SubmitByLink(linkId)
    {
        lnk=document.getElementById(linkId);
	    if(!window.attachEvent){
		    var evt = document.createEvent("MouseEvents");
		    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
		    c=lnk.dispatchEvent(evt);}
	    else
		    lnk.click();
    }
    
function UpdateCircleDOB(tc)
{
	var ddlMonth=document.getElementById("month{Required}");
	var ddlDay=document.getElementById("day{Required}");
	var ddlYear=document.getElementById("year-c{Required}");
	var dob=ddlMonth.value+"/"+ddlDay.value+"/"+ddlYear.value;
	document.getElementById("dob<10028037,OPEN>").value=dob ;
		
  UpdateHowLongBiologic();
  
	SubmitByLink("Save[ParticipantSubmit('"+tc+"')]");
}

function UpdateHowLongBiologic() 
{
        var enbrel = document.getElementById("biologic<10002352,10001001>");
        var humira = document.getElementById("biologic<10002353,10001001>");
        var kineret = document.getElementById("biologic<10002364,10001001>");
        var rituxan = document.getElementById("biologic<11000226,10001001>");
        var remicade = document.getElementById("biologic<10002354,10001001>");
        var simponi = document.getElementById("biologic<15001443,10001001>");
        var cimzia = document.getElementById("biologic<15001439,10001001>");
        var howLongEnbrel = document.getElementById("howLongEnbrel<11000236,10009001>");
        var howLongHumira = document.getElementById("howLongHumira<11000237,10009001>");
        var howLongKineret = document.getElementById("howLongKineret<11000240,10009001>");
        var howLongRituxan = document.getElementById("howLongRituxan<11000251,10009001>");
        var howLongRemicade = document.getElementById("howLongRemicade<11000249,10009001>");
        var howLongSimponi = document.getElementById("howLongSimponi<15001444,10009001>");
        var howLongCimzia = document.getElementById("howLongCimzia<15001440,10009001>");
        var howLongBiologic = document.getElementById("howLongBiologic");

        if (enbrel.checked)
        {
            if(howLongBiologic.value == "")
            {
                howLongEnbrel.value = "10009005";
            }
            else
            {
                howLongEnbrel.value = howLongBiologic.value;
            }
        }
        else if (humira.checked)
        {
            if(howLongBiologic.value == "")
            {
                howLongHumira.value = "10009005";
            }
            else
            {
                howLongHumira.value = howLongBiologic.value;
            }
        }
        else if (kineret.checked)
        {
            if(howLongBiologic.value == "")
            {
                howLongKineret.value = "10009005";
            }
            else
            {
                howLongKineret.value = howLongBiologic.value;
            }
        }
        else if (rituxan.checked)
        {
            if(howLongBiologic.value == "")
            {
                howLongRituxan.value = "10009005";
            }
            else
            {
                howLongRituxan.value = howLongBiologic.value;
            }
        }    
        else if (remicade.checked)
        {
            if(howLongBiologic.value == "")
            {
                howLongRemicade.value = "10009005";
            }
            else
            {
                howLongRemicade.value = howLongBiologic.value;
            }
        }  
        else if (simponi.checked)
        {
            if(howLongBiologic.value == "")
            {
                howLongSimponi.value = "10009005";
            }
            else
            {
                howLongSimponi.value = howLongBiologic.value;
            }
        } 
        else if (cimzia.checked)
        {
            if(howLongBiologic.value == "")
            {
                howLongCimzia.value = "10009005";
            }
            else
            {
                howLongCimzia.value = howLongBiologic.value;
            }
        }        
}


/* ***********************************************************************************
-  Page Validation
************************************************************************************ */

  function OnValidationRequiredCheck(launchNetElementClicked)
  {
    return commands.HandleValidationRequiredCheck(launchNetElementClicked);
    //return true if the incoming launchNetElementClicked indicates a need to perform validation
    //note that launchNetElementClicked is of type LaunchNetElement (see LaunchNetClientBase.js)
  }

  function OnValidateLaunchNetElements(validatableLaunchNetElements)
  {
          var launchNetElementsValid1 = ficoServices.OnValidateLaunchNetElements(validatableLaunchNetElements);
          var launchNetElementsValid2 = platformServices.OnValidateLaunchNetElements(validatableLaunchNetElements);
         
		 var HeaderTextSuffix = "HeaderText";
		 var errElmColor="";
		 var e_id="";
		 var errElem = null;
		 var fieldLabel=null;
		 //---------For consumer reg------------------------------------------------------
		 var yob=document.getElementById("year-c{Required}");
		 var dob=document.getElementById("dob<10028037,OPEN>");
		 var cszError=false;
		 var dobError=false;
		 var csz=null;
		 var mdy=null;
		 //-------------------------------------------------------------------------------------
		 for (var i = 0; i < validatableLaunchNetElements.length; i++) {			
			e_id ="error_"+validatableLaunchNetElements[i].Element.id;
			errElem = document.getElementById(e_id);
			errElmColor="";
			if(errElem!=null && errElem.className == 'errorContainer')
			{
				errElem.innerHTML = '';
				errElem.style.display = 'none';
				errElmColor="#cc0000";
			}
			
			fieldLabel = document.getElementById(validatableLaunchNetElements[i].Id + HeaderTextSuffix);
			if(fieldLabel!=null && fieldLabel.style.display!='none') {fieldLabel.style.color = errElmColor;}			
			
			//------------------------For consumer reg---------------------------------
			if(yob!=null && dob!=null) //Consumer registration hopefully.
			{
				if(validatableLaunchNetElements[i].Id=="City" || validatableLaunchNetElements[i].Id=="State" || validatableLaunchNetElements[i].Id=="Zip")
				{
					csz=document.getElementById("City"+HeaderTextSuffix);
					if(csz!=null && !cszError) {csz.style.color=errElmColor; cszError=(errElmColor=="#cc0000");}					
				}
				if(validatableLaunchNetElements[i].Id=="month" || validatableLaunchNetElements[i].Id=="day" || validatableLaunchNetElements[i].Id=="year-c")
				{
					mdy=document.getElementById("dob"+HeaderTextSuffix);
					if(mdy!=null && !dobError) {mdy.style.color=errElmColor; dobError=(errElmColor=="#cc0000");}
				}
				if(validatableLaunchNetElements[i].Id=="phone<10015006,OPEN>")
				{
					var phNumber=document.getElementById(validatableLaunchNetElements[i].Element.id)
					if(phNumber!=null && !IsNumeric(phNumber.value))
					{
						fieldLabel.style.color="#cc0000";
					}
					else
					{fieldLabel.style.color="";}
				}
			}
			//------------------------------------------------------------------------------
		 }
		 /* Do custom validation */ 
		 var bValid=true; //All custom validations should use in var.
		 
		  //---------------Consumer Reg---------------------
			if(yob!=null && dob!=null) //Consumer registration hopefully.
			{
				
				bValid=ConReg_ValidateCurrentMedType() && bValid;
				bValid=ConReg_ValidateIfDignosed() && bValid;
			}		
		  //------------------------------------------------
		  
		  //--------------DOB Validation--------------
		  if(mdy!=null && !dobError)
		  {
			var mm=document.getElementById("month{Required}");
			var dd=document.getElementById("day{Required}");
			var yy=document.getElementById("year-c{Required}");
			if(!isDate(mm,dd,yy))
			{
				mdy.style.color="#cc0000"; 
				bValid = false;
			}
			else
			{
				mdy.style.color=""; 
			}
		  }
		  //------------------------------------------------
   	      var summary = document.getElementById("summarymessage");
          if (summary != null)
          {
            if (!(launchNetElementsValid1 && launchNetElementsValid2 && bValid))
            {
                summary.style.display = "";
                summary.style.color = "#cc0000";
            }
            else
            {
                summary.style.display = "none";                
            }
          }
	
          return launchNetElementsValid1 && launchNetElementsValid2 && bValid ;
  }
  
  function ConReg_ValidateCurrentMedType()
  {
  	inf=document.getElementById("infusion<15002910,10001002>");
  	inj=document.getElementById("injection<15002911,10001002>");
  	oral=document.getElementById("oral<15002912,10001002>");
        med =document.getElementById("med<15005914,10001002>");
  	var currentmed=true;
  	if(inf!=null && inj!=null && oral!=null && med!=null)
  	{
  		currentmed = (inf.checked || inj.checked || oral.checked || med.checked);
  		var patient=document.getElementById("q4_patient");
  		var caregiver=document.getElementById("q4_caregiver");
  		if(patient!=null && patient.style.display!='none') {patient.style.color = (currentmed ?"":"#cc0000");}	
  		if(caregiver!=null && caregiver.style.display!='none') {caregiver.style.color = (currentmed ?"":"#cc0000");}	
  	}
  	
  	return currentmed;
  }
 
  function ConReg_ValidateIfDignosed()
  {
 	var ptype=document.getElementById("ra_radio");
	var yes=null;
	if(ptype!=null)
	{
		if(ptype.style.display!='none')
		{
			yes=document.getElementById("rheumatoid-arthritis<10026141,10001001>");
		  	no=document.getElementById("rheumatoid-arthritis<10026141,10001002>");
		  	dontknow=document.getElementById("rheumatoid-arthritis<10026141,10009004>");
		}
		else
		{
			yes=document.getElementById("child-jia<14000206,10001001>");
		  	no=document.getElementById("child-jia<14000206,10001002>");
		  	dontknow=document.getElementById("child-jia<14000206,10009004>");
		}
	}
  	var isdiagnosed=true;
  	if(yes!=null && no!=null && dontknow!=null)
  	{
  		isdiagnosed = (yes.checked || no.checked || dontknow.checked);
  		var patient=document.getElementById("q1_patient");
  		var caregiver=document.getElementById("q1_caregiver");
		var jia=document.getElementById("q1_jia");
  		if(patient!=null && patient.style.display!='none') {patient.style.color = (isdiagnosed ?"":"#cc0000");}	
  		if(caregiver!=null && caregiver.style.display!='none') {caregiver.style.color = (isdiagnosed ?"":"#cc0000");}	
		if(jia!=null && jia.style.display!='none') {jia.style.color = (isdiagnosed ?"":"#cc0000");}	
  	}
  	
  	return isdiagnosed;
  }
 
  function daysInFebruary (year){
	        // February has 29 days in any year evenly divisible by four,
            // EXCEPT for centurial years which are not also divisible by 400.
            return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
  }
  
  function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
        if (i==2) {this[i] = 29}
   } 
   return this
  }
  
  function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
  }
  
  function isDate(ddlMonth,ddlDay,ddlYear){
    var dtStr= ddlMonth.value+"/"+ddlDay.value+"/"+ddlYear.value ;
    
    var minYear=1900;
    //var maxYear=new Date().getFullYear()-18;
    
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf('/')
    var pos2=dtStr.indexOf('/',pos1+1)
    var strMonth=dtStr.substring(0,pos1)
    var strDay=dtStr.substring(pos1+1,pos2)
    var strYear=dtStr.substring(pos2+1)
    strYr=strYear
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
    }
    month=parseInt(strMonth)
    day=parseInt(strDay)
    year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
        return false;
    }
    if (strMonth.length<1 || month<1 || month>12){
        return false;
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
        return false;
    }
    if (strYear.length != 4 || year==0 || year<minYear){
        return false;
    }
    if (dtStr.indexOf('/',pos2+1)!=-1 || !IsNumeric(stripCharsInBag(dtStr, '/'))){
        return false;
    }
  return true;
  }

  function IsNumeric(input)
  {
		return (parseFloat(input)==input);
  }  
}

function typingTool() {
    var typingEligible = false;
    var currentMedication = "";
    var patient = document.getElementById("usertype-patient<10008001,10016015>");
    var methotrexate = document.getElementById("checkbox-Methotrexate<15001436,10001002>");
    var orencia = document.getElementById("checkbox-Orencia<10002350,10001002>");
    var remicade = document.getElementById("checkbox-Remicade<10002354,10001002>");
    var rituxan = document.getElementById("checkbox-Rituxan<11000226,10001002>");
    var cimzia = document.getElementById("checkbox-Cimzia<15001439,10001002>");
    var enbrel = document.getElementById("checkbox-Enbrel<10002352,10001002>");
    var humira = document.getElementById("checkbox-Humira<10002353,10001002>");
    var kineret = document.getElementById("checkbox-Kineret<10002364,10001002>");
    var methotrexate2 = document.getElementById("checkbox-Methotrexate2<15001441,10001002>");
    var simponi = document.getElementById("checkbox-Simponi<15001443,10001002>");
    var arava = document.getElementById("checkbox-Arava<10002356,10001002>");
    var azulfidine = document.getElementById("checkbox-Azulfidine<10002357,10001002>");
    var methotrexate3 = document.getElementById("checkbox-Methotrexate3<15001446,10001002>");
    var plaquenil = document.getElementById("checkbox-Plaquenil<10002368,10001002>");
    var ridaura = document.getElementById("checkbox-Ridaura<11000227,10001002>");
    var infusion = document.getElementById("infusion<15002910,10001002>");
    var injection = document.getElementById("injection<15002911,10001002>");

    if (!patient.checked) {
        return "";
    }


    //Medication hierarchy

    var biologicCount = 0;
    var infusionCount = 0;
    var injectionCount = 0;

    var biologics = new Array();

    if (ridaura.checked) {
        currentMedication = "ridaura";
        typingEligible = true;
    }
    if (plaquenil.checked) {
        currentMedication = "plaquenil";
        typingEligible = true;
    }
    if (methotrexate3.checked) {
        currentMedication = "methotrexate";
        typingEligible = true;
    }
    if (azulfidine.checked) {
        currentMedication = "azulfidine";
        typingEligible = true;
    }
    if (methotrexate2.checked) {
        currentMedication = "methotrexate";
        injectionCount++;
        typingEligible = true;
    }
    if (methotrexate.checked) {
        currentMedication = "methotrexate";
        infusionCount++;
        typingEligible = true;
    }
    if (orencia.checked) {
        currentMedication = "orencia";
        biologics.push("orencia");
        biologicCount++;
        infusionCount++;
        typingEligible = true;
    }
    if (rituxan.checked) {
        currentMedication = "rituxan";
        biologics.push("rituxan");
        biologicCount++;
        infusionCount++;
        typingEligible = true;
    }
    if (remicade.checked) {
        currentMedication = "remicade";
        biologics.push("remicade");
        biologicCount++;
        infusionCount++;
        typingEligible = true;
    }
    if (humira.checked) {
        currentMedication = "humira";
        biologics.push("humira");
        biologicCount++;
        injectionCount++;
        typingEligible = true;
    }
    if (enbrel.checked) {
        currentMedication = "enbrel";
        biologics.push("enbrel");
        biologicCount++;
        injectionCount++;
        typingEligible = true;
    }
    if (kineret.checked) {
        currentMedication = "kineret";
        biologics.push("kineret");
        biologicCount++;
        injectionCount++;
        typingEligible = true;
    }
    if (arava.checked) {
        currentMedication = "arava";
        biologics.push("arava");
        biologicCount++;
        typingEligible = true;
    }
    if (cimzia.checked) {
        currentMedication = "cimzia";
        biologics.push("cimzia");
        biologicCount++;
        injectionCount++;
        typingEligible = true;
    }
    if (simponi.checked) {
        currentMedication = "simponi";
        biologics.push("simponi");
        biologicCount++;
        injectionCount++;
        typingEligible = true;
    }
    if (infusionCount == 0 && injectionCount == 0) {
        if (infusion.checked) {
            currentMedication = "methotrexate";
            biologicCount = 1;
            typingEligible = true;
        }
    }
    if (infusionCount == 0 && injectionCount == 0) {
        if (injection.checked) {
            currentMedication = "methotrexate";
            biologicCount = 1;
            typingEligible = true;
        }
    }
    if (!typingEligible) {
        return "";    // no medication selected, return and display thank you message.
    }

    var response = OrenciaClientProxy.SaveCurrentMedication(currentMedication, biologics);
    if (response.error != null) {
        __context.RedirectToErrorPage();
        return "";
    }

    if (typingEligible) {
        if (biologicCount > 1) //go to biologic page
        {
            return "biologic.aspx";
        }
        else  // go to typing tool
        {
            var resp = OrenciaClientProxy.SaveCurrentBiologicQVA("10009001");
            if (resp.error != null) {
                __context.RedirectToErrorPage();
                return "";
            }
            return "typingtool03.aspx";
        }
    }
    
    
}

function circleTypingTool() {
    var typingEligible = false;
    var currentMedication = "";
    var role = document.getElementById("role<10008001,ID>{Required}");
    var methotrexate = document.getElementById("dmard1<10002351,10001002>");
    //var orencia = document.getElementById("checkbox-Orencia<10002350,10001002>");
    var remicade = document.getElementById("biologic<10002354,10001001>");
    var rituxan = document.getElementById("biologic<11000226,10001001>");
    //var cimzia = document.getElementById("checkbox-Cimzia<15001439,10001002>");
    var enbrel = document.getElementById("biologic<10002352,10001001>");
    var humira = document.getElementById("biologic<10002353,10001001>");
    var kineret = document.getElementById("biologic<10002364,10001001>");
    var simponi = document.getElementById("biologic<15001443,10001001>");
    var cimzia = document.getElementById("biologic<15001439,10001001>");
    //var simponi = document.getElementById("checkbox-Simponi<15001443,10001002>");
    var arava = document.getElementById("dmard3<10002356,10001002>");
    //var azulfidine = document.getElementById("checkbox-Azulfidine<10002357,10001002>");
    var plaquenil = document.getElementById("dmard2<10002368,10001002>");
    //var ridaura = document.getElementById("checkbox-Ridaura<11000227,10001002>");

    //return if not patient
    if (role.value != "10016015") {
        return "";
    }


    //Medication hierarchy

    var biologicCount = 0;

//    if (ridaura.checked) {
//        currentMedication = "ridaura";
//        typingEligible = true;
//    }
    if (plaquenil.checked) {
        currentMedication = "plaquenil";
        typingEligible = true;
    }
//    if (azulfidine.checked) {
//        currentMedication = "azulfidine";
//        typingEligible = true;
//    }
    if (methotrexate.checked) {
        currentMedication = "methotrexate";
        typingEligible = true;
    }
//    if (orencia.checked) {
//        currentMedication = "orencia";
//        typingEligible = true;
//    }
    if (rituxan.checked) {
        currentMedication = "rituxan";
        typingEligible = true;
    }
    if (remicade.checked) {
        currentMedication = "remicade";
        typingEligible = true;
    }
    if (humira.checked) {
        currentMedication = "humira";
        typingEligible = true;
    }
    if (enbrel.checked) {
        currentMedication = "enbrel";
        typingEligible = true;
    }
    if (kineret.checked) {
        currentMedication = "kineret";
        typingEligible = true;
    }
    if (cimzia.checked) {
        currentMedication = "cimzia";
        typingEligible = true;
    }
    if (simponi.checked) {
        currentMedication = "simponi";
        typingEligible = true;
    }

    if (arava.checked) {
        currentMedication = "arava";
        typingEligible = true;
    }
    if (cimzia.checked) {
        currentMedication = "cimzia";
        typingEligible = true;
    }
    if (simponi.checked) {
        currentMedication = "simponi";
        typingEligible = true;
    }
    if (!typingEligible) {
        return "";    // no medication selected, return and display thank you message.
    }

    var response = OrenciaClientProxy.SaveCurrentMedication(currentMedication, null);
    if (response.error != null) {
        __context.RedirectToErrorPage();
        return "";
    }

    if (typingEligible) {
            return "../typingtool03.aspx";
    }
}



