/// <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;
var __cardtype;
var isIE = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));

function OnglyzaApprovedServices() {
    var commands = new LaunchNetServiceCommands();
    commands.Add("ParticipantContinue");
    commands.Add("OnglyzaApprovedParticipantUnsubscribeSubmit");
    commands.Add("Hcp_ParticipantContinue");
    commands.Add("UpdateDOB");
    
//    commands.Add("CustomValidation");
    
    this.OnglyzaApprovedParticipantUnsubscribeSubmit = OnglyzaApprovedParticipantUnsubscribeSubmit;
    this.ParticipantContinue = ParticipantContinue;
    this.Hcp_ParticipantContinue = Hcp_ParticipantContinue;
    this.UpdateDOB = UpdateDOB;
    
//    this.CustomValidation = CustomValidation;
    
    this.OnPageLoad = OnPageLoad;
    this.OnPageClick = OnPageClick;
    this.OnValidationRequiredCheck = OnValidationRequiredCheck;
    this.OnValidateLaunchNetElements = OnValidateLaunchNetElements;

    var ficoServices = new FicoServices();
    var platformServices = new PlatformServices();   
    

    function ParticipantContinue() 
    {
        return true;
    }
    
    function Hcp_ParticipantContinue() 
    {
        return true;
    }   
    
    function UpdateDOB()
    {
        var ddlMonth=document.getElementById("month{Required/spError-month}");
        var ddlDay=document.getElementById("day{Required/spError-day}");
        var ddlYear=document.getElementById("year-c{Required/spError-year}");
        var dob=ddlMonth.value+"/"+ddlDay.value+"/"+ddlYear.value;
        
        document.getElementById("dob<10028037,OPEN>").value=dob ;
        
        isactivating=document.getElementById("activateCard<14000377,10001002>{RequiredList/spnError_vcoptions}").checked;
	
	    if(!isactivating){SubmitByLink("SaveProfile[ParticipantSubmit]");return;}
    		
	    last_4=document.getElementById("TelPh<14000380,OPEN>{AnswerText/spError_Telph}").value;
	    cardId=document.getElementById("CardId<14000378,OPEN>{AnswerText/spError_CardId}").value;
	    zip=document.getElementById("Zip{Zip}").value;			
	        	    
        var status = __context.GetServiceClientProxy("OnglyzaApprovedServices").ValidateValueCard(cardId,last_4,zip,dob).value;
        
	    if(status == 'NEW')
	    {	
		    SubmitByLink("SaveProfile[ParticipantSubmit]");
	    }
	    else
	    {
//		    document.getElementById('light').style.display='block';
//		    var h=document.body.clientHeight;
//		    document.getElementById('fade').style.height=h+"px";
//		    document.getElementById('fade').style.display='block';
//		    if(isIE){fixdropdowns(true);}
            SubmitByLink("errorLightboxLink");
	    }
    }
	
    /* ***********************************************************************************
    -  Page Load Event
    ************************************************************************************ */

    function OnPageLoad() 
    {
        
        //Get CardType from Session
        __cardtype=__context.GetServiceClientProxy("OnglyzaApprovedServices").GetValueCardType();
    
        // HCP Registration
        //------------------------------------------------------------------------------------------
        var opt_18=document.getElementById("optout<14000337,10001001>{Required/opt_18}");
        var opt_agree=document.getElementById("optout<14000332,10001001>{Required/opt_agree}");
        if(opt_18!=null && opt_agree!=null)
        {
            opt_18.checked = true;
		    opt_agree.checked = true; 
		}
		//------------------------------------------------------------------------------------------
		
		//Consumer Registration
		//------------------------------------------------------------------------------------------		
		var yob=document.getElementById("year-c{Required/spError-year}");
		if(yob!=null)
		{
		    var currentyear = new Date().getFullYear(); 
		    for (i = 1882 ; i+18 <= currentyear-18; i++)
            {
                adjustedYOB = i + 18;
                oOption=new Option();
                oOption.text=adjustedYOB;
                oOption.value=adjustedYOB;
                yob.options[yob.options.length]=oOption;
            }            
        }
        //Check if this consumer registration Page2.If year of Diagnosis is present- It is Reg page2.
        var yodiag=document.getElementById("yearDiagnosis<14000335,OPEN>");
		if(yodiag!=null)
		{    
            var last4= document.getElementById("dvLast4");
            var newcard= document.getElementById("dvNewCard");
            var benefit=document.getElementById("<14000361,10001002>{Required/error_14000361}");
            //var medack=document.getElementById("<14000362,10001002>{Required/error_14000362}");
            var ph_last4=document.getElementById("TelPh<14000380,OPEN>{Required/spError_Telph}");
           
            //Uncomment when integrating with LNP
            if(last4!=null && typeof(last4)!="undefine")
            {
                if(__cardtype.value=='NEW')
                {               
                    last4.style.display="block";
                    newcard.style.display="block";
                    benefit.checked=false;
                    //medack.checked=false;
                    ph_last4.value="";
                    ph_last4.style.display="inline";
                }
                else
                {
                    last4.style.display="none";
                    newcard.style.display="none";
                    benefit.checked=true;
                    benefit.style.display="none";        
                    //medack.checked=true;
                    //medack.style.display="none";        
                    ph_last4.value="xxxx";
                    ph_last4.style.display="none";        
                }
            }
        }
        
        //Consumer Registration Confirmation Page.
        dvRegAct=document.getElementById("userActivate");
        dvRegNew=document.getElementById("userRegister");
        if(dvRegAct!=null && dvRegNew!=null)
        {
            __cardtype =__context.GetServiceClientProxy("OnglyzaApprovedServices").GetValueCardType();
            if(__cardtype.value=='NEW')
            { 
                dvRegAct.style.display="none";
                dvRegNew.style.display="block";
            }
            else
            {
                dvRegAct.style.display="block";
                dvRegNew.style.display="none";
            }
        }
        //------------------------------------------------------------------------------------------
    }

    /* ***********************************************************************************
    -  Page Click Event
    ************************************************************************************ */

    function OnPageClick(launchNetElementClicked, pageValid) 
    {       
        commands.HandlePageClick(this, launchNetElementClicked, pageValid);
    }    

    function OnglyzaApprovedParticipantUnsubscribeSubmit() {
        //obtain data for participant unsubscribe
        var firstName = GetLaunchNetElementById("FirstName").GetValue();
        var lastName = GetLaunchNetElementById("LastName").GetValue();
        var address1 = GetLaunchNetElementById("Address1").GetValue();
        var city = GetLaunchNetElementById("City").GetValue();
        var state = GetLaunchNetElementById("State").GetValue();
        var zip = GetLaunchNetElementById("Zip").GetValue();
        //var email = GetLaunchNetElementById("Email").GetValue();
        var emailElement = GetLaunchNetElementById("Email");
        var email = emailElement == null ? "10009005" : (emailElement.GetValue() == "" ? "10009005" : emailElement.GetValue());

        //as some elements are optional, we'll provide an empty string if the apropriate element cannot be found
        var prefixElement = GetLaunchNetElementById("Prefix");
        var suffixElement = GetLaunchNetElementById("Suffix");
        var middleInitialElement = GetLaunchNetElementById("MiddleInitial");
        var address2Element = GetLaunchNetElementById("Address2");

        var prefix = prefixElement == null ? "" : prefixElement.GetValue();
        var middleInitial = middleInitialElement == null ? "" : middleInitialElement.GetValue();
        var suffix = suffixElement == null ? "" : suffixElement.GetValue();
        var address2 = address2Element == null ? "" : address2Element.GetValue();

        var response = __context.GetServiceClientProxy('FicoServices').AddParticipantUnsubscribe
      (
      prefix
      , firstName
      , middleInitial
      , lastName
      , suffix
      , address1
      , address2
      , city
      , state
      , zip
      , email
      );

        if (response.error != null || response.value == null) {
            __context.RedirectToErrorPage();
            return false;
        }

        return true;
    }

    /* ***********************************************************************************
    -  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 submitpopup = document.getElementById("submit_popup");
        var launchNetElementsValid1 = ficoServices.OnValidateLaunchNetElements(validatableLaunchNetElements);
        var launchNetElementsValid2 = platformServices.OnValidateLaunchNetElements(validatableLaunchNetElements);
        var telph="";
        var isValid=true;
        var yob;
        /*----------------------------------------------------------------------------------------
                                 Reg Page 1 custom validations
        ------------------------------------------------------------------------------------------*/
        yob=document.getElementById("year-c{Required/spError-year}");
        if(yob!=null)
        {
            var ddlMonth=document.getElementById("month{Required/spError-month}");
            var ddlDay=document.getElementById("day{Required/spError-day}");
            var ddlYear=document.getElementById("year-c{Required/spError-year}");
            var actcard=document.getElementById("activateCard<14000377,10001002>{RequiredList/spnError_vcoptions}");
            var ddlState=document.getElementById("State{State}");
            var err_Email=document.getElementById("error_Email<10028050,OPEN>{Email}");
            
            if(err_Email!=null)
            {
                err_Email.innerHTML=err_Email.innerHTML.replace("email","e-mail");
            }
            
            isValid=isDate(ddlMonth,ddlDay,ddlYear);
            
            if(actcard.checked)
            {
                var cardid=document.getElementById("CardId<14000378,OPEN>{AnswerText/spError_CardId}");
                telph=document.getElementById("TelPh<14000380,OPEN>{AnswerText/spError_Telph}");

                if(!IsNumeric(cardid.value) || cardid.value.length < 9)
                {
                   document.getElementById("spError_CardId").innerHTML="Must be a 9-digit number"; 
                   document.getElementById("spError_CardId").style.display="inline";
                   isValid=false;
                }
                   
                if(!IsNumeric(telph.value) || telph.value.length < 4)
                {                
                    document.getElementById("spError_Telph").innerHTML="Must be a 4-digit number"; 
                    document.getElementById("spError_Telph").style.display="inline";
                    isValid=false;
                }            
            }
            if(ddlState.options[ddlState.selectedIndex].value=='MA')
            {
                document.getElementById("spError_State").innerHTML="* Card not valid in MA"; 
                document.getElementById("spError_State").style.display="inline";
                isValid=false;
            }
            else
            {
                document.getElementById("spError_State").style.display="none";
            }
        }
        //----------------------------------------------------------------------------------------
        
        /*----------------------------------------------------------------------------------------
                                 Reg Page 2 custom validations
        ------------------------------------------------------------------------------------------*/
        if(document.getElementById("yearDiagnosis<14000335,OPEN>")!=null)
        {
            yob = __context.GetServiceClientProxy("OnglyzaApprovedServices").GetDOB().value;
            
            if(yob!=null){yob=yob.split("/")[2];}
            
            telph=document.getElementById("TelPh<14000380,OPEN>{Required/spError_Telph}");
            
            if(telph.style.display!="none")
            {
                if(!IsNumeric(telph.value) || telph.value.length < 4)
                {
                    document.getElementById("spError_Telph").innerHTML="Must be a 4-digit number"; 
                    document.getElementById("spError_Telph").style.display="inline";
                    isValid=false;
                }
            }
            
            var yrdiagnosis=document.getElementById("yearDiagnosis<14000335,OPEN>");
            if(yrdiagnosis!=null && parseInt(yrdiagnosis.value) < parseInt(yob))
            {
                document.getElementById("spError-disnosis").style.display="inline";
                isValid=false;
            }
            else
            {
                document.getElementById("spError-disnosis").style.display="none";
            }
        }
        //------------------------------------------------------------------------------------------       
       
        if((document.getElementById("Send[ParticipantUnsubscribeSubmit]")==null) && document.getElementById("submit_popup")!=null)
        {
                
            if (document.getElementById("submit_popup").style.display == "none") {
                if (!launchNetElementsValid1) 
                {
                    document.getElementById("divError1").style.display = "block";
                }
                else 
                {
                    document.getElementById("divError1").style.display = "none";
                }
            }
            else 
            {
                if (!launchNetElementsValid2) 
                {
                    document.getElementById("divError2").style.display = "block";
                    document.getElementById("divError3").style.display = "block";
                    //document.getElementById("btn_submit").style.top = "-12 px";
                    document.getElementById("submit_popup").style.height= "250px"
                }
                else 
                {
                    document.getElementById("divError2").style.display = "none";
                    document.getElementById("divError3").style.display = "none";
                    //document.getElementById("btn_submit").style.top = "0 px";
                }
            }
       }
        
        return (launchNetElementsValid1 && launchNetElementsValid2 && isValid);
    }
} //object ends

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){
        document.getElementById("spError-month").innerHTML="* Required";
        document.getElementById("spError-month").style.display="inline";
        return false;
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
        document.getElementById("spError-day").innerHTML="* Invalid day";
        document.getElementById("spError-day").style.display="inline";
        return false;
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
        document.getElementById("spError-year").innerHTML="* Required";
        document.getElementById("spError-year").style.display="inline";
        return false;
    }
    if (dtStr.indexOf('/',pos2+1)!=-1 || !IsNumeric(stripCharsInBag(dtStr, '/'))){
        return false;
    }
return true;
}

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 IsNumeric(input)
{
    return (parseFloat(input)==input);
}

function closelb()
{
	document.getElementById('light').style.display='none';
	document.getElementById('fade').style.display='none';
	if(isIE){fixdropdowns(false);}
}

function fixdropdowns(bshow,elementlist,classname)
{
	var arSelect; 
	var ospan;
	var oselect;
	var oSel=null;
	var selValue="";

	if(typeof(elementlist)=="undefined"){arSelect = document.getElementsByTagName("select");}
	else{arSelect = elementlist.split("|");}

	for(var i=0;i<arSelect.length;i++)
	{	
		oSel = (typeof(arSelect[i])=="string"?document.getElementById(arSelect[i]):arSelect[i]);
		
		selValue=oSel.options[oSel.selectedIndex].text;

		ospan=document.getElementById(oSel.id+"-layer");
		if(ospan!=null)
		{			
			ospan.parentNode.removeChild(ospan);
		}

		ospan=document.createElement("span");
		ospan.id=oSel.id+"-layer";
		ospan.appendChild(document.createTextNode(selValue));
		ospan.className=(typeof(classname)=="undefined"?"layerspan_small":classname);
		oSel.parentNode.insertBefore(ospan,oSel);
		
		oSel.style.display=(bshow?"none":"inline");
		ospan.style.display=(bshow?"inline":"none");
		
	}
}

//HCP Popup
function createCookie(name,value,days) {
    if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
    else expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) 
    {
        var c = ca[i];
        while (c.charAt(0)==' ') {c = c.substring(1,c.length);}
        if (c.indexOf(nameEQ) == 0) {return c.substring(nameEQ.length,c.length);}
    }
    return null;
}

function checkCookie() {
    return (readCookie('ONGHCP')); 
}

function setCookie(txtAnswer) {
    if (txtAnswer=="yes") {
        createCookie('ONGHCP','YES',0);
    } else {
        createCookie('ONGHCP','NO',0);
    }
}

function popup_show(gotoHcp,e,url)
	{
		popup_hide();
		if(gotoHcp)
		{
			var cookie_val=checkCookie();
			if(cookie_val==null || cookie_val!="YES")
			{
				document.getElementById('popup_light').style.left=(document.body.clientWidth/2 - 200)+"px";
				document.getElementById('popup_light').style.display='block';
				document.getElementById('fade').style.display='block';
				var h=document.body.clientHeight;
				document.getElementById('fade').style.height=h+"px"; 
				if(isIE){fixdropdowns(true);}
			}
			else
			{
				window.location = "/hcp/hcp.aspx";
			}
		}
		
		else
		{
			dvexitpopup=document.getElementById('popup_exit');
			moveObject(dvexitpopup, e)
			var lnk_exit=document.getElementById('lnk_exit');
			var fda_link="http://www.fda.gov/medwatch";
			
			if(typeof(url)!="undefined" && (lnk_exit)!=null) {lnk_exit.href=url;}
			else{lnk_exit.href=fda_link;}
			
			document.getElementById('popup_exit').style.display='block';
			if(isIE){fixdropdowns(true);}
		}
	}
	function popup_hide()
	{
		document.getElementById('popup_exit').style.display = 'none';
	
		document.getElementById('popup_light').style.display = 'none';
		document.getElementById('fade').style.display = 'none';
		
		var pi_flash=document.getElementById('pi_flash');
		if(pi_flash != null) {pi_flash.style.display = 'none'}
	
		if(isIE){fixdropdowns(false);}
	}
	
    function moveObject( obj, e ) 
    {
		// step 1
  		var offset = -25;
  		var objHolder = obj;
		var windowHeight =  windowSize();
		var scrollY = getScrollXY();
		
		var tempX = (document.body.clientWidth * .23);	  
		var tempY = 1 * scrollY + (windowHeight * .20);
	  	

	  // step 4
	  if (tempX < 0){tempX = 0}
	  if (tempY < 0){tempY = 0}

	  // step 5
	  obj.style.top  = (tempY + offset) + 'px';
	  obj.style.left = (tempX + offset) + 'px';
  }

  //get window height + width
  function windowSize() 
  {
	  var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	  }
  		return  myHeight;
  }

  //gets scroll
  function getScrollXY() {
	  var scrOfX = 0, scrOfY = 0;
	  if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	  }
	 // return [ scrOfX, scrOfY ];
	  return [ scrOfY ];
  }	