<%--
    Document   : kycCreation
    Created on : Mar 18, 2016, 12:19:23 PM
    Author     : TCS
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="LoginDb.DbHandler"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Connection"%>

<html>
    <head>
        <title>KYC Creation</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="${pageContext.request.contextPath}/js/Calendar.js?pacs=<%=((new java.util.Date()).getTime())%>"></script>
        <link rel="stylesheet" type="text/css" href="/PacsApplication/css/TableCSSCode.css?pacs=<%=((new java.util.Date()).getTime())%>" />
        <link rel="shortcut icon" href="${pageContext.request.contextPath}/img/favicon.ico?pacs=<%=((new java.util.Date()).getTime())%>" type="image/x-icon" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" type="text/css" href="/PacsApplication/css/styles.css?pacs=<%=((new java.util.Date()).getTime())%>"/>
        <link rel="stylesheet" type="text/css" href="/PacsApplication/css/ButtonAndText.css?pacs=<%=((new java.util.Date()).getTime())%>" />
        <link rel="stylesheet" type="text/css" href="/PacsApplication/css/info.css?pacs=<%=((new java.util.Date()).getTime())%>" />
        <script type="text/javascript" src="${pageContext.request.contextPath}/jquery-ui-1.10.4.custom/development-bundle/jquery-1.10.2.js?pacs=<%=((new java.util.Date()).getTime())%>"></script>
        <script type="text/javascript" src="/PacsApplication/chromejs/chrome.js?pacs=<%=((new java.util.Date()).getTime())%>"></script>
        <script type="text/javascript" src="/PacsApplication/js/iFrame_killer.js"></script>
        <style>
            #image-holder{
                position: absolute;
                top:280;
                right: 100;
                left: 850;
                bottom:330;
                width: auto;

            }

        </style>
        <script type="text/javascript">
            (function($) {
                $.fn.ajaxfileupload = function(options) {
                    var settings = {
                        params: {},
                        action: '',
                        onStart: function() { },
                        onComplete: function(response) { },
                        onCancel: function() { },
                        validate_extensions : true,
                        valid_extensions : ['jpg'],
                        submit_button : null
                    };

                    var uploading_file = false;

                    if ( options ) {
                        $.extend( settings, options );
                    }


                    // 'this' is a jQuery collection of one or more (hopefully)
                    //  file elements, but doesn't check for this yet
                    return this.each(function() {
                        var $element = $(this);

                        // Skip elements that are already setup. May replace this
                        //  with uninit() later, to allow updating that settings
                        if($element.data('ajaxUploader-setup') === true) return;

                        $element.change(function()
                        {
                            // since a new image was selected, reset the marker
                            uploading_file = false;

                            // only update the file from here if we haven't assigned a submit button
                            if (settings.submit_button == null)
                            {
                                upload_file();
                            }
                        });

                        if (settings.submit_button == null)
                        {
                            // do nothing
                        } else
                        {
                            settings.submit_button.click(function(e)
                            {
                                // Prevent non-AJAXy submit
                                e.preventDefault();

                                // only attempt to upload file if we're not uploading
                                if (!uploading_file)
                                {
                                    upload_file();
                                }
                            });
                        }

                        var upload_file = function()
                        {
                            if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);

                            // make sure extension is valid
                            var ext = $element.val().split('.').pop().toLowerCase();
                            if(true === settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
                            {
                                // Pass back to the user
                                settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
                            } else
                            {
                                uploading_file = true;

                                // Creates the form, extra inputs and iframe used to
                                //  submit / upload the file
                                wrapElement($element);

                                // Call user-supplied (or default) onStart(), setting
                                //  it's this context to the file DOM element
                                var ret = settings.onStart.apply($element, [settings.params]);

                                // let onStart have the option to cancel the upload
                                if(ret !== false)
                                {
                                    $element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
                                } else {
                                    uploading_file = false;
                                }
                            }
                        };

                        // Mark this element as setup
                        $element.data('ajaxUploader-setup', true);

                        /*
          // Internal handler that tries to parse the response
          //  and clean up after ourselves.
                         */
                        var handleResponse = function(loadedFrame, element) {
                            var response, responseStr = $(loadedFrame).contents().text();
                            try {
                                //response = $.parseJSON($.trim(responseStr));
                                response = JSON.parse(responseStr);
                            } catch(e) {
                                response = responseStr;
                            }

                            // Tear-down the wrapper form
                            element.siblings().remove();
                            element.unwrap();

                            uploading_file = false;

                            // Pass back to the user
                            settings.onComplete.apply(element, [ {
                                    status : true,
                                    message : 'Your file has been uploaded!'
                                }, settings.params ]);
                        };

                        /*
          // Wraps element in a <form> tag, and inserts hidden inputs for each
          //  key:value pair in settings.params so they can be sent along with
          //  the upload. Then, creates an iframe that the whole thing is
          //  uploaded through.
                         */
                        var wrapElement = function(element) {
                            // Create an iframe to submit through, using a semi-unique ID
                            var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
                            $('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
                            $('#'+frame_id).get(0).onload = function() {
                                handleResponse(this, element);
                            };

                            // Wrap it in a form
                            element.wrap(function() {
                                return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
                            })
                            // Insert <input type='hidden'>'s for each param
                            .before(function() {
                                var key, html = '';
                                for(key in settings.params) {
                                    var paramVal = settings.params[key];
                                    if (typeof paramVal === 'function') {
                                        paramVal = paramVal();
                                    }
                                    html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
                                }
                                return html;
                            });
                        }
                    });
                }
            })( jQuery )
        </script>
        <script lang="Javascript">
            $(document).ready(function() {
                $('#file').ajaxfileupload({
                    'action' : '/PacsApplication/UploadFile',
                    'onComplete' : function(response) {
                        $('#upload').hide();
                        $('#message').show();

                        var statusVal = JSON.stringify(response.status);

                        if(statusVal == "false")
                        {
                            $("#message").html("<font color='red'>"+JSON.stringify(response.message)+"</font>");
                        }
                        if(statusVal == "true")
                        {
                            $("#message").html("<font color='green'>"+JSON.stringify(response.message)+"</font>");
                        }
                    },
                    'onStart' : function() {
                        $('#upload').show();
                        $('#message').hide();
                    }
                });

                $('#sigUpld').ajaxfileupload({
                    'action' : '/PacsApplication/SigUploadFile',
                    'onComplete' : function(response) {
                        $('#sigupload').hide();
                        $('#sigmessage').show();

                        var statusVal = JSON.stringify(response.status);

                        if(statusVal == "false")
                        {
                            $("#sigmessage").html("<font color='red'>"+JSON.stringify(response.message)+"</font>");
                        }
                        if(statusVal == "true")
                        {
                            $("#sigmessage").html("<font color='green'>"+JSON.stringify(response.message)+"</font>");
                        }
                    },
                    'onStart' : function() {
                        $('#sigupload').show();
                        $('#sigmessage').hide();
                    }
                });
            });
        </script>
    </head>
    <body  onload="noBack()">
        <script type="text/javascript">

            function noBack()
            {
                window.history.forward();
            }
            function checkDiv(kycCreateForm)
            {
                if (kycCreateForm.cif.value == "")
                {
                    alert("!! * marked fields must be filled !!");
                    kycCreateForm.cif.focus();
                    return false;
                }
                if (kycCreateForm.linkedAccount.value == "")
                {
                    alert("!! * marked fields must be filled !!");
                    kycCreateForm.linkedAccount.focus();
                    return false;
                }
                if (kycCreateForm.tittle.value == "")
                {
                    alert("!! * marked fields must be filled !!");
                    kycCreateForm.tittle.focus();
                    return false;
                }
                if (kycCreateForm.fName.value == "")
                {
                    alert("!! * marked fields must be filled !!");
                    kycCreateForm.fName.focus();
                    return false;
                }
                if (kycCreateForm.lName.value == "")
                {
                    alert("!! * marked fields must be filled !!");
                    kycCreateForm.lName.focus();
                    return false;
                }
                if (kycCreateForm.add1.value == "")
                {
                    alert("!! * marked fields must be filled !!");
                    kycCreateForm.add1.focus();
                    return false;
                }
                if (kycCreateForm.add3.value == "")
                {
                    alert("!! * marked fields must be filled !!");
                    kycCreateForm.add3.focus();
                    return false;
                }
                if (kycCreateForm.distname.value == "")
                {
                    alert("!! * marked fields must be filled !!");
                    kycCreateForm.distname.focus();
                    return false;
                }
                if (kycCreateForm.gender.value == "")
                {
                    alert("!! * marked fields must be filled !!");
                    kycCreateForm.gender.focus();
                    return false;
                }
                if (kycCreateForm.religion.value == "")
                {
                    alert("!! * marked field must be filled !!");
                    kycCreateForm.religion.focus();
                    return false;
                }
                if (kycCreateForm.caste.value == "")
                {
                    alert("!! * marked field must be filled !!");
                    kycCreateForm.caste.focus();
                    return false;
                }
                if (kycCreateForm.dob.value == "")
                {
                    alert("!! * marked fields must be filled !!");
                    kycCreateForm.dob.focus();
                    return false;
                }

                if (kycCreateForm.cif.value.length != 11)
                {
                    alert("!!CIF Details must contain 11 digit !!");
                    kycCreateForm.cif.focus();
                    return false;
                }
                if (kycCreateForm.mNumber.value != "")
                {

                    if (kycCreateForm.mNumber.value.length != 10)
                    {
                        alert("!!Mobile Number Details must contain 10 digit !!");
                        kycCreateForm.mNumber.focus();
                        return false;
                    }
                }
                re = /^\d+$/; //this checks whether field contains digits
                if (!re.test(kycCreateForm.cif.value))
                {
                    alert("!!CIF Details could only contain numbers !!");
                    kycCreateForm.cif.focus();
                    return false;
                }

                var a = $('#dbDate').val();
                var chkdate = document.getElementById("dob").value;
                var edate = chkdate.split("/");
                var spdate = new Date(a.substring(6,10),a.substring(3,5) - 1,a.substring(0, 2));
                var sdd = spdate.getDate();
                var smm = spdate.getMonth();
                var syyyy = spdate.getFullYear()-0;
                var today = new Date(syyyy,smm,sdd).getTime();
                var e_date = new Date(edate[2],edate[1]-1,edate[0]).getTime();
                if(e_date > today)
                {
                    alert("Date of Birth is not valid!");
                    return false;
                }

                return true;
            }


            function hasExtension(inputID, exts) {
                var fileName = document.getElementById(inputID).value;
                return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName);
            }







            function submitform(kycCreateForm)
            {


                //if (kycCreateForm.file.value == "" || !$('#file').val()){
                //    alert("Please select Photograph to proceed!");
                //      return false;
                //  }
                if (!kycCreateForm.file.value == "" || $('#file').val()){
                    if (!hasExtension('file', ['.jpg'])) {
                        alert("Invalid Photo! Please select valid JPG/JPEG Photograph.");
                        return false;
                    }

                    //alert("file size is" + file.size);
                    var fileUpload = document.getElementById("file");

                    //Check whether the file is valid Image.
                    // var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
                    // if (regex.test(fileUpload.value.toLowerCase())) {

                    //Check whether HTML5 is supported.
                    if (typeof (fileUpload.files) != "undefined") {
                        //Initiate the FileReader object.
                        var reader = new FileReader();
                        //Read the contents of Image File.
                        reader.readAsDataURL(fileUpload.files[0]);
                        reader.onload = function (e) {
                            //Initiate the JavaScript Image object.
                            var image = new Image();

                            //Set the Base64 string return from FileReader as source.
                            image.src = e.target.result;

                            //Validate the File Height and Width.
                            image.onload = function () {
                                var height = this.height;
                                var width = this.width;
                                if (height > 500 || width > 500) {
                                    alert("Height and Width must not exceed 100px.");
                                    return false;
                                }
                                alert("Uploaded image has valid Height and Width.");
                                return true;
                            };

                        }
                    } else {
                        alert("This browser does not support HTML5.");
                        return false;
                    }
                }
                if (checkDiv(kycCreateForm))
                {
                    if($('#message').text().indexOf("Your file has been uploaded!") >= 0){
                        $('#nameOfFile').val($('#file').val());
                    }

                    if($('#sigmessage').text().indexOf("Your file has been uploaded!") >= 0){
                            $('#nameOfsigFile').val($('#sigUpld').val());
                        }
                    document.forms[0].handle_id.value = "Create";
                    document.kycCreateForm.action = '/PacsApplication/kycCreationServlet';
                    document.kycCreateForm.submit();
                }

            }



            function Upload() {
                //Get reference of FileUpload.
                var fileUpload = document.getElementById("file");

                //Check whether the file is valid Image.
                // var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
                // if (regex.test(fileUpload.value.toLowerCase())) {

                //Check whether HTML5 is supported.
                if (typeof (fileUpload.files) != "undefined") {
                    //Initiate the FileReader object.
                    var reader = new FileReader();
                    //Read the contents of Image File.
                    reader.readAsDataURL(fileUpload.files[0]);
                    reader.onload = function (e) {
                        //Initiate the JavaScript Image object.
                        var image = new Image();

                        //Set the Base64 string return from FileReader as source.
                        image.src = e.target.result;

                        //Validate the File Height and Width.
                        image.onload = function () {
                            var height = this.height;
                            var width = this.width;
                            if (height > 500 || width > 500) {
                                alert("Height and Width must not exceed 100px.");
                                return false;
                            }
                            alert("Uploaded image has valid Height and Width.");
                            return true;
                        };

                    }
                } else {
                    alert("This browser does not support HTML5.");
                    return false;
                }
                //  } else {
                //      alert("Please select a valid Image file.");
                //      return false;
                //  }
            }


            function readURL(input) {
                if (input.files && input.files[0]) {
                    var reader = new FileReader();

                    reader.onload = function (e) {
                        $('#blah').attr('src', e.target.result);
                    }

                    reader.readAsDataURL(input.files[0]);
                }
            }

            function sigreadURL(input) {
                if (input.files && input.files[0]) {
                    var reader = new FileReader();

                    reader.onload = function (e) {
                        $('#blahsig').attr('src', e.target.result);
                    }

                    reader.readAsDataURL(input.files[0]);
                }
            }

            $(document).ready(function() {
                $("#file").change(function(){
                    readURL(this);
                    $('#image-holder').show();
                });
                $("#sigUpld").change(function(){
                    sigreadURL(this);
                    $('#blahsig').show();
                });
            });


            function ShowParent()
            {

                document.forms[0].action = "${pageContext.request.contextPath}/kycCreation.jsp";
                document.forms[0].submit();
            }

            // to restrict back button
            history.pushState(null, null, location.href);
            window.addEventListener('popstate', function(event) {
                history.pushState(null, null, location.href);
            });
            
        </script>


        <jsp:include page="MenuHead.jsp" flush="true" />
        <br>

        <%
                    String sysDt = new String();
                    String error_msg = "";
                    Object error = request.getAttribute("message");
                    if (error != null) {
                        error_msg = error.toString();
                    }

                    Connection connection = null;
                    ResultSet rs = null;
                    Statement statement = null;
                    connection = DbHandler.getDBConnection();
                    try {
                        statement = connection.createStatement();
                        rs = statement.executeQuery("select to_char(SYSTEM_DATE,'DD/MM/YYYY') from system_date");
                        while (rs.next()) {
                            sysDt = rs.getString(1);
                        }
                       // statement.close();
                       // connection.close();
                    }  catch (Exception e) {
                System.out.println("Error occurred during processing.");
            } finally {
                try {
                    if(statement !=null)
                        statement.close();
                    if (connection != null)
                    connection.close();

            } catch (Exception e) {               
               System.out.println("Error Occurred during connection close.");
            }

            }
        %>

        <fieldset style="border-color: black; background-image: url('/PacsApplication/img/download.jpg'); border-width: 3px">
            <legend style="padding: 8px; border-radius: 20px; background-color: #006600; color: white">CUSTOMER (KYC) DETAILS CREATION</legend>
            <form action="" method="post" name="kycCreateForm">

                <br>

                <%if (!error_msg.equalsIgnoreCase("")) {%>
                <center><div class="info" id="errorMessage"><center><%= error_msg%></center></div></center>
                <% }%>
                <br>
                <br><br>

                <div id="create" align="left" >
                    <table>
                        <tbody>
                            <tr>
                                <td>Select Photograph:</td>
                                <td><input type="file" name="file" id="file" size="60"/>
                                    <div id="upload" style="display: none;">Uploading..</div>
                                    <div id="message"></div>
                                </td>
                            </tr>
                            <tr>
                                <td>Select Signature:</td>
                                <td><input type="file" name="sigUpld" id="sigUpld" size="60"/>
                                    <div id="sigupload" style="display: none;">Uploading..</div>
                                    <div id="sigmessage"></div>
                                </td>
                            </tr>
                            <tr>
                                <td>CBS CIF No:*</td>
                                <td><input type="text" name="cif" id="cif" maxlength=11 style="width: 260px;" /></td>
                            </tr>
                            <tr>
                                <td>Customer Type: </td>
                                <td>
                                    <select name="cType"  id="cType" style="width: 260px">
                                        <OPTION value="">      -- Please Select --     </OPTION>
                                        <option value="PERSONAL">PERSONAL</option>
                                        <option VALUE="NON-PERSONAL">NON-PERSONAL</option>

                                    </select>
                                </td>
                            </tr>

                            <tr>
                                <td>Linked CBS A/C No.*</td>
                                <td><input type="text" name="linkedAccount" id="linkedAccount"  /></td>
                            </tr>
                            <tr>
                                <td>Title:*</td>
                                <td>
                                    <select name="tittle"  id="tittle">
                                        <OPTION value="">      -- Please Select --     </OPTION>
                                        <option value="Mr.">Mr.</option>
                                        <option value="Mrs.">Mrs.</option>


                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td>First Name:*</td>
                                <td><input type="text" name="fName" style="width: 260px" id="fName" /></td>
                            </tr>
                            <tr>
                                <td>Middle Name: </td>
                                <td><input type="text" name="mName" style="width: 260px" id="mName"/></td>
                            </tr>
                            <tr>
                                <td>Last Name:*</td>
                                <td><input type="text" name="lName" style="width: 260px" id="lName" /></td>
                            </tr>
                            <tr>
                                <td>Guardian Name/ Husband Name: </td>
                                <td><input type="text" name="gName" style="width: 260px" id="gName"  /></td>
                            </tr>
                            <tr>
                                <td>
                                    Address Line1:*
                                </td>
                                <td>
                                    <textarea name="add1" id="add1" style="resize: none;" ></textarea>
                                </td>

                                <td>Block: </td>
                                <td><input type="text" name="block" id="block" /></td>

                                <td>
                                    Address Line2:
                                </td>
                                <td>
                                    <textarea name="add2" id="add2" style="resize: none;"></textarea>
                                </td>
                                <td>
                                    Address Line3:*
                                </td>
                                <td>
                                    <textarea name="add3" id="add3" style="resize: none;"></textarea>
                                </td>
                            </tr>
                            <tr>
                                <td>District:*</td>
                                <td><input type="text" name="distname" style="width: 260px" id="distname" /></td>
                                <td>City/Town: </td>
                                <td><input type="text" name="cityname" id="cityname" /></td>

                                <td>State: </td>
                                <td><input type="text" name="statename" id="statename" /></td>
                                <td>Email Id: </td>
                                <td><input  type="text" name="emailId"  id="emailId"/></td>
                            </tr>
                            <tr>
                                <td>Date Of Birth:*</td>
                                <td><input type="text" readonly name="dob"  id="dob"/><a href="#" onclick="return getCalendar(document.forms[0].dob);"><img src="${pageContext.request.contextPath}/img/calendar.gif" name="imgr" border="0" width="15" height="20" /></a></td>
                            </tr>
                            <tr>
                                <td>Gender:*</td>
                                <td><select name="gender" id="gender">
                                        <option value="">-- Please select --</option>
                                        <option value="Male">Male</option>
                                        <option value="Female">Female</option>
                                        <option value="Other">Other</option>
                                    </select>
                                </td>
                                <td>Religion:*</td>
                                    <td><select id="religion" name="religion">
                                            <option value="" disabled selected>--- Select ---</option>
                                            <option value="1">Hindu</option>
                                            <option value="2">Muslim</option>
                                            <option value="3">Christian</option>
                                            <option value="4">Sikh</option>
                                            <option value="5">Jain</option>
                                            <option value="6">Buddhist</option>
                                            <option value="7">Parsi</option>
                                            <option value="8">Others</option>
                                        </select>
                                    </td>
                                    <td>Caste:*</td>
                                    <td><select id="caste" name="caste">
                                            <option value="" selected disabled>--- Select ---</option>
                                            <option value="1">General</option>
                                            <option value="2">SC</option>
                                            <option value="3">ST</option>
                                            <option value="4">Others</option>
                                        </select>
                                    </td>
                            </tr>
                            <tr>
                                <td>Mobile Number: </td>
                                <td><input type="text" maxlength=10 name="mNumber" id="mNumber" /></td>
                            </tr>
                            <tr>
                                <td>ID Type: </td>
                                <td><input type="text" name="idType" id="idType" /></td>
                                <td>ID Number: </td>
                                <td><input type="text" name="idNumber" id="idNumber" /></td>
                            </tr>
                            <tr>
                                <td>ID Issue Date: </td>
                                <td><input type="text" readonly name="idIssueDate" id="idIssueDate" /><a href="#" onclick="return getCalendar(document.forms[0].idIssueDate);"><img src="${pageContext.request.contextPath}/img/calendar.gif" name="imgr" border="0" width="15" height="20" /></a></td>
                                <td>ID Issued At: </td>
                                <td><input type="text" name="idIssueAt"  id="idIssueAt"/></td>
                            </tr>

                        </tbody>
                    </table>
                    <div id="image-holder" style="display:none;"><img id="blah" src="#" alt="Invalid image" width="140" height="150" border="1px" />&nbsp;&nbsp;<img id="blahsig" src="#" alt="Invalid image" width="180" height="100" border="1px" style="display:none;"/></div>
                    <br>
                    <center><input type="button" value="Submit" onclick="javascript:submitform(kycCreateForm)">
                        <input type="button" value="Reset" name="reset" onclick="javascript:ShowParent();" />
                    </center>
                </div>
                <!--<div >
                    <img src="${pageContext.request.contextPath}/img/faceDefault.jpg" name="imgr" border="2" width="100" height="100" style="margin:10px 10px 10px 50px;" />
                    <div><input type="file" name="photoFile" id="photoFile" /></div>
                </div>-->
                <!-- <div id="wrapper" style="margin-top: 20px;"><input id="fileUpload" name="fileUpload" type="file"/>
                     <div id="image-holder"></div>-->
                <input type="hidden" name="handle_id" value="Create" />
                <input type="hidden" name="dbDate" id="dbDate" value="<%=sysDt%>" />
                <input type="hidden" name="nameOfFile" id="nameOfFile" value="">
                <input type="hidden" name="nameOfsigFile" id="nameOfsigFile" value="">
            </form>
        </fieldset>
    </body>
</html>
