{% extends "::base.html.twig" %}        

{% block body %}

<div id="navbar" style="font-size:18px;">   
    <ul>       
        <li><a href="javascript: submitFormAssistance(9)">Home</a></li>
        <li><a href="javascript: submitFormAssistance(1)">Client Information</a></li> 
        <li><a href="javascript: submitFormAssistance(2)">Finance</a></li>
        <li><a href="javascript: submitFormAssistance(3)">Notes</a></li>
        <li><a href="javascript: submitFormAssistance(4)" style="background-color:#00b5cb; font-size:30px;">Assistance</a></li>
        <li><a href="javascript: submitFormAssistance(5)">Referrals</a></li>
    </ul> 
</div>

{% if app.session.hasFlash('info') %}
    <div class="flash-notice" style="padding-left:27px; padding-top:10px;">
        {{ app.session.flash('info') }}
    </div>
{% endif %}

<section class="assistance" id="assistance">
    <br/>
    <input type=button onClick="location.href='javascript: submitFormAssistance(6)'" value='Save/Next' style="color:#00b5cb; background-color:white;">       
    {#<input type=button onClick="location.href='javascript: clearform()'" value='Cancel Changes' style="color:#00b5cb; background-color:white; margin-right: 30px;">#}
    <div style="padding-right:50px; float:right;">
        {% set urlpath = path('DorcasTabithaBundle_print_pledgeShow', { 'client_id': client.clientid } ) %}
        <input type="button" value="Pledge Confirmation" onclick="window.open(' {{ urlpath }} ','','width=850,height=1000, menubar=yes')" />        

        {% set urlpath = path('DorcasTabithaBundle_print_promissoryShow', { 'client_id': client.clientid } ) %}
        <input type="button" value="Promissory Note" onclick="window.open(' {{ urlpath }} ','','width=850,height=1000, menubar=yes')" />        
    </div>


    <br>
    <section class="previous-assistance">       
        {% include 'DorcasTabithaBundle:Assistance:assistanceloop.html.twig' with { 'assistances': assistances } %}
    </section>
</section>

<section class="assistance" id="assistances">
            {# .. #}

    <br/>
    <br />

    {% if form is defined %}
        {% if blockmessage is defined %}
            {% if blockmessage != true %}
                <div style="color:maroon;">
                    {{ form_errors(form) }}
                </div>
            {% endif %}
        {% endif %}
    {% endif %}

    {% if valid is defined %}
        {% if valid %}
            {% render 'DorcasTabithaBundle:Assistance:new' with { 'client_id': client.clientid, 'history': history } %} 
        {% else %}
            {% render 'DorcasTabithaBundle:Assistance:renew' with { 'client_id': client.clientid, 'history': history } %}         
        {% endif %}
    {% else %}
        {% render 'DorcasTabithaBundle:Assistance:renew' with { 'client_id': client.clientid, 'history': history } %}
    {% endif %}


</section>


{#    </div>
</div> #}

{% endblock %}

{% block javascripts %}

    {{ parent() }}           

<script type="text/javascript">

$(function() {
//    $( ".datepicker" ).datepicker({ showAnim: "slideDown" });
    $( ".datepicker" ).datepicker({ changeMonth: true, changeYear: true, yearRange:"-90:+0", maxDate: "+0d"
        });
        });

window.alert = function(message) {
	$('#override_javascript_alert').html(message).dialog({
		modal:true,
		title:'Tabitha Validation Message',
		buttons: {
			'OK':function(){
				$(this).dialog('close');
			}
		}
	});
};


warnusers = function(message) {
	$('#override_javascript_alertx').html(message).dialog({
		modal: true,
                title:'Tabitha Warning Message',
			buttons: {
				"Continue to Page": function() {
                                        var form = document.forms["clientform"];
                                        form.submit();
					$( this ).dialog( "close" );
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});
	};


/**--------------------------
//* Validate Date Field script- By JavaScriptKit.com
//* For this script and 100s more, visit http://www.javascriptkit.com
//* This notice must stay intact for usage
---------------------------**/

function checkdate(input){
    var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
    var returnval=false
    if (!validformat.test(input))
    {
//        alert("Invalid Date Format. Please correct and submit again.")
    }
    else{ //Detailed check for valid date ranges
        var monthfield=input.split("/")[0]
        var dayfield=input.split("/")[1]
        var yearfield=input.split("/")[2]
        var dayobj = new Date(yearfield, monthfield-1, dayfield)
        if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
        {
//            alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
        }
        else
            returnval=true
    }
//    if (returnval==false) input.select()
    return returnval
}

function submitFormAssistance(navnumber) {
                    var form = document.forms["clientform"];
                    var hiddenField = document.createElement("input"); 
                    hiddenField.setAttribute("type", "hidden"); 
                    hiddenField.setAttribute("name", "passnav"); 
                    hiddenField.setAttribute("value", navnumber); 
                    form.appendChild(hiddenField);
                    saveallabove(true);
                }


function saveallabove(nav)
{ 
    // Read all values
    var foodGiven = document.getElementById('assistanceform_food_given').checked;
    var foodGivenDate = document.getElementById('assistanceform_food_given_date').value;
    var checkDorcas = document.getElementById('assistanceform_check_dorcas').value;
    var checkOasis = document.getElementById('assistanceform_check_oasis').value;
    var checkSfumc = document.getElementById('assistanceform_check_sfumc').value;
    var checkOther = document.getElementById('assistanceform_check_other').value;
    var checksIssuedPayee = document.getElementById('assistanceform_checks_issued_payee').value;
    var checksIssuedDate = document.getElementById('assistanceform_checks_issued_date').value;
    var checkPurpose = document.getElementById('assistanceform_checkpurpose').value;
    var specialProgram = document.getElementById('assistanceform_special_program').value;
    var specialProgramDate = document.getElementById('assistanceform_special_program_date').value;
    var specialProgramRecipientName = document.getElementById('assistanceform_special_program_recipient_name').value;
    var specialProgramParentName = document.getElementById('assistanceform_special_program_parent_name').value;
    var specialProgramProgramCheck = document.getElementById('assistanceform_special_program_check').value;
    
    okaytosubmit = true;
    alertMessage = "";

    // Check for nothing entered
    if (foodGiven == true) okaytosubmit = true;
    else if (foodGivenDate) okaytosubmit = true;
    else if (checkDorcas) okaytosubmit = true;
    else if (checkOasis) okaytosubmit = true;
    else if (checkSfumc) okaytosubmit = true;
    else if (checkOther) okaytosubmit = true;
    else if (checksIssuedPayee) okaytosubmit = true;
    else if (checksIssuedDate) okaytosubmit = true;
    else if (checkPurpose != 1) okaytosubmit = true;
    else if (specialProgram != 1) okaytosubmit = true;
    else if (specialProgramDate) okaytosubmit = true;
    else if (specialProgramRecipientName) okaytosubmit = true;
    else if (specialProgramParentName) okaytosubmit = true;
    else if (specialProgramProgramCheck) okaytosubmit = true;
    else 
    {
        alertMessage = alertMessage + '&#8227 No information entered, nothing saved. <br/>';
        if ( nav ) okaytosubmit = true;
        else okaytosubmit = false; 
    } 

    // Check Food Given Date for valid date
    if (foodGivenDate && !checkdate(foodGivenDate))
    {
        alertMessage = alertMessage + '&#8227 Please enter a valid Food Given Date. <br/>';
        okaytosubmit = false;
    }

    // Check Special Programs Date for valid date
    if (specialProgramDate && !checkdate(specialProgramDate))
    {
        alertMessage = alertMessage + '&#8227 Please enter a valid Special Programs <br/>&nbsp Date. <br/>';
        okaytosubmit = false;
    }

    // Check Checks Issued Date for valid date
    if (checksIssuedDate && !checkdate(checksIssuedDate))
    {
        alertMessage = alertMessage + '&#8227 Please enter a valid Checks Issued Date. <br/>';
        okaytosubmit = false;
    }

    // Check Special Programs for non-required fields and do not send to server side - do nothing
    if ((specialProgramDate || specialProgramRecipientName || specialProgramParentName)
        && (specialProgram == 1 && !specialProgramProgramCheck)) 
    {
        alertMessage = alertMessage + '&#8227 Please enter Special Programs Program <br/>&nbsp and Amount. <br/>';
        okaytosubmit = false;
    }

    // Check for Special Programs Program selected but Amount is not entered
    if (specialProgram != 1 && !specialProgramProgramCheck)
    {
        alertMessage = alertMessage + '&#8227 Please enter a Special Programs Amount <br/>&nbsp for Program Selected. <br/>';
        okaytosubmit = false;
    }

    // Check for Special Programs Amount entered but Program is not Selected
    if (specialProgram == 1 && specialProgramProgramCheck)
    {
        alertMessage = alertMessage + '&#8227 Please enter a Special Programs Program <br/>&nbsp for Amount Selected. <br/>';
        okaytosubmit = false;
    }
    
    // Check Checks Issued for at least one dollar field entered if ANY other required fields are entered
    if ((checkPurpose != 1 || checksIssuedDate || checksIssuedPayee) && !(checkDorcas || checkOasis || checkSfumc || checkOther))
    {
        alertMessage = alertMessage + '&#8227 Please enter Checks Issued Purpose, <br/>&nbsp; Date, Payee, and a dollar amount in <br/>&nbsp; at least one dollar field. <br/>';
        okaytosubmit = false;
    }
   
    // Linda's code
   // if ((checkPurpose && checksIssuedDate && checksIssuedPayee) && (checkDorcas || checkOasis || checkSfumc || checkOther)) {}
   //   else
   //      {
   //      alertMessage = alertMessage + '&#8227 Please enter Checks Issued Purpose, <br/>&nbsp Date, Payee, and a dollar amount in <br/>&nbsp at least one dollar field.<br/>';
   //     okaytosubmit = false;
   //     }

    // Check Checks Issued for any dollar field has a value and all three required fields are not present
    if (!(checkPurpose != 1 && checksIssuedDate && checksIssuedPayee) && (checkDorcas || checkOasis || checkSfumc || checkOther))
    {
        alertMessage = alertMessage + '&#8227 Please enter Checks Issued Purpose, <br/>&nbsp Date, Payee, and a dollar amount in <br/>&nbsp at least one dollar field. <br/>';
        okaytosubmit = false;
    }

    if (okaytosubmit == true)
    {
        var form = document.forms["clientform"];
        form.submit();
    }
    else
    {
        // If nav is selected and none of these values were set, then it is okay to redirect
            if((foodGiven == false && !foodGivenDate) && !checkDorcas
                    && !checkOasis && !checkOther && !checkSfumc
                    && !specialProgramProgramCheck && specialProgram == 1
                    && checkPurpose == 1 && nav)
            {
                alertMessage = '<p style = "color:red;"> Warning: Your changes to Assistance will not be saved! </p>';
                warnusers(alertMessage);
            }
            else alert(alertMessage);
    }
}




function Xclearform()
{
    var checkboxid = document.getElementById('assistanceform_food_given');
    checkboxid.checked = false;

    var textboxid = document.getElementById('assistanceform_food_given_date');
    textboxid.value = "";

    var input = document.getElementById('assistanceform_check_dorcas');
    input.value = "";
    var input = document.getElementById('assistanceform_check_oasis');
    input.value = "";
    var input = document.getElementById('assistanceform_check_sfumc');
    input.value = "";
    var input = document.getElementById('assistanceform_check_other');
    input.value = "";
    var input = document.getElementById('assistanceform_checks_issued_payee');
    input.value = "";
    var input = document.getElementById('assistanceform_checks_issued_date');
    input.value = "";
    var input = document.getElementById('assistanceform_checkpurpose');
    input.value = "";  
}

function isNumber(field)
{
     if( isNaN(field.value)){
        alert("Please enter a dollar amount with no dollar sign.");
        field.value = 0;
        field.focus();
         }
}

    function fgcheckbox(field)
    {
        var checkboxid = document.getElementById('assistanceform_food_given');
        if(checkboxid.checked == true){
            //Get todays date
            var now = new Date();
            var formattednow = now.format("mm/dd/yyyy");
            var textboxid = document.getElementById('assistanceform_food_given_date');
            textboxid.value = formattednow;
        }    
        else
        {
            var textboxid = document.getElementById('assistanceform_food_given_date');
            textboxid.value = "";  
        }
    }

    function fgdate(field)
    {
        var checkboxid = document.getElementById('assistanceform_food_given');
        var textboxid = document.getElementById('assistanceform_food_given_date');
        checkboxid.checked = true;
        if (textboxid.value == "") {
            checkboxid.checked = false;
        }
    }



    /*
    * Date Format 1.2.3
    * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
    * MIT license
    *
    * Includes enhancements by Scott Trenda <scott.trenda.net>
    * and Kris Kowal <cixar.com/~kris.kowal/>
    *
    * Accepts a date, a mask, or a date and a mask.
    * Returns a formatted version of the given date.
    * The date defaults to the current date/time.
    * The mask defaults to dateFormat.masks.default.
    */

    var dateFormat = function () {
            var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
                    timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
                    timezoneClip = /[^-+\dA-Z]/g,
                    pad = function (val, len) {
                            val = String(val);
                            len = len || 2;
                            while (val.length < len) val = "0" + val;
                            return val;
                    };

            // Regexes and supporting functions are cached through closure
            return function (date, mask, utc) {
                    var dF = dateFormat;

                    // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
                    if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
                            mask = date;
                            date = undefined;
                    }

                    // Passing date through Date applies Date.parse, if necessary
                    date = date ? new Date(date) : new Date;
                    if (isNaN(date)) throw SyntaxError("invalid date");

                    mask = String(dF.masks[mask] || mask || dF.masks["default"]);

                    // Allow setting the utc argument via the mask
                    if (mask.slice(0, 4) == "UTC:") {
                            mask = mask.slice(4);
                            utc = true;
                    }

                    var	_ = utc ? "getUTC" : "get",
                            d = date[_ + "Date"](),
                            D = date[_ + "Day"](),
                            m = date[_ + "Month"](),
                            y = date[_ + "FullYear"](),
                            H = date[_ + "Hours"](),
                            M = date[_ + "Minutes"](),
                            s = date[_ + "Seconds"](),
                            L = date[_ + "Milliseconds"](),
                            o = utc ? 0 : date.getTimezoneOffset(),
                            flags = {
                                    d:    d,
                                    dd:   pad(d),
                                    ddd:  dF.i18n.dayNames[D],
                                    dddd: dF.i18n.dayNames[D + 7],
                                    m:    m + 1,
                                    mm:   pad(m + 1),
                                    mmm:  dF.i18n.monthNames[m],
                                    mmmm: dF.i18n.monthNames[m + 12],
                                    yy:   String(y).slice(2),
                                    yyyy: y,
                                    h:    H % 12 || 12,
                                    hh:   pad(H % 12 || 12),
                                    H:    H,
                                    HH:   pad(H),
                                    M:    M,
                                    MM:   pad(M),
                                    s:    s,
                                    ss:   pad(s),
                                    l:    pad(L, 3),
                                    L:    pad(L > 99 ? Math.round(L / 10) : L),
                                    t:    H < 12 ? "a"  : "p",
                                    tt:   H < 12 ? "am" : "pm",
                                    T:    H < 12 ? "A"  : "P",
                                    TT:   H < 12 ? "AM" : "PM",
                                    Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                                    o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                                    S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
                            };

                    return mask.replace(token, function ($0) {
                            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
                    });
            };
    }();

    // Some common format strings
    dateFormat.masks = {
            "default":      "ddd mmm dd yyyy HH:MM:ss",
            shortDate:      "m/d/yy",
            mediumDate:     "mmm d, yyyy",
            longDate:       "mmmm d, yyyy",
            fullDate:       "dddd, mmmm d, yyyy",
            shortTime:      "h:MM TT",
            mediumTime:     "h:MM:ss TT",
            longTime:       "h:MM:ss TT Z",
            isoDate:        "yyyy-mm-dd",
            isoTime:        "HH:MM:ss",
            isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
            isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
    };

    // Internationalization strings
    dateFormat.i18n = {
            dayNames: [
                    "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
                    "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
            ],
            monthNames: [
                    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
                    "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
            ]
    };

    // For convenience...
    Date.prototype.format = function (mask, utc) {
            return dateFormat(this, mask, utc);
    };


</script>

    
{% endblock %}