// simplyinteractive.net
// last rev. Jan 20, 2009
// daniel@simplyinteractive.net


function valform(formtovalidate){

    if(formtovalidate.emailsignup.value == ""){
        alert("An email es required to begin the registration process.");
        return false;
    } else if(formtovalidate.emailsignup.value.indexOf('@') == -1){
        alert("A valid email es required to begin the registration process.");
        return false;
    } else if(formtovalidate.emailsignup.value.indexOf('.') == -1){
        alert("A valid email es required to begin the registration process.");
        return false;
    } else if(formtovalidate.emailsignup.value.indexOf('\'') != -1){
        alert("A valid email es required to begin the registration process.");
        return false;
    } else if(formtovalidate.emailsignup.value.indexOf('\"') != -1){
        alert("A valid email es required to begin the registration process.");
        return false;
    } else if(formtovalidate.emailsignup.value.indexOf('=') != -1){
        alert("A valid email es required to begin the registration process.");
        return false;
    } else {
        formtovalidate.action = "createpatient_a.php";

        $('signup').request({
            onComplete: function(respond){

                //alert (respond.responseText);

                if(respond.responseText.indexOf('sentok') != -1){

                    new Effect.Fade('signupform', {
                        duration: .3
                    });
                    new Effect.Appear('signupformok', {
                        duration: .3,
                        queue: 'end'
                    });

                    // reset the form
                    formtovalidate.reset();
                } else if(respond.responseText.indexOf('exist') != -1){
                    alert ("The E-mail has already been registered");
                }

            }
        });

        return false;
    }

}


// user login stuff


function valuserloginform(userloginform){

    if(userloginform.email.value == ""){
        alert("An email es required to enter.");
        return false;
    } else if(userloginform.email.value.indexOf('@') == -1){
        alert("A valid email es required to enter.");
        return false;
    } else if(userloginform.email.value.indexOf('.') == -1){
        alert("A valid email es required to enter.");
        return false;
    } else if(userloginform.email.value.indexOf('\'') != -1){
        alert("A valid email es required to enter.");
        return false;
    } else if(userloginform.email.value.indexOf('\"') != -1){
        alert("A valid email es required to enter.");
        return false;
    } else if(userloginform.email.value.indexOf('=') != -1){
        alert("A valid email es required to enter.");
        return false;
    }else if(userloginform.passwd.value == ""){
        alert("A password es required to enter.");
        return false;
    } else {
        userloginform.action = "userval.php";

        $('signin').request({
            onComplete: function(respond){

                if(respond.responseText.indexOf('loginok') != -1){

                    var theeval = respond.responseText.split('loginok');

                    window.location = "userwelcome.php";

                }else{

                    alert("Your username or password did not match or records, please try again.");

                }

            }
        });

        return false;
    }

}

function valuserloginformJournal(userloginform){

    if(userloginform.email.value == ""){
        alert("An email es required to enter.");
        return false;
    } else if(userloginform.email.value.indexOf('@') == -1){
        alert("A valid email es required to enter.");
        return false;
    } else if(userloginform.email.value.indexOf('.') == -1){
        alert("A valid email es required to enter.");
        return false;
    } else if(userloginform.email.value.indexOf('\'') != -1){
        alert("A valid email es required to enter.");
        return false;
    } else if(userloginform.email.value.indexOf('\"') != -1){
        alert("A valid email es required to enter.");
        return false;
    } else if(userloginform.email.value.indexOf('=') != -1){
        alert("A valid email es required to enter.");
        return false;
    }else if(userloginform.passwd.value == ""){
        alert("A password es required to enter.");
        return false;
    } else {
        userloginform.action = "userval.php";

        $('signinJ').request({
            onComplete: function(respond){

                if(respond.responseText.indexOf('loginok') != -1){

                    var theeval = respond.responseText.split('loginok');

                    window.location = "userwelcome.php?action=set_notes";

                }else{

                    alert("Your username or password did not match or records, please try again.");

                }

            }
        });

        return false;
    }

}


function showsignup(){
    $('signupform').setStyle({
        display: 'block'
    });
}



function valuserrecoveryform(userrecoveryform){

    if(userrecoveryform.email.value == ""){
        alert("An email es required to enter.");
        return false;
    } else if(userrecoveryform.email.value.indexOf('@') == -1){
        alert("A valid email es required to enter.");
        return false;
    } else if(userrecoveryform.email.value.indexOf('.') == -1){
        alert("A valid email es required to enter.");
        return false;
    } else if(userrecoveryform.email.value.indexOf('\'') != -1){
        alert("A valid email es required to enter.");
        return false;
    } else if(userrecoveryform.email.value.indexOf('\"') != -1){
        alert("A valid email es required to enter.");
        return false;
    } else if(userrecoveryform.email.value.indexOf('=') != -1){
        alert("A valid email es required to enter.");
        return false;
    }else {
        userrecoveryform.action = "recoveryval.php";

        $('signinrecover').request({
            onSuccess: function(respond){
                var resultado = respond.responseText.evalJSON();
                if (resultado.valido) {
                    window.location = "online_clinic_entrance.php";
                    alert("Your password was successfully updated and sent to your email");
                } else {
                    alert(resultado.motivo);
                }
            }
        });
        return false;
    }

}



// query available packages for finishing the signup process.
function getavailpackages(){

    $('getavailpackages').request({
        onComplete: function(respond){

            if(respond.responseText != ""){

                $('packagefromajax').innerHTML = respond.responseText;
            //$('amountdue').innerHTML = $('services').innerHTML;
            //$('amountdue').innerHTML = ($('services').getElementsByTagName('option')).innerHTML;
            }
        }
    });
}



var childreg=false;
//document.getavailpackagesform.childreg.value = "N";

// date function starts here

function getAge(yearval, monthval, dayval) {

    var beforeEpoch = false;

    var yeartonum = Number(yearval);

    if(yeartonum < 1970){

        beforeEpoch = true

    }

    var numofdayssinceepoch = 0;


    var today = new Date(); // today

    var TodayDate = (today.getMonth()+1)+"/"+today.getDate()+"/"+today.getFullYear();

    numofdayssinceepoch = (Date.parse(TodayDate)/(24*60*60*1000));

    var usrDate = monthval+"/"+dayval+"/"+yearval;

    calcDate1= Date.parse(TodayDate); // number of milliseconds since 1/1/1970
    calcDate2= Date.parse(usrDate); // number of milliseconds since 1/1/1970 for the user's entered date.

    datediff = ((calcDate1-calcDate2)/(24*60*60*1000))  // results in the number of days diff.

    // get years from diff
    yearsDiff = datediff/365;

    //console.log(datediff);


    // remove decimals
    yearsDiffStr = String(yearsDiff);
    yearsDiffStrArray = yearsDiffStr.split(".");
    yearsDiff = Number(yearsDiffStrArray[0]);

    //absolute years lived in days
    yearsDiffinDays = (yearsDiff * 365);
    // number of days diff minus the number of years
    remainingDiffdays = Number(datediff - yearsDiffinDays);

    //console.log(remainingDiffdays);

    // we need to convert those days into months, for that we convert the days into weeks since months do not have a consistent number of days.
    if(remainingDiffdays > 7){ // do we have at least 1 week?
        remainingDiffdaystoWeeks = remainingDiffdays/7;
    }else{
        remainingDiffdaystoWeeks = 0;
    }

    // now we convert our weeks to months
    if(remainingDiffdaystoWeeks != 0){
        remainingDiffMonths = remainingDiffdaystoWeeks/4;
    }else{
        remainingDiffMonths = 0;
    }

    // make remainingDiffMonths a number
    if(remainingDiffMonths != 0){
        monthsDiffStr = String(remainingDiffMonths);
        monthsDiffStrArray = monthsDiffStr.split(".");
        remainingDiffMonths = Number(monthsDiffStrArray[0]);

    }

    // after converting the months we need to go back to the total days and subtract the months in order to get the ramining days (if any) from the date.

    if(remainingDiffdaystoWeeks != 0){
        remainingDiffdays = (remainingDiffdays - (remainingDiffdaystoWeeks*7));
    }




    //console.log(yearsDiff+"yr "+remainingDiffMonths+"month "+remainingDiffdays+"days");
    return datediff;
}




// end Date calc stuff.

todaysdate = new Date();
thisyear = todaysdate.getFullYear();


///////////////
//
//
//Web Registration Sreeen 1 Data validation entry Start//
//
//
//////////////




function webregstepa(thewebuserform){


    // password val check

    if(thewebuserform.pswd.value != thewebuserform.pswdr.value){
        alert("Passwords do not match. Please enter them again.");
        thewebuserform.pswd.value = "";
        thewebuserform.pswdr.value = "";
        return false;
    }

    if(thewebuserform.pswd.value.length < 6 || thewebuserform.pswdr.value.length < 6){
        alert("Password has to be at least 6 charaters in length.");
        thewebuserform.pswd.value = "";
        thewebuserform.pswdr.value = "";
        return false;
    }

    var mypass = thewebuserform.pswd.value;
    for(x=0;x<mypass.length;x++){
        //console.log(isNaN(mypass.charAt(x)))
        if(isNaN(mypass.charAt(x))){
            foundnumber=true;
        }else{
            foundnumber=false;
            break;
        }
    }

    if(foundnumber){
        alert("Password has to have at least one number.");
        thewebuserform.pswd.value = "";
        thewebuserform.pswdr.value = "";
        return false;
    }

    //console.log(thewebuserform.pswd.value);
    // end pass chck


    // patient information


    if(thewebuserform.first_name.value == "" || thewebuserform.last_name.value== "" || thewebuserform.middle_name.value==""){
        alert("Patient's First, Middle and Last name must not be empty. If you do not have a middle innitial please enter NMI.");
        return false;
    }


    if(thewebuserform.gender[0].checked == false && thewebuserform.gender[1].checked == false){
        alert("Please select F or M at the gender radio button.");
        return false;
    }


    // check date of birth.


    if(thewebuserform.MM.value == "mm" || thewebuserform.DD.value == "dd" || thewebuserform.YY.value == "yyyy" || thewebuserform.MM.value == "" || thewebuserform.DD.value == "" || thewebuserform.YY.value == "" ){
        alert("Please enter the complete patient's date of birth.");
        return false;
    }

    if(isNaN(thewebuserform.MM.value) == true || isNaN(thewebuserform.DD.value) == true  || isNaN(thewebuserform.YY.value)== true ){
        alert("Please verify the patient's date of birth.");
        return false;
    }

    if(thewebuserform.MM.value > 12 || thewebuserform.DD.value > 31 || thewebuserform.YY.value < 1900 || thewebuserform.YY.value > thisyear){
        alert("Please verify the patient's date of birth, including the year in 4 digit format.");
        return false;
    }


    // format the date of birth for the guardian section before submition
    thewebuserform.dateofbirth.value = thewebuserform.YY.value+"-"+thewebuserform.MM.value+"-"+thewebuserform.DD.value;


    //ageoldlist == mm,dd,yyyy
    //agediffdays = getAge(thewebuserform.YY.value, thewebuserform.MM.value, thewebuserform.DD.value)

    //console.log(thewebuserform.dateofbirth.value)

    // end date checks.

    // if guardian is available then


    if(childreg){

        // check guardian's name fields

        if(thewebuserform.guardian_firstname.value == "" || thewebuserform.guardian_lastname.value== "" || thewebuserform.guardian_middlename.value==""){
            alert("Guardian's First, Middle and Last name must not be empty. If you do not have a middle innitial please enter NMI.");
            return false;
        }

        if(thewebuserform.guardian_gender[0].checked == false && thewebuserform.guardian_gender[1].checked == false){
            alert("Please select F or M at the guardian's gender radio button.");
            return false;
        }

        // check date of birth.

        if(thewebuserform.guardMM.value == "mm" || thewebuserform.guardDD.value == "dd" || thewebuserform.guardYY.value == "yyyy" || thewebuserform.guardMM.value == "" || thewebuserform.guardDD.value == "" || thewebuserform.guardYY.value == "" ){
            alert("Please enter the complete guardian's date of birth.");
            return false;
        }


        if(isNaN(thewebuserform.guardMM.value) == true || isNaN(thewebuserform.guardDD.value) == true  || isNaN(thewebuserform.guardYY.value)== true ){
            alert("Please verify the guardian's date of birth.");
            return false;
        }

        if(thewebuserform.guardMM.value > 12 || thewebuserform.guardDD.value > 31 || thewebuserform.guardYY.value < 1900 || thewebuserform.guardYY.value > thisyear){
            alert("Please verify the guardian's date of birth, including the year in 4 digit format.");
            return false;
        }


        // end guardian's date of birth entry check.

        // format the date of birth for the guardian section before submition
        thewebuserform.guardian_dateofbirth.value = thewebuserform.guardYY.value+"-"+thewebuserform.guardMM.value+"-"+thewebuserform.guardDD.value

    //console.log(thewebuserform.guardian_dateofbirth.value);

    }


    // end guardian

    // contact phone numbers check and formatting:

    // check for not empty and lenght functions need to be implemented here

    if(thewebuserform.pphone1.value.length != 3 || thewebuserform.pphone2.value.length != 3 || thewebuserform.pphone3.value.length != 4){
        alert("Make sure the primary phone field is filled in completely.");
        return false;
    }

    if(isNaN(thewebuserform.pphone1.value) == true || isNaN(thewebuserform.pphone2.value) == true || isNaN(thewebuserform.pphone3.value) == true){
        alert("Enter numbers only on the primary phone field.");
        return false;
    }

    if(thewebuserform.wphone1.value != ""){
        if(thewebuserform.wphone1.value.length != 3 || thewebuserform.wphone2.value.length != 3 || thewebuserform.wphone3.value.length != 4){
            alert("Make sure the work phone field is filled in completely.");
            return false;
        }

        if(isNaN(thewebuserform.wphone1.value) == true || isNaN(thewebuserform.wphone2.value) == true || isNaN(thewebuserform.wphone3.value) == true){
            alert("Enter numbers only on the work phone field.");
            return false;
        }
    }

    if(thewebuserform.altphone1.value != ""){
        if(thewebuserform.altphone1.value.length != 3 || thewebuserform.altphone2.value.length != 3 || thewebuserform.altphone3.value.length != 4){
            alert("Make sure the alternate phone field is filled in completely.");
            return false;
        }

        if(isNaN(thewebuserform.altphone1.value) == true || isNaN(thewebuserform.altphone2.value) == true || isNaN(thewebuserform.altphone3.value) == true){
            alert("Enter numbers only on the alternate phone field.");
            return false;
        }
    }


    thewebuserform.primary_phone.value = thewebuserform.pphone1.value+"-"+thewebuserform.pphone2.value+"-"+thewebuserform.pphone3.value;

    //console.log(thewebuserform.primary_phone.value);

    thewebuserform.work_phone.value = thewebuserform.wphone1.value+"-"+thewebuserform.wphone2.value+"-"+thewebuserform.wphone3.value;

    thewebuserform.alternate_phone.value = thewebuserform.altphone1.value+"-"+thewebuserform.altphone2.value+"-"+thewebuserform.altphone3.value;

    //console.log(thewebuserform.work_phone.value);
    //console.log(thewebuserform.alternate_phone.value);

    // end contact numbers handling


    // Address validation stuff

    if(thewebuserform.addressaltname.value == ""){
        alert("Please enter an address into the Address field.");
        return false;
    }

    if(thewebuserform.Cityaltname.value == ""){
        alert("Please enter city name into the city field.");
        return false;
    }

    if(thewebuserform.State.selectedIndex == 0){
        alert("Please choose a state.");
        return false;
    }

    if(thewebuserform.zipcode.value == ""){
        alert("Please provide a zip code.");
        return false;
    }

    // end patient information


    // this ultimately submits the form.

    // query database for package based on if there is a child or not
    //getavailpackages();
    // go to next step.

    /////////////
    //// States of Service Limitation

    if(thewebuserform.State.options[thewebuserform.State.selectedIndex].value == "MN" || thewebuserform.State.options[thewebuserform.State.selectedIndex].value == "ND" || thewebuserform.State.options[thewebuserform.State.selectedIndex].value == "CA" || thewebuserform.State.options[thewebuserform.State.selectedIndex].value == "WA" || thewebuserform.State.options[thewebuserform.State.selectedIndex].value == "AK"){

        switchdiv(2);

    } else {
        thewebuserform.action = "futurepatientregistration1.php";
        thewebuserform.submit();

    }



//////////////


//
//alert("I will go next..");


//return true;
}


// if a user is registeing for a child

function isachildreg(yn){

    objtomodif = document.getElementById("guardianinfotitle").style;
    objtomodif2 = document.getElementById("guardianinfo").style;
    objtomodif3 = document.getElementById("guardianinfomore").style;
    if(yn == 'N'){
        childreg = false;
        //document.getavailpackagesform.childreg.value = "N";
		document.getServiceSelect.childreg.value = "N";

        // IE 7 work arround
        objtomodif.display="";
        objtomodif2.display="";
        objtomodif3.display="";

        objtomodif.display="none";
        objtomodif2.display="none";
        objtomodif3.display="none";

    }else{

        childreg = true;
        //document.getavailpackagesform.childreg.value = "Y";
		document.getServiceSelect.childreg.value = "Y";

        // IE 7 stupid work arround
        objtomodif.display="";
        objtomodif2.display="";
        objtomodif3.display="";

    }

}
// end registeing for a child.


// functions to replace an sample data entry from a field on entry.
function resetelement(what){
    if(what == "mm"){
        if(document.signin.MM.value == ""){
            document.signin.MM.value = "mm";
        }
    }else if (what == "dd"){
        if(document.signin.DD.value == ""){
            document.signin.DD.value = "dd";
        }
    }else if (what == "yyyy"){
        if(document.signin.YY.value == ""){
            document.signin.YY.value = "yyyy";
        }
    }

}

function resetelementguardian(what){
    if(what == "mm"){
        if(document.signin.guardMM.value == ""){
            document.signin.guardMM.value = "mm";
        }
    }else if (what == "dd"){
        if(document.signin.guardDD.value == ""){
            document.signin.guardDD.value = "dd";
        }
    }else if (what == "yyyy"){
        if(document.signin.guardYY.value == ""){
            document.signin.guardYY.value = "yyyy";
        }
    }

}

function clearelement(what){
    if(what == "mm"){
        if(document.signin.MM.value == "mm"){
            document.signin.MM.value = "";
        }
    }else if (what == "dd"){
        if(document.signin.DD.value == "dd"){
            document.signin.DD.value = "";
        }
    }else if (what == "yyyy"){
        if(document.signin.YY.value == "yyyy"){
            document.signin.YY.value = "";
        }
    }

}


function clearelementguardian(what){
    if(what == "mm"){
        if(document.signin.guardMM.value == "mm"){
            document.signin.guardMM.value = "";
        }
    }else if (what == "dd"){
        if(document.signin.guardDD.value == "dd"){
            document.signin.guardDD.value = "";
        }
    }else if (what == "yyyy"){
        if(document.signin.guardYY.value == "yyyy"){
            document.signin.guardYY.value = "";
        }
    }

}
// end set reset data sample.


//function to hide/show parts of the registration form
function switchdiv(divtoswitch){

    div1 = document.getElementById("patientStep1").style;
    div2 = document.getElementById("patientStep2").style;
    div3 = document.getElementById("patientStep3").style;

    if(divtoswitch == 1){

        // IE 7 work arround
        div1.display="";
        div2.display="";
        div3.display="";

        div1.display="block";
        div2.display="none";
        div3.display="none";

    }else if(divtoswitch == 2){

        // IE 7 work arround
        div1.display="";
        div2.display="";
        div3.display="";

        div1.display="none";
        div2.display="block";
        div3.display="none";

    }else if(divtoswitch == 3){
            //alert ('entro al divswitch');

        if(checkTypeService()){
            //alert ('entro1');
            return false;
        }else if(checkTimesEntered()){
            //alert ('entro2');

            // IE 7 work arround
            div1.display="";
            div2.display="";
            div3.display="";

            div1.display="none";
            div2.display="none";
            div3.display="block";
        }else{
            //alert ('entro3');
            alert("1st and 2nd choice date times must be selected in order to continue.");
            return false;
        }

    }

}


    function checkTypeService() {
        //alert('entro TS');
        var varTypeService;
        var type=$j('#type').val();
        if (type!='') var service=$j('#services').val();
        else var service='';
        //alert('Type:'+type);
        //alert('Service: '+service);
        if ( service!=''){
            var valores = service.split('-')
            var price_final=valores[2];
            //alert('Price final: '+price_final);
            document.getElementById("price").value=price_final;
            //alert('Price: '+document.getElementById("price").value);
        }
        if (type=='') {
            alert ("You must select your Type...");
            //alert('entro 1');
            //$j("#dialog_type").dialog("destroy");
            //$j("#dialog_type").dialog({autoOpen: true, bgiframe: true, modal: true});
            return true;
        }else if (service=='') {
            alert ("You must select your Service...");
            //alert('entro 2');
            //$j("#dialog_service").dialog("destroy");
            //$j("#dialog_service").dialog({autoOpen: true, bgiframe: true, modal: true});
            return true;
        }else return false;
    }

function commonDatetoMysql(datetoparse){

    var mydateslice = datetoparse.split("/");

    var mysqldate = mydateslice[2]+"-"+mydateslice[0]+"-"+mydateslice[1];

    return mysqldate;

}

function updateIsAvailable() {
    /*$('updateProvider').request({
        onComplete: function(respond){
            $('availableProvider').innerHTML = respond.responseText;
        }
    });
	//window.location.reload();
	var timepopress = new Date();
	var timefin = timepopress.getTime();
	//alert(timefin);
	window.location.href="welcome.php?tm="+timefin;
    return true;*/
	document.updateProvider.submit();
}

function getAvailableProvider() {
    //$('checkProvider').innerHTML = "Availability for provider";

    $('getavailprovider').request({
        onComplete: function(respond){
            $('checkProvider').innerHTML = respond.responseText;
            //mandamos links
            if (respond.responseText.indexOf('not') != -1){
                deshabilitarLinks();
            }
            else{
                habilitarLinks();
            }

        }
    });

    return false;
}

function getAvailableService() {

    $('getavailservice').request({
        onComplete: function(respond){
            $('servicefromajax').innerHTML = respond.responseText;
        }
    });
    return true;
}

function getAvailableHours(option){
    var datetoparse = Array();

    if(option == 1){

        if(document.signin.timeEnlapsed1.value != ""){
            document.signin.timeEnlapsed1hidden.value = commonDatetoMysql(document.signin.timeEnlapsed1.value);
            $('radio1buttons').innerHTML = "Getting available hours...";
            datetoparse = document.signin.timeEnlapsed1.value.split("/")

        }else{
            alert('Please choose a date by clicking on the calendar icon in order to check for available hours.');
            return false;
        }

    }else{

        if(document.signin.timeEnlapsed2.value != ""){
            document.signin.timeEnlapsed2hidden.value = commonDatetoMysql(document.signin.timeEnlapsed2.value);
            $('radio2buttons').innerHTML = "Getting available hours...";
            datetoparse = document.signin.timeEnlapsed2.value.split("/")
        }else{
            alert('Please choose a date by clicking on the calendar icon in order to check for available hours.');
            return false;
        }
    }


    // set the according field for ajax

    // reset fields
    document.getavailhours.timeEnlapsed1d.value = "";
    document.getavailhours.timeEnlapsed1m.value = "";
    document.getavailhours.timeEnlapsed1y.value = "";

    // reset fields
    document.getavailhours.timeEnlapsed2d.value = "";
    document.getavailhours.timeEnlapsed2m.value = "";
    document.getavailhours.timeEnlapsed2y.value = "";



    // set fields
    if(option == 1){
        document.getavailhours.timeEnlapsed1d.value = datetoparse[1];
        document.getavailhours.timeEnlapsed1m.value = datetoparse[0];
        document.getavailhours.timeEnlapsed1y.value = datetoparse[2];
    }else{
        document.getavailhours.timeEnlapsed2d.value = datetoparse[1];
        document.getavailhours.timeEnlapsed2m.value = datetoparse[0];
        document.getavailhours.timeEnlapsed2y.value = datetoparse[2];
    }

    // get and set the chosen provider value

    // get the index for the selected value
    if(document.signin.apointmentProvider.selectedIndex != 0){

        document.getavailhours.apointmentProvider.value = document.signin.apointmentProvider.options[document.signin.apointmentProvider.selectedIndex].value

        // query for hours.

        $('getavailhours').request({
            onComplete: function(respond){

                if(respond.responseText.indexOf('No hours available') == -1){
                    // populate the hours

                    if(option == 1){
                        $('radio1buttons').innerHTML = respond.responseText;

                    }else{
                        $('radio2buttons').innerHTML = respond.responseText;
                    };


                }else{

                    if(option == 1){
                        $('radio1buttons').innerHTML = "An error occured while trying to get the available hours, please try again.";

                    }else{
                        $('radio2buttons').innerHTML = "An error occured while trying to get the available hours, please try again.";
                    };

                }

            }
        });


    //alert(document.getavailhours.apointmentProvider.value);

    }else{
        alert('Please choose your provider in order to get avialable hours.');
        return false;
    }


}

function getAvailableHours2(option){
    var datetoparse = Array();

    if(option == 1){

        if(document.signin.timeEnlapsed1.value != ""){
            document.signin.timeEnlapsed1hidden.value = commonDatetoMysql(document.signin.timeEnlapsed1.value);
            $('radio1buttons').innerHTML = "Getting available hours...";
            datetoparse = document.signin.timeEnlapsed1.value.split("/")

        }else{
            alert('Please choose a date by clicking on the calendar icon in order to check for available hours.');
            return false;
        }

    }else{

        if(document.signin.timeEnlapsed2.value != ""){
            document.signin.timeEnlapsed2hidden.value = commonDatetoMysql(document.signin.timeEnlapsed2.value);
            $('radio2buttons').innerHTML = "Getting available hours...";
            datetoparse = document.signin.timeEnlapsed2.value.split("/")
        }else{
            alert('Please choose a date by clicking on the calendar icon in order to check for available hours.');
            return false;
        }
    }


        //alert ('datetoparse'+datetoparse);

    // set the according field for ajax

    // reset fields
    /*document.getavailhours.timeEnlapsed1d.value = "";
    document.getavailhours.timeEnlapsed1m.value = "";
    document.getavailhours.timeEnlapsed1y.value = "";

    // reset fields
    document.getavailhours.timeEnlapsed2d.value = "";
    document.getavailhours.timeEnlapsed2m.value = "";
    document.getavailhours.timeEnlapsed2y.value = "";*/

    document.getElementById("timeEnlapsed1d").value="";
    document.getElementById("timeEnlapsed1m").value="";
    document.getElementById("timeEnlapsed1y").value="";

    document.getElementById("timeEnlapsed2d").value="";
    document.getElementById("timeEnlapsed2m").value="";
    document.getElementById("timeEnlapsed2y").value="";

    // set fields

    /*if(option == 1){
        document.getavailhours.timeEnlapsed1d.value = datetoparse[1];
        document.getavailhours.timeEnlapsed1m.value = datetoparse[0];
        document.getavailhours.timeEnlapsed1y.value = datetoparse[2];
    }else{
        document.getavailhours.timeEnlapsed2d.value = datetoparse[1];
        document.getavailhours.timeEnlapsed2m.value = datetoparse[0];
        document.getavailhours.timeEnlapsed2y.value = datetoparse[2];
    }*/

    if(option == 1){
        document.getElementById("timeEnlapsed1d").value = datetoparse[1];
        document.getElementById("timeEnlapsed1m").value = datetoparse[0];
        document.getElementById("timeEnlapsed1y").value = datetoparse[2];
    }else{
        document.getElementById("timeEnlapsed1d").value = datetoparse[1];
        document.getElementById("timeEnlapsed1m").value = datetoparse[0];
        document.getElementById("timeEnlapsed1y").value = datetoparse[2];
    }

    // get and set the chosen provider value

    // get the index for the selected value
    if(document.signin.apointmentProvider.value != 0){

        //document.getavailhours.apointmentProvider.value = document.signin.apointmentProvider.value;
        document.getElementById("apointmentProvider").value = document.signin.apointmentProvider.value;

        // query for hours.

        $('getavailhours').request({
            onComplete: function(respond){

                //alert('respond: '+respond.responseText);
                if(respond.responseText.indexOf('No hours available') == -1){
                    // populate the hours

                    if(option == 1){
                        $('radio1buttons').innerHTML = respond.responseText;

                    }else{
                        $('radio2buttons').innerHTML = respond.responseText;
                    };


                }else{

                    if(option == 1){
                        $('radio1buttons').innerHTML = "An error occured while trying to get the available hours, please try again.";

                    }else{
                        $('radio2buttons').innerHTML = "An error occured while trying to get the available hours, please try again.";
                    };

                }

            }
        });


    //alert(document.getavailhours.apointmentProvider.value);

    }else{
        alert('Please choose your provider in order to get avialable hours.');
        return false;
    }


}

function choosehour(valuefromclick, fromcolumn, hourselected){
	//ponemos el div con la hora seleccionada; fromcolumn = numero caja
	var divhourselected = "radio"+fromcolumn+"buttons_hourselected";
	//alert("divhourselected:"+divhourselected);
	//document.getElementById(divhour).value = hourselected;
	$(divhourselected).innerHTML = "<b>Time: "+hourselected+" was selected.</b>";

    //alert('fromcolumn: '+fromcolumn);
    if(fromcolumn == 1){
        //alert('Valuefromclick: '+valuefromclick);
        document.signin.timestamp1.value = valuefromclick;
    //alert(document.signin.timestamp1.value);
    }else{
        document.signin.timestamp2.value = valuefromclick;
    //alert(document.signin.timestamp2.value);
    }
}


function checkTimesEntered(){

    //alert('entroTE');
    //alert ('Objeto: '+document.signin.HourSelected1);
    //Buscamos el valor del select
    if (document.signin.HourSelected1==undefined) {
        return false;
    }else {
        var seleccionado1=document.signin.HourSelected1.selectedIndex;
        //alert('seleccionado1: '+seleccionado1);
		if(seleccionado1<0){ //revisamos que ademas de ke este el select se haya escogido una hora
			return false;
		}
        var valor_select1=document.signin.HourSelected1.options[seleccionado1].value;
        //alert('valor_select1: '+valor_select1);
        document.signin.timestamp1.value = valor_select1;
    }
    //alert ('Primero Timestamp');
    if (document.signin.HourSelected2==undefined) {
        return false;
    }else {
        var seleccionado2=document.signin.HourSelected2.selectedIndex;
		if(seleccionado2<0){	//revisamos que ademas de ke este el select se haya escogido una hora
			return false;
		}
        var valor_select2=document.signin.HourSelected2.options[seleccionado2].value;
        document.signin.timestamp2.value = valor_select2;
    }
    //alert('seleccionado1: '+seleccionado1);
    //alert('valor_select1: '+valor_select1);
    //alert('seleccionado2: '+seleccionado2);
    //alert('valor_select2: '+valor_select2);
    //alert('timestamp1: '+document.signin.timestamp1.value);
    //alert('timestamp2: '+document.signin.timestamp2.value);
    if(document.signin.timestamp1.value != "" && document.signin.timestamp2.value != ""){
        return true;
    }

}

function submitregistration(usrid){
    document.cookie = "u="+usrid;
    document.signin.submit();
}

//update total amount to be paid.

function updateamount(addorsub){
    //console.log(document.signin.pswd.value);
   // alert('Price: '+document.getElementById("price").value);
    var amountpackage=document.getElementById("price").value;
    //alert ('Amountpackage Antes: '+amountpackage)
    amountpackage=parseFloat(amountpackage);
    if(addorsub == 1){

        //$('amountdue').innerHTML = Number($('amountpackage').innerHTML) + 100;
        $('amountdue').innerHTML = amountpackage + 100;

    } else {
        //$('amountdue').innerHTML = Number($('amountpackage').innerHTML);
        $('amountdue').innerHTML = amountpackage;
    }
    //alert ('Amountpackage despues: '+amountpackage);

}


function checkifexpire(theform){

    if(theform.expire.checked){

        return confirm('Expiring a session will make it no longer accessible, but will allow the patient to purchase additional follow up sessions. Expire this session?');

    }else{
        return true;
    }

}


// Admin function to re-schedule a canceled apointnment.
originalstate="";

function uncancelappointment(){

    if($('datefield').getStyle('display') == 'none'){

        // turn off the strings, and turn on the input fields.

        $('datestring').setStyle({
            display: 'none'
        });

        $('datefield').setStyle({
            display: 'block'
        });

    }else{
        // flip back to the other hidden mode, since the user checked the cancel again.

        $('datestring').setStyle({
            display: 'block'
        });

        $('datefield').setStyle({
            display: 'none'
        });


    }

}


/// admin get available hours for un-cancelling an apointment

function getAvailableHoursadmin(option){
    var datetoparse = Array();


    if(option == 1){

        if(document.formulario.timeEnlapsed1.value != ""){
            document.formulario.timeEnlapsed1hidden.value = commonDatetoMysql(document.formulario.timeEnlapsed1.value);
            $('radio1buttons').innerHTML = "Getting available hours...";
            datetoparse = document.formulario.timeEnlapsed1.value.split("/")

        }else{
            alert('Please choose a date by clicking on the calendar icon in order to check for available hours.');
            return false;
        }
    }


    // set the according field for ajax

    // reset fields
    document.getavailhours.timeEnlapsed1d.value = "";
    document.getavailhours.timeEnlapsed1m.value = "";
    document.getavailhours.timeEnlapsed1y.value = "";


    // set fields
    if(option == 1){
        document.getavailhours.timeEnlapsed1d.value = datetoparse[1];
        document.getavailhours.timeEnlapsed1m.value = datetoparse[0];
        document.getavailhours.timeEnlapsed1y.value = datetoparse[2];
    }

    // get and set the chosen provider value

    // get the index for the selected value

    document.getavailhours.apointmentProvider.value = document.formulario.apointmentProvider.options[document.formulario.apointmentProvider.selectedIndex].value

    // query for hours.

    $('getavailhours').request({
        onComplete: function(respond){

            if(respond.responseText.indexOf('No hours available') == -1){
                // populate the hours

                if(option == 1){
                    $('radio1buttons').innerHTML = respond.responseText;
  //alert("select:"+respond.responseText);
                }

            }else{

                if(option == 1){
                    $('radio1buttons').innerHTML = "There are no avialable hours on that date.";
                }

            }

        }
    });



}

// when editing an apotment it set the value of the chosen hour into the apropiate field for posting.

function choosehouradm(valuefromclick, fromcolumn,hourselected){
		//ponemos el div con la hora seleccionada; fromcolumn = numero caja
	var divhourselected = "radio"+fromcolumn+"buttons_hourselected";
	//alert("divhourselected:"+divhourselected);
	//document.getElementById(divhour).value = hourselected;
	$(divhourselected).innerHTML = "<b>Time: "+hourselected+" was selected.</b>";

    if(fromcolumn == 1){
        document.formulario.timestamp1.value = valuefromclick;
    //alert(document.formulario.timestamp1.value);
    }

}

function checkadmin(){
    if(document.formulario.cancelled.checked == false && document.formulario.timestamp1.value == "" && document.formulario.expire.value == ""){
        alert('Please make sure you choose an hour in order to proceed.');
        return false;
    }else{

        if(document.formulario.cancelled.checked == true && document.formulario.expire.checked == true){
            alert('Only one item either cancel or expire can be checked when submiting.');
            return false;
        }else{
            return true;
        }

    }
}




////////
///
//   Patient Followp Scheduler Starts
///
////////



/// admin get available hours for un-cancelling an apointment

function getAvailableHoursPatient(option){
    var datetoparse = Array();


    if(option == 1){

        if(document.additonalvisit.timeEnlapsed1.value != ""){
            document.additonalvisit.timeEnlapsed1hidden.value = commonDatetoMysql(document.additonalvisit.timeEnlapsed1.value);
            $('radio1buttons').innerHTML = "Getting available hours...";
            datetoparse = document.additonalvisit.timeEnlapsed1.value.split("/")

        }else{
            alert('Please choose a date by clicking on the calendar icon in order to check for available hours.');
            return false;
        }
    }


    // set the according field for ajax

    // reset fields
    document.getavailhours.timeEnlapsed1d.value = "";
    document.getavailhours.timeEnlapsed1m.value = "";
    document.getavailhours.timeEnlapsed1y.value = "";


    // set fields
    if(option == 1){
        document.getavailhours.timeEnlapsed1d.value = datetoparse[1];
        document.getavailhours.timeEnlapsed1m.value = datetoparse[0];
        document.getavailhours.timeEnlapsed1y.value = datetoparse[2];
    }

    // get and set the chosen provider value

    // get the index for the selected value

    document.getavailhours.apointmentProvider.value = document.additonalvisit.apointmentProvider.value

    // query for hours.

    $('getavailhours').request({
        onComplete: function(respond){

            if(respond.responseText.indexOf('No hours available') == -1){
                // populate the hours

                if(option == 1){
                    $('radio1buttons').innerHTML = respond.responseText;

                }

            }else{

                if(option == 1){
                    $('radio1buttons').innerHTML = "There are no avialable hours on that date.";
                }

            }

        }
    });



}

// when editing an apotment it set the value of the chosen hour into the apropiate field for posting.

function choosehourpatient(valuefromclick, fromcolumn, hourselected){
	//ponemos el div con la hora seleccionada; fromcolumn = numero caja
	var divhourselected = "radio"+fromcolumn+"buttons_hourselected";
	//alert("divhourselected:"+divhourselected);
	//document.getElementById(divhour).value = hourselected;
	$(divhourselected).innerHTML = "<b>Time: "+hourselected+" was selected.</b>";

    if(fromcolumn == 1){
        document.additonalvisit.timestamp1.value = valuefromclick;
    //alert(document.formulario.timestamp1.value);
    }
}


//function to hide/show parts of the patients scheduler form
function switchdivpatient(divtoswitch){

    pdiv1 = document.getElementById("patientaddvisit1").style;
    pdiv2 = document.getElementById("patientaddvisit2").style;


    if(divtoswitch == 1){

        // IE 7 work arround
        pdiv1.display="";
        pdiv2.display="";

        pdiv1.display="block";
        pdiv2.display="none";


    }else if(divtoswitch == 2){
		if(document.additonalvisit.timestamp1==undefined){
				// IE 7 work arround
				pdiv1.display="";
				pdiv2.display="";


				pdiv1.display="none";
				pdiv2.display="block";

		}
		else
		{
			if(document.additonalvisit.timestamp1.value == ""){
				alert("Please choose an hour for the appointment in order to continue.");

			}else{

				// IE 7 work arround
				pdiv1.display="";
				pdiv2.display="";


				pdiv1.display="none";
				pdiv2.display="block";


			}
		}
    }

}


function submitpatientfollowup(){

    document.additonalvisit.action = 'patientFollowupReg.php'

    if(document.additonalvisit.packages_ID.checked == false){
        alert("Please check the package checkbox to continue.");
    } else {

        document.additonalvisit.submit();

    }



}




function sendstatusnotification(initialvisit)
{
	//alert('initial:'+initialvisit);
	//desabilitamos el boton
	document.sendappointmentconfirmation.buttonsn.disabled=true;
    if(initialvisit == 1){
		//alert('createpatient_d');
        document.sendappointmentconfirmation.action = "../createpatient_d.php";
    }else{
		//alert('createpatient_e');
        document.sendappointmentconfirmation.action = "../createpatient_e.php";
    }


    $('statusmessage').innerHTML = "sending message...";
    $('sendappointmentconfirmation').request({

        onComplete: function(respond){

            if(respond.responseText.indexOf('sentok') == -1){
                // populate the hours

                // email sent.
                $('statusmessage').innerHTML = "email message sent OK.";

            }else{

                $('statusmessage').innerHTML = "email message sent OK.";//respond.responseText;

            }

        }

    });




//return false;
}

function sendnotification_cancelexp(id,cancel,expire)
{

 //desabilitamos el boton
 document.sendappointmentconfirmation.buttonce.disabled=true;
 //alert('desabilitado boton');
 //alert('id'+id+'-cancel:'+cancel+'-expired:'+expire);
    if(cancel == 1){
        document.sendappointmentconfirmation.action = "send_cancelnotification.php?id="+id;
        //alert('cancel');
    }else if(expire == 1){
        document.sendappointmentconfirmation.action = "send_expirenotification.php?id="+id;
        //alert('expired');
    }else {
		document.sendappointmentconfirmation.action = "../createpatient_d.php";
       //alert('fecha nueva');
    }

    $('statusmessage').innerHTML = "sending message...";
    //alert('antes del ajax');
    $('sendappointmentconfirmation').request({
        onComplete: function(respond){
            //alert('responsetext:'+respond.responseText);
            if(respond.responseText.indexOf('sentok') != -1){
                // populate the hours
                // email sent.
                $('statusmessage').innerHTML = "email message sent OK.";
            }else{
                $('statusmessage').innerHTML = "email message sent OK.";
            }
        }
    });
//return false;

}

function deshabilitarLinks() {
    var enlaces = document.getElementsByTagName("A");
    var attname;
    for(var i=0; i<enlaces.length; i++) {
        attname = enlaces[i].getAttribute("name");
        if (attname == 'linkattend'){
            var nuevoSPAN = document.createElement("SPAN");
            nuevoSPAN.setAttribute("name", "enlaceEliminado");
            nuevoSPAN.name = "enlaceEliminado";
            // ATRIBUTOS - guardamos todos los atributos del enlace que nos interesen
            nuevoSPAN.setAttribute("href", enlaces[i].getAttribute("href") );
            // CONTENIDO - el span tendrá el mismo contenido que el enlace
            nuevoSPAN.innerHTML = enlaces[i].innerHTML;
            // SUSTITUIMOS - el enlace con el span nuevo
            enlaces[i].parentNode.replaceChild(nuevoSPAN, enlaces[i] );

        }
    }

}

function habilitarLinks() {
    var enlacesEliminados = document.getElementsByTagName("SPAN");
    for(var i=0; i<enlacesEliminados.length; i++) {
        if( enlacesEliminados[i].getAttribute("name") == "enlaceEliminado") {
            var nuevoA = document.createElement("A");
            // ATRIBUTOS - restauramos todos los atributos del enlace que nos interesen
            nuevoA.setAttribute("href", enlacesEliminados[i].getAttribute("href") );
            nuevoA.setAttribute("target", enlacesEliminados[i].getAttribute("target") );
            nuevoA.setAttribute("name", 'linkattend' );
            nuevoA.setAttribute("id", 'linkattend' );
            // CONTENIDO - el span tendrá el mismo contenido que el enlace
            nuevoA.innerHTML = enlacesEliminados[i].innerHTML;
            // SUSTITUIMOS - el span con el enlace original
            enlacesEliminados[i].parentNode.replaceChild(nuevoA, enlacesEliminados[i]);
            i--;
        }
    }
	//mostramos el div con los datos para la session en linea
	document.getElementById("userdatasession").style.display='';

}

function loadService() {
    //$('checkProvider').innerHTML = "Availability for provider";
    //alert ("Entro");
    //alert(document.signin.type);
    var seleccionado=document.signin.type.selectedIndex;
    var valor_select=document.signin.type.options[seleccionado].value;
    //alert(seleccionado);
    //alert(valor_select);
    document.getServiceSelect.type_select.value=valor_select;
    $('getServiceSelect').request({
        onComplete: function(respond){
            $('newselect').innerHTML = respond.responseText;

        }
    });

    return false;
}

function loadDescripcion(valor_type) {
    //$('checkProvider').innerHTML = "Availability for provider";
    //alert('entro');
    if (valor_type)
    {
        var seleccionado=document.signin.services.selectedIndex;
        var valor_select=document.signin.services.options[seleccionado].value;
    } else valor_select=0;
    //alert(seleccionado);
    //alert(valor_select);
    document.getDescriptionDiv.description_select.value=valor_select;
    $('getDescriptionDiv').request({
        onComplete: function(respond){
            $('divselect').innerHTML = respond.responseText;

        }
    });

    return false;
}