/// <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 RAlivingServices()
{
  var commands = new LaunchNetServiceCommands();
  commands.Add("YourCommandName");
  commands.Add("OnValidateLaunchNetElements");
  commands.Add("UpdateDOB");
  //commands.Add("UpdateCircleDOB");
  commands.Add("EmailAFriend");
   
  this.OnPageLoad = OnPageLoad;
  this.OnPageClick = OnPageClick;
  this.OnValidationRequiredCheck = OnValidationRequiredCheck;
  this.OnValidateLaunchNetElements = OnValidateLaunchNetElements;
  this.EmailAFriend = EmailAFriend;
  
  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 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 howLongBiologic = document.getElementById("howLongBiologic");

        if (enbrel.checked)
            howLongEnbrel.value = howLongBiologic.value;
        else if (humira.checked)
            howLongHumira.value = howLongBiologic.value;
        else if (kineret.checked)
            howLongKineret.value = howLongBiologic.value;
        else if (rituxan.checked)
            howLongRituxan.value = howLongBiologic.value;
        else if (remicade.checked)
            howLongRemicade.value = howLongBiologic.value;            
}

function EmailAFriend()
  {
    var yourEmail = GetLaunchNetElementById("YourEmail").GetValue();
    var friendEmail = GetLaunchNetElementById("FriendEmail").GetValue();

    //as some elements are optional, we'll provide an empty string if the apropriate element cannot be found
    var yourNameElement = GetLaunchNetElementById("YourName");
    var friendNameElement = GetLaunchNetElementById("FriendName");
       
    var yourName = yourNameElement == null ? "" : yourNameElement.GetValue();
    var friendName = friendNameElement == null ? "" : friendNameElement.GetValue();
   
    var qsParm = new Array();
    var urlcoll = new Hash('/ra-living.aspx','living_learn','/ra-living/quiz.aspx','living_8way','/ra-body.aspx','body','/ra-body/body-tips.aspx','body_tips','/ra-mind.aspx','mind','/ra-mind/mind-tips.aspx','mind_tips','/ra-mind/help-others.aspx','mind_elp','/register.aspx','ra_signup');
   
    var url = new Array();
    var query = window.location.search.substring(1);
    
    if(query != "")
    {
        var parms = query.split('&');
        for (var i=0; i<parms.length; i++) 
        {
            var pos = parms[i].indexOf('=');
            if (pos > 0) 
                {
                var key = parms[i].substring(0,pos);
                var val = parms[i].substring(pos+1);
                qsParm[key] = val;
                }
        }

        paraName = qsParm["paraname"];
        Url = urlcoll.items[paraName];
    }
    //if(window.location.search.substring(1) != "")
    //paraName = window.location.search.substring(1).split('=')[1];
   
    var response = RAlivingClientProxy.EmailAFriend(yourName, yourEmail, friendName, friendEmail,Url);
    
    if (response.error != null)
    {
      __context.RedirectToErrorPage();
      return false;
    }
    
    return true;
  }
  
    function Hash()
    {
        this.length = 0;
        this.items = new Array();
        for (var i = 0; i < arguments.length; i += 2) {
	        if (typeof(arguments[i + 1]) != 'undefined') {
		        this.items[arguments[i+1]] = arguments[i];
		        this.length++;
	        }
        }
    }

/* ***********************************************************************************
-  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="#ff0000";
			}
			
			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=="#ff0000");}					
				}
				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=="#ff0000");}
				}
				if(validatableLaunchNetElements[i].Id=="phone<10015006,OPEN>")
				{
					var phNumber=document.getElementById(validatableLaunchNetElements[i].Element.id)
					if(phNumber!=null && !IsNumeric(phNumber.value))
					{
						fieldLabel.style.color="#ff0000";
					}
					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="#ff0000"; 
				bValid = false;
			}
			else
			{
				mdy.style.color=""; 
			}
		  }

		  //DOB  18 years validation
		  var elementYear = document.getElementById("year-c{Required}");
		  var elementmonth = document.getElementById("month{Required}");
		  var elementday = document.getElementById("day{Required}");
		  var year;
		  var age = 0;
		  var selectyear = 0;
		  //var dob = null;
          if(elementYear!= null && elementmonth != null && elementday != null)
          {
		      var selectedyear = elementYear.options[elementYear.selectedIndex].value;
		      var selectedmonth = elementmonth.options[elementmonth.selectedIndex].value;
		      var selectedday = elementday.options[elementday.selectedIndex].value;
		  //}

		  var new_date = new Date();
		  var current_month = new_date.getMonth();
		  var current_day = new_date.getDate();
		  var current_year = new_date.getFullYear();

		  if ((current_month > selectedmonth - 1) || (current_month == selectedmonth - 1 & current_day >= selectedday)) {
		      selectyear = selectedyear;
		  }
		  else {
		      selectyear = parseInt(selectedyear) + 1;
		  }
		  age = (current_year - selectyear);
		  if (!(age >= 18)) {
		      mdy = document.getElementById("dob" + HeaderTextSuffix);
		      mdy.style.color = "#ff0000"; 
		      bValid = false;
		  }
         }

		  
		  //------------------------------------------------
   	      var summary = document.getElementById("summarymessage");
   	      var summarysub = document.getElementById("summarymessagesub");
          highlightsummary(summary, launchNetElementsValid1, launchNetElementsValid2, bValid);
          highlightsummary(summarysub, launchNetElementsValid1, launchNetElementsValid2, bValid);
          	
          return launchNetElementsValid1 && launchNetElementsValid2 && bValid ;
  }
  
  function highlightsummary(tagid, launchNetElementsValid1, launchNetElementsValid2, bValid)
  {
    if (tagid != null)
    {
      if (!(launchNetElementsValid1 && launchNetElementsValid2 && bValid))
      {
          tagid.style.display = "";
          tagid.style.color = "#ff0000";
      }
      else
      {
          tagid.style.display = "none";                
      }
    }
  }
  
  function ConReg_ValidateCurrentMedType()
  {
  	inf=document.getElementById("infusion<15002910,10001002>");
  	inj=document.getElementById("injection<15002911,10001002>");
  	oral=document.getElementById("oral<15002912,10001002>");
  	nottaking=document.getElementById("not-taking<15005914,10001002>");
  	var currentmed=true;
  	if(inf!=null && inj!=null && oral!=null && nottaking!= null)
  	{
  		currentmed = (inf.checked || inj.checked || oral.checked || nottaking.checked);
  		var patient=document.getElementById("q4_patient");
  		var caregiver=document.getElementById("q4_caregiver");
  		if(patient!=null && patient.style.display!='none') {patient.style.color = (currentmed ?"":"#ff0000");}	
  		if(caregiver!=null && caregiver.style.display!='none') {caregiver.style.color = (currentmed ?"":"#ff0000");}	
  	}
  	
  	return currentmed;
  }
 
  function ConReg_ValidateIfDignosed()
  {
	yes=document.getElementById("rheumatoid-arthritis<10026141,10001001>");
  	no=document.getElementById("rheumatoid-arthritis<10026141,10001002>");
  	dontknow=document.getElementById("rheumatoid-arthritis<10026141,10009004>{RequiredList}");
  	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 ?"":"#ff0000");}	
  		if(caregiver!=null && caregiver.style.display!='none') {caregiver.style.color = (isdiagnosed ?"":"#ff0000");}	
		//if(jia!=null && jia.style.display!='none') {jia.style.color = (isdiagnosed ?"":"#ff0000");}	
  	}
  	
  	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 (arava.checked) {
        currentMedication = "arava";
        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 (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 = RAlivingClientProxy.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
        {
            return "typingtool03.aspx";
        }
    }
}




