var isTamil = isTamil || false;

function loadFn(){
    var $iframe = $('#frm-dwnld-dialog iframe')
    ,   $iBody  = $iframe.contents().find('body')
    ,   style = 'text-align: center; padding: 17% 0px; color: #999; letter-spacing: 3px; font-size: 24px; text-shadow: 3px 3px 3px #ccc;';
    
    //$iBody.html('<div style="'+ style+'">File is downloading ...</div>');
    setTimeout(function(){
        var len = $iframe.contents().find('.plceholder').length;
        if( len > 0 ) {
            $iBody.html('<div class="plceholder" style="'+ style+'; color: #1ba;">File is being downloaded ...</div>');

            setTimeout(function(){
                $('#frm-dwnl-clse-btn').trigger('click');
            }, 2500);
        }
    }, 400);

};

function set_timepicker() {
    $(".timepicker").timepicker({
        showInputs: false
    });
}

function reset_timepicker() {
    $('.timepicker:not(.value_setted)').val('');
    $(".timepicker").addClass('value_setted');
}

function set_datepicker() {
    $('.datepicker').each(function(index, element) {
        if ($(element).attr('datepicker_set') === undefined) {
            $(element).datepicker({
                format: 'dd-mm-yyyy',
                autoclose: true,
                todayHighlight: true,
                startView: 0
            });
            
            $(element).prop('autocomplete', 'off');
            $(element).attr('datepicker_set', true);
        }
    });
}

function firstToUpperCase( str ) {
    return str.substr(0, 1).toUpperCase() + str.substr(1);
}

function set_datetimepicker() {
    $('.datepicker').each(function(index, element) {
        if ($(element).attr('datetimepicker_set') === undefined) {
            $(element).datetimepicker();
            
            $(element).prop('autocomplete', 'off');
            $(element).attr('datetimepicker_set', true);
        }
    });
}

function convert_str_to_date(date_str, time_str) {
    var date, month, year;
    if (date_str != '') {
        date = parseInt(date_str.substr(0, 2));
        month = parseInt(date_str.substr(3, 2));
        year = parseInt(date_str.substr(6, 4));
    }
    else {
        var cur_date = new Date();
        date = cur_date.getDate();
        month = cur_date.getMonth();
        month = month + 1;
        year = cur_date.getFullYear();
    }
    
    var hr = 0;
    var mins = 0;
    if (time_str != '') {
        hr = parseInt(time_str.substr(0, 2));
        mins = parseInt(time_str.substr(3, 2));
        var periode = time_str.substr(6, 2);
        
        if (periode == 'PM') {
            if (hr != 12) {
                hr = hr + 12;
            }
        }
        else if (hr == 12) {
            hr = 0;
        }
    }

    return new Date(year, month - 1, date, hr, mins)
}

function cal_date_diff_in_ms(date1, date2) {
    return date2.getTime() - date1.getTime();
}

function cal_date_diff(date1, date2) {
    var date_in_ms = date2.getTime() - date1.getTime();
    return new Date(date_in_ms);
}

function show_alert(msg) {
    $('#alert_message .modal-body .message_container').html(msg);
    $("#alert_message").modal({
        backdrop: "static",
        keyboard: true,
        show: true
    });
}

function show_confirm(msg, redirect_url) {
    $('#confirm .modal-body .message_container').html(msg);
    $('#confirm .modal-footer input[name="redirect_url"]').val(redirect_url);
    $("#confirm").modal({
        backdrop: "static",
        keyboard: true,
        show: true
    });
}

function show_loader(msg) {
    $('#loader_popup .modal-body .loading_content').html(msg);
    $("#loader_popup").modal({
        backdrop: "static",
        show: true
    });
}

function hide_loader() {
    $("#loader_popup").modal('hide');
}

function show_log_in_console(log_obj) {
    console.log(log_obj.responseText);
}

function integer_value() {
    $('.integer_value,.contact-no').each(function() {
        if (!$(this).hasClass('integer_only')) {
            $(this).on('keydown', function(e) {
                e = (e) ? e : window.event;
                var charCode = (e.which) ? e.which : e.keyCode;
                if ((charCode >= 96 && charCode <= 105) || (charCode >= 48 && charCode <= 57) || (charCode >= 37 && charCode <= 40)
                    || charCode == 8 || charCode == 9 || charCode == 13 || charCode == 46) { // Conditions to check integer
                    return true;
                }
                
                return false;
            });
            
            $(this).addClass('integer_only');
        }
    });
}

/* function float_value() {
    $('.float_value').each(function() {
        if (!$(this).hasClass('float_only')) {
            $(this).on('keydown', function(e) {
                e = (e) ? e : window.event;
                var charCode = (e.which) ? e.which : e.keyCode;
                if (((charCode >= 96 && charCode <= 105) || charCode == 110) // Number pad
                    || ((charCode >= 48 && charCode <= 57) || charCode == 190)
                    || ((charCode >= 37 && charCode <= 40) || charCode == 8 || charCode == 9 || charCode == 13 || charCode == 46 ) //  Left, right, top, bottom, Backspace, tap, enter, delete
                    ) { // Conditions to check float value
                    return true;
                }
                
                return false;
            });
            
            $(this).addClass('float_only');
        }
    });
} */

function file_preview(file) {
    var file_data = $(file).prop('files')[0];
    var _URL = window.URL || window.webkitURL;
    var img = new Image();
    var file_size = file_data.size / 1024;
    file_size = file_size / 1024;
    img.onload = function() {
        var return_val = true;
        if (($(file).attr('data-allowed_width') !== undefined) && ($(file).attr('data-allowed_width') != '')
            || ($(file).attr('data-allowed_height') !== undefined) && ($(file).attr('data-allowed_height') != '')) {
            var allowed_width = parseFloat($(file).attr('data-allowed_width'));
            var allowed_height = parseFloat($(file).attr('data-allowed_height'));
            if ((allowed_width != img.width) || (allowed_height != img.height)) {
                alert('Image size should be Width: ' + allowed_width + 'px X Height: ' + allowed_height + 'px');
                $(file).val('');
                return_val = false;
            }
        }
        else if ($(file).attr('data-allowed_size') != 'undefined') {
            var allowed_size = parseInt($(file).attr('data-allowed_size'));
            if (file_size > allowed_size) {
                alert('The file size exceeds the limit allowed and cannot be upload!');
                $(file).val('');
                return_val = false;
            }
        }
        
        if (return_val) {
            $(file).parents('.form-group').find('.img_preview').html(img);
        }
        
        return return_val;
    }
    img.src = _URL.createObjectURL(file_data);  
}

function show_textarea_count() {
    $('textarea.show_txt_count').each(function() {
        if ($(this).next('.txt_left').length == 0) {
            var text_count = (typeof($(this).attr('maxlength')) != 'undefined') ? $(this).prop('maxlength') : 500;
            $(this).after('<div class="major_txt_color txt_left">Left: <b>' + text_count + '</b> charecters only.</div>');
        }
        
        $(this).on('keyup', function() {
            var text_count = (typeof($(this).attr('maxlength')) != 'undefined') ? $(this).prop('maxlength') : 500;
            $(this).next().find('b').html(parseInt(text_count) - $(this).val().length); 
        });
    });
}

function set_chosen() {
    $('.chosen-select').each(function(index, element) {
        if (!$(element).hasClass('has_chosen')) {
            $(element).chosen({
                allow_single_deselect: true,
                placeholder_text_single: 'Select an Option',
                no_results_text: 'No results match!'
            });
            $(element).addClass('has_chosen');
            
            $(document).on('mouseover', '.active-result', function() {
                if ($(this).attr('tool_tip_text') !== undefined) {
                    show_chosen_tooltip(this);
                }
            });
            
            $(document).on('mouseout', '.active-result', function() {
                if ($(this).attr('tool_tip_text') !== undefined) {
                    hide_tooltip();
                }
            });
        }
    });
    
    $('.chosen-container').css('min-width', '200px');
    $('.chosen-container').css('max-width', '300px');
    $('.chosen-container').css('width', '100%');
}

function update_choosen(_this){
    $(_this).trigger("chosen:updated");
}

function validateEmail( email ) {
    var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if( pattern.test( email ) ) return true;
    else return false;
}

function goBack() {
    clearMsg( 0 );
    window.history.back();
}

function clearMsg( delay, fadeOut ) {
    if( delay == '' || typeof delay == 'undefined' ) {
        delay = 5000;
    }
    
    if( fadeOut == '' || typeof fadeOut == 'undefined' ) {
        fadeOut = 'slow';
    }
    
    window.setTimeout( function() {
        /*$('.flash_msg').fadeOut(function(){
            $('.flash_msg').remove();
        }, 1000);*/
        
        $('.flash_msg').fadeOut(fadeOut).remove();
    }, delay); 
}

$(window).load(function() {
    $(".page_loader").fadeOut("slow");
});

/*
* Billing Scripts
*/
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
function getTwoDigits( value ) {
    
    return value < 10 ? '0'+value : value;
}

function globalMsg(msg) {
    
    if( $('.err-container').length == 0 ) {
        $('.box-body:first').prepend( '<div class="err-container"></div>' );
    }

    $('html, body').animate({
        scrollTop: $('.err-container').offset().top-($('.header:first').height()+60)
    }, 1000);
    $('.err-container').html(msg).slideDown('slow');    

    window.setTimeout(function(){
        $('.err-container').slideUp('slow', function(){$(this).html('')});
    }, 15000);
}

function scrollTo($this) {
    if( typeof $this != 'undefined' ) {
        var o = $this.offset();
        if( typeof o != 'undefined' ) {
            $('body, html').animate({
                scrollTop: o.top+'px'
            }, 1000);
        }
    }
}

function autoValidate($thisWrap) {
    
    var err     = 0
    ,   msg     = ''
    ,   $form   = (typeof $thisWrap != 'undefined' ? $thisWrap : $('form'))
    ,   $sbmtBtn= $errEle = $form.find('[type="submit"], .sbmt-btn, #sbmt-btn')
    ,   type  = ''
    ,   isDialog = $form.hasClass('dialog') || $form.parent().closest('.dialog').length > 0 ? true : false;
    
    $form.find('.err').slideUp('slow', function(){ $(this).remove() });
    $('.err-ele').removeClass('err-ele');
    
    $form.find('.req').each(function(){
        if( typeof $thisWrap == 'undefined' && $(this).hasClass('ignore') ) {
            // Skip for Modal "req" class..
            return true;
        }
        
        var $this= $(this)
        ,   lblText = $this.attr('data-err-msg') || "";
        
        type = $this.attr('type') || "";
        
        if( type == 'checkbox' || type == 'radio' ) {
            var name = $this.attr('name');
            $errEle = $this.parent().closest('.form-group').find('> div:first');
            
            if( $('[name="'+ name +'"]:checked').length == 0 ) {
                ++err;
                $this = $('[name="'+ name +'"]:first');
                window.setTimeout(function(){
                    clearErrors();
                }, 2500);
            }
            
        }else{
            type = $(this).prop('tagName').toLowerCase();
            $errEle = $this;
            
            if( $this.val() == '' ){
                ++err;
            }else if($this.hasClass('email') && !validateEmail( $this.val() )) {
                ++err;
                lblText = 'valid email address!';
            }
        }
        
       if( err > 0 ) {
            msg  = 'Please ';
            
            var $errTrgt = $this.parent().closest('.err-target') || "";
            if( $errTrgt.length == 0 ){
                $errTrgt = $this.parent().closest('.err-target-wrapper').find('.err-target') || "";
                
                if( $errTrgt.length == 0 ){
                   $errTrgt = $($this.attr('data-err-target')) || "";   
                }
            }
            
            
            
            if( lblText == '' ) {
                lblText = $this.parent().closest('.form-group').find('label:first').text().toLowerCase().replace('*', '') || "";
            }    

            if( lblText != '' ) {
                if( type == 'select' || type == 'radio' ) {
                   msg += 'choose '
                }else if( type == 'checkbox' ){
                   msg += 'check ' 
                }else {
                   msg += 'enter ';
                }   

                msg += 'the '+lblText;
            }else {
                msg = 'This field is required!';
            }

            $errEle.addClass('err-ele');
            
            if( $errTrgt != '' && $this.is(':hidden') ) {
                $errTrgt.trigger('click');
            }
            return false;
       }

    });

    if( err > 0 ) {
        if( isDialog ) {
            msgBox(msg);
        }else {
            var winW    = $(window).outerWidth()
            ,   stle    = 'color: #fff; position: absolute; text-align: center; background: #f00; padding: 5px 35px; z-index: 99; min-width: 193px; '; // margin-left: 150px;

            if( type == 'checkbox' || type == 'radio' ) {
                stle += 'width: 300px;';
            }else {
                stle += 'width: '+ $errEle.outerWidth() +'px;';
            }

            if( winW < 570 || ( winW > 990 && winW < 1260 ) ) {
                stle += ' left: '+($errEle.offset().left-40)+'px; ';
            }

            if( $errEle.parent().closest('.modal').length > 0 ) {
                msg = '<span class="err" style="'+ stle +'">'+ msg +'</span>';
                $errEle.parent().closest('.form-group').prepend(msg);
            }else {
                // Normal
                stle += 'margin-top: -28px;';
                msg = '<span class="err" style="'+ stle +'">'+ msg +'</span>';
                $errEle.before(msg);
            }
        }    
        
        $sbmtBtn.attr('disabled', 'disabled');
        $('html, body').animate({
            scrollTop: ($errEle.offset().top-60)
        }, 1000);
        return false;

    }else {
        // Submit
        msgBox();
        $sbmtBtn.removeAttr('disabled');
        return true;
    }


    return false;
}

/*function autoValidate($thisWrap) {
    
    var err     = 0
    ,   msg     = ''
    ,   $form   = (typeof $thisWrap != 'undefined' ? $thisWrap : $('form'))
    ,   $sbmtBtn= $errEle = $form.find('[type="submit"]')
    ,   type  = '';

    $form.find('.err').slideUp('slow', function(){ $(this).remove() });
    $('.err-ele').removeClass('err-ele');

    $form.find('.req').each(function(){
        
        if( typeof $thisWrap == 'undefined' && $(this).hasClass('ignore') ) {
            // Skip for Modal "req" class..
            return true;
        }
        
        var $this= $(this)
        ,   lblText = $this.attr('data-err-msg') || "";
        
        type = $this.attr('type') || "";
        
        if( type == 'checkbox' || type == 'radio' ) {
            var name = $this.attr('name');
            $errEle = $this.parent().closest('.form-group').find('> div:first');
            
            if( $('[name="'+ name +'"]:checked').length == 0 ) {
                ++err;
                $this = $('[name="'+ name +'"]:first');
                window.setTimeout(function(){
                    clearErrors();
                }, 2500);
            }
            
        }else{
            type = $(this).prop('tagName').toLowerCase();
            $errEle = $this;
            
            if( $this.val() == '' ){
                ++err;
            }else if($this.hasClass('email') && !validateEmail( $this.val() )) {
                ++err;
                lblText = 'valid email address!';
            }
        }
        
       if( err > 0 ) {
            msg  = 'Please ';
            
            var $errTrgt = $this.parent().closest('.err-target') || "";
            if( $errTrgt.length == 0 ){
                $errTrgt = $this.parent().closest('.err-target-wrapper').find('.err-target') || "";
                
                if( $errTrgt.length == 0 ){
                   $errTrgt = $($this.attr('data-err-target')) || "";   
                }
            }
            
            
            
            if( lblText == '' ) {
                lblText = $this.parent().closest('.form-group').find('label:first').text().toLowerCase().replace('*', '') || "";
            }    

            if( lblText != '' ) {
                if( type == 'select' || type == 'radio' ) {
                   msg += 'choose '
                }else if( type == 'checkbox' ){
                   msg += 'check ' 
                }else {
                   msg += 'enter ';
                }   

                msg += 'the '+lblText;
            }else {
                msg = 'This field is required!';
            }

            $errEle.addClass('err-ele');
            
            if( $errTrgt != '' && $this.is(':hidden') ) {
                $errTrgt.trigger('click');
            }
            return false;
       }

    });



    if( err > 0 ) {
        var winW    = $(window).outerWidth()
        ,   stle    = 'color: #fff; position: absolute; text-align: center; background: #f00; padding: 5px 35px; z-index: 99; min-width: 193px; '; // margin-left: 150px;
        
        if( type == 'checkbox' || type == 'radio' ) {
            stle += 'width: 300px;';
        }else {
            stle += 'width: '+ $errEle.outerWidth() +'px;';
        }
        
        if( winW < 570 || ( winW > 990 && winW < 1260 ) ) {
            stle += ' left: '+($errEle.offset().left-40)+'px; ';
        }
        
        if( $errEle.parent().closest('.modal').length > 0 ) {
            msg = '<span class="err" style="'+ stle +'">'+ msg +'</span>';
            $errEle.parent().closest('.form-group').prepend(msg);
        }else {
            // Normal
            stle += 'margin-top: -28px;';
            msg = '<span class="err" style="'+ stle +'">'+ msg +'</span>';
            $errEle.before(msg);
        }
        
        $sbmtBtn.attr('disabled', 'disabled');
        $('html, body').animate({
            scrollTop: ($errEle.offset().top-60)
        }, 1000);
        return false;

    }else {
        // Submit
        $sbmtBtn.removeAttr('disabled');
        return true;
    }


    return false;
}*/

function check_controller_name() {
    var controller_arr = controller.split('_');
    if( controller_arr.shift() == 'billing') {
       return true;
    } else
        return false;
}
    

function clearErrors($this) {
    if( typeof $this == 'undefined' ) {
        $this = $('form > *:first');
    }
    var $form = $this.parent().closest('form');
    $(this).removeClass('err-ele');
    $form.find('[type="submit"], .sbmt-btn').removeAttr('disabled');
       
    $form.find('.err').fadeOut('slow', function(){
        $(this).remove();
    })
}

function adjNotify() {
    var  top     = 0
    ,   zIndx    = 9000;   
    
    //if( $('#notify .notify-box').length > 1 ) {
        $('#notify .notify-box').each(function(){
            $(this).css({bottom: top+'px', 'z-index' : ++zIndx });
            top += ($(this).height()+41);
        });

        //$(this).css({bottom: (top+$(this).height())+'px'});
    //}
    
}

function notify(msg, delay, type, name) {
    var delay   = typeof delay == 'undefined' || delay == '' ? 5000 : delay
    ,   type    = typeof type == 'undefined' || type == '' ? 'err' : type
    ,   fa      = type == 'success' ? 'fa-check' : ( type == 'info' ? 'fa-info' : 'fa-exclamation-triangle' ) 
    ,   name    = 'notify-'+(typeof name != undefined ? name : 'blck')
    ,   html    = '';
    
    if( $('.notify-box.'+name).length > 0 ) {
        // Already Exists
        $('.'+name).removeClass('err warning success info').addClass(type);
        $('.'+name+' .status .fa').removeAttr('class').attr('class', 'fa '+fa);
        $('.'+name+' .cntnt').html(msg);
        
    }else {    
        if( $('#notify').length == 0 ) {
            $('body').prepend( '<div id="notify"></div>' );
        };
        
        var idd = name+'-'+$('#notify .notify-box').length;
        html += '<div class="notify-box '+ name +' '+ type +'" id="'+ idd +'">';
        html +=     '<div class="status"><i class="fa '+ fa +'"></i></div>';
        html +=     '<div class="cntnt">'+ msg +'</div>';
        html +=     '<i class="fa fa-times-circle clse-btn"></i>';
        html += '</div>';

        $('#notify').prepend(html);
        var $box = $('#notify .notify-box:first');

        $box.slideDown('slow', function(){
            adjNotify();
            if( delay > 1 ) {
                window.setTimeout(function(){
                    $box.find('.clse-btn').trigger('click');
                }, delay);
            }
        });
    }
    
    
}

var msgTimer = '';
function msgBox(msg, delay, type, blink ) {
    window.clearTimeout(msgTimer);

    var msg     = typeof msg != 'undefined' ?  msg : ''
    ,   delay   = ( msg == '' ? 0 : ( typeof delay != 'undefined' && delay != '' ? delay : 5000 ) )
    ,   type    = typeof type != 'undefined' ? type : 'err'
    ,   blink   = typeof blink != 'undefined' || blink ? true : false;

    if( msg != '' ) {
        if( $('.msg-box').length == 0 ) {
                $('body').prepend( '<div class="msg-box"></div>' );
        };

        if( type == 'success' ) {
            msg = '<i class="fa fa-check status"></i> Success: '+msg;
        }else if( type == 'info' ) {
            msg = '<i class="fa fa-info status"></i> Info: '+msg;
        }else if( type == 'warning' ) {
            msg = '<i class="fa fa-exclamation-triangle status"></i> Warning: '+msg;    
        }else {
            msg = '<i class="fa fa-exclamation-triangle status"></i> Error: '+msg;
        }

        msg = '<div>'+msg+'<i class="fa fa-times-circle clse-btn"></i></div>'; 

        $('.msg-box').html(msg).removeClass('err success info warning').addClass(type).slideDown('slow', function(){
            if( type == 'err' || blink ) {
                var blinkInter = ''
                ,   i = 0
                ,   speed = 200;

                blinkInter = window.setInterval(function(){

                    if(i >= 3) {
                        window.clearInterval(blinkInter);
                    }
                    $('.msg-box > div').fadeOut(speed/2, function(){
                        $(this).fadeIn(speed);
                        ++i;
                    })

                }, speed);
            }
        });
    }

    if( delay != -1 ) {

        msgTimer = window.setTimeout(function(){
            /*if( !$('.msg-box').hasClass('ignore') ) {
                $('.msg-box').removeClass('ignore');
                $('.msg-box').slideUp(500, function(){
                    $(this).html('').removeClass('err success info warning');
                });
            };*/
            
            /*if( $('.msg-box > div').length > 0 ) {
                // Multiple 
                $('.msg-box > div').each(function(){
                    var dely = parseInt( $(this).attr('data-delay') ) || -1;
                    if( dely != -1 ) {
                        $(this).slideUp(500, function(){$(this).remove();})
                    }
                });
                
            }else {*/
                $('.msg-box').slideUp(500, function(){
                    $(this).html('').removeClass('err success info warning');
                });
            /*}*/
            
        }, delay);
    }
}

function virtualKeyboard(isHide) {
    var value   = $('.input-tamil.active').val() || "" 
    ,   isShow  = typeof isHide == 'undefined'  ? true : false
    ,   $virtualKeyboard = document.getElementsByClassName('virtual-keyboard')[0] || "";

    if( $virtualKeyboard == '' ){ 

        /*var a = [
            // Row 1
            [
                '0B83',
                '0BA3',
                '0B92',
                '0B89',
                '0B8E', 
                '0BC6',
                '0BC7',
                '0B85',
                '0B87',
                '0B99',
                '0BB4,0BC2', //looou
                '0BAE,0BC2',
                '0BCD'
            ],

            // Row 2
            [
                '0BA3,0BC1',
                '0BB1',
                '0BA8',
                '0B9A',
                '0BB5',
                '0BB2',
                '0BB0',
                '0BC8', //
                '0B9F,0BBF',
                '0BBF', //
                '_]',
                //''
            ],

            // Row 3
            [
                '0BAF',
                '0BB3',
                '0BA9',
                '0B95',
                '0BAA',
                '0BBE', //
                '0BA4',
                '0BAE',
                '0B9F',
                '_[',
            ],

            // Row 4
            [
                '0BB3,0BC2',
                '0BB8',
                '_;',
                '0BB7',
                '0B9C',
                '0BC1',
                '0BC2',
                '0BEF', //(Doubt)
                '0BB0,0BC2',
                '0BB6,0BCD,0BB0,0BC0',
            ],

            // Row 5
            [
                '0BB9',
                '0BB1,0BC1',
                '0BA8,0BC1',
                '0B9A,0BC1',
                '0B95,0BC2',
                '0BB2,0BC1',
                '0BB0,0BC1',
                '0B90',
                '0B9F,0BC0',
                '0BC0',
                '_{',
                '_}',
            ],

            // Row 6
            [
                '0BB1,0BBE',
                '0BB3,0BC1',
                '0BA9,0BC1',
                '0B95,0BC1',
                '0BB4,0BC1',
                '0BB4',
                '0BA4,0BC1',
                '0BAE,0BC1',
                '0B9F,0BC1',
                '_@',
                '0B9E',
            ],

            // Row 7
            [
                '0BA3,0BC1',
                '0B93',
                '0B8A',
                '0B8F',
                '0BA9,0BC1',
                '0B9A,0BC2',
                '0B86',
                '0B88',
                '0B9F,0BC2',
            ],
        ];*/


        var a = [
            // Row 1
            [
                '`',
                'z',
                'x',
                'c',
                'v', 
                'b',
                'n',
                'm',
                ',',
                '\'',
                '=', //looou
                '\\',

            ],

            // Row 2
            [
                'q',
                'w',
                'e',
                'r',
                't',
                'y',
                'u',
                'i', //
                'o',
                'p', //
                '[',
                ']'
            ],

            // Row 3
            [
                'a',
                's',
                'd',
                'f',
                'g',
                'h', //
                'j',
                'k',
                'l',
                ';',
            ],

            // Row 4
            [
                '~',
                '!',
                '@',
                '#',
                '$',
                '%',
                '^',
                '&', 
                '+',
                '|',
            ],

            // Row 5
            [
                'Q',
                'W',
                'E',
                'R',
                'T',
                'Y',
                'U',
                'I',
                'O',
                'P',
                '{',
                '}',
            ],

            // Row 6
            [
                'A',
                'S',
                'D',
                'F',
                'G',
                'H',
                'J',
                'K',
                'L',
                ':',
                '&quot;',
            ],

            // Row 7
            [
                'Z',
                'X',
                'C',
                'V',
                'B',
                'N',
                'M',
                '<',
                '?',
            ],
        ];    
        
        var html  = '<div class="wrapper">';
            html +=     '<div class="inpt" style="border-color: '+ keybrdClr +'; box-shadow: 0px 1px 3px '+ keybrdClr +';">';
            html +=         '<input type="text" class="virtual-keybrd-inp" autofocus style="font-family: amudham;" value="">';
            html +=         '<div class="ctrls">';
            html +=             '<button class="btn btn-primary ok-btn" id="ok">Ok</button>';
            html +=             '<button class="btn bksp-btn">Bksp</button>';
            html +=             '<button class="btn clr-btn">Clear</button>';
            html +=             '<span class="mre-btn">More</span>';
            html +=             '<i class="fa fa-times clse-btn" style="background: '+ keybrdClr +'; box-shadow: 3px 3px 9px '+ keybrdClr +';"></i>';
            html +=         '</div>';
            html +=     '</div>';
            html +=     '<div class="layout">';

        Object.keys(a).map(function(i){
            html += '<div class="rw">';
           Object.keys(a[i]).map(function(j){
               var hex = a[i][j];

                //if( hex[0] == '_' ) {
                    // Keyboard key
                  //  var hex = hex.substring(1);
                   // alert(hex);

                    html += '<div class="cell" data-val="'+hex+'" style="background: '+ keybrdClr +'"><input type="text" readonly value="'+hex+'" style="-10px 0px 0px -15px; font-family: amudham; border: none; cursor: pointer; font-weight: bolder; font-size: 30px; width: 35px; text-align: center; background: '+ keybrdClr +'; color: #fff;"></div>';

                /*}else {    
                    if( hex.indexOf(',') >= 0 ) {
                        var s = hex.split(',');
                        hex = '&#x'+s[0]+'&#x'+s[1];
                    }else {
                        hex = '&#x'+hex;
                    }

                    html += '<div class="cell" data-val="'+hex+'">'+hex+'</div>';
                }*/



            }); 
            html += '</div>';
        });

        var more = [
            [
                '1',
                '2',
                '3',
                '4',
                '5',
                '6',
                '7',
                '8',
                '9',
                '0'
            ],
            [
                '0BD0',
                '0BF3',
                '0BF4',
                '0BE8',
                '0BE9',
                '0BEA',
                '0BEC',
                '0BF5',
            ],
            
            
        ];

        var moreHalf = Math.floor(more.length/2);
        Object.keys(more).map(function(i){
            html +=     '<div class="rw">';
            Object.keys(more[i]).map(function(j){
                var hex = i == 1 ? '&#x'+ more[i][j] : more[i][j];
                html += '<div class="cell more" data-val="'+ hex +'" style="background: '+ keybrdClr +'">'+ hex +'</div>';
                j = parseInt(j);

                if( i == 1 && j == 3 ) {
                    html += '<div class="cell spce-btn" style="background: '+ keybrdClr +'">&nbsp;</div>';
                }

            });                    

            html +=     '</div>';
        });    
        html += '</div>';

        var $body = document.getElementsByTagName('body')[0]
        ,   $ele  = document.createElement('div');

        $ele.className = 'virtual-keyboard';
        $ele.style     = 'height: '+$(window).height()+'px;';// line-height: '+($(window).height()/10)+'px'; 

        $body.appendChild($ele).innerHTML = html;
    }

    if( !isShow ){
        // Aleady there..
        $('.virtual-keyboard').fadeOut('slow', function(){
                  $(this).find('.wrapper .inpt input[type="text"]').val('');
        });

    }else {
        var $inp = $('.virtual-keyboard .wrapper .inpt input[type="text"]');
        $inp.val(value)
        $('.virtual-keyboard').fadeIn('slow', function(){
            $inp.focus();
        });
    }


}

function vitualKeyboardFns() {
    $(document).on('click', '.virtual-keyboard .mre-btn', function(){
        var $this   = $(this)
        ,   $parent = $this.parent().closest('.virtual-keyboard');
        if( $this.hasClass('active') ) {

            $parent.find('.more').fadeOut('slow');/*each(function(i){
                $(this).fadeOut((i*120), function(){
                    //$(this).css({'display':'inline-block'});
                })
            });*/

            $this.text('More');

        }else {

            $parent.find('.more').each(function(i){
                $(this).fadeIn((i*250), function(){
                    $(this).css({'display':'inline-block'});
                })
            });
            $this.text('Less');

        }

        $this.toggleClass('active');

    });

    $(document).on('click focus', '.input-tamil', function(){
        $('.input-tamil').removeClass('active').css({'font-family' : 'amudham'});
        if( !$(this).attr('readonly') && !$(this).attr('disabled') ) {
            $(this).addClass('active');
            virtualKeyboard();
        }
    });
    
    $(document).on('click', '.virtual-keyboard .inpt .clse-btn', function(){
        virtualKeyboard(false);
    });

    $(document).on('click', '.virtual-keyboard .inpt .ok-btn', function(){
        var $parent = $(this).parent().closest('.virtual-keyboard')
        ,   $inp    = $parent.find('.inpt input[type="text"]')
        ,   val     = $inp.val();


        /*var $actInp = $('.input-tamil.active')
        ,   name = $actInp.attr('name');
        
        if( val.indexOf('"') > 0 ) {
            
            name = name.replace('tam-', '');
            $actInp.attr('name', 'tam-'+name).val(val);
            
            val = val.replace('"', "&quot;");
            $('[name="'+name+'"]').remove();
            //alert(val);
            $actInp.after('<input type="hidden" name="'+ name +'" value="'+ val +'">');
        }else{
            if( name.indexOf('tam-') == 0 ){
                name = name.replace('tam-', '');
                $('[name="'+name+'"]').remove();
                $actInp.attr('name', name);
            }
            
            $actInp.val(val);
        }*/


        $('.input-tamil.active').val(val);
        virtualKeyboard(false);
    });

    $(document).on('click', '.virtual-keyboard .inpt .bksp-btn', function(){
        var $parent = $(this).parent().closest('.virtual-keyboard')
        ,   $inp    = $parent.find('.inpt input[type="text"]');
        //,   val     = $inp.val();
        
        var inpBx = document.getElementsByClassName('virtual-keybrd-inp')[0]
        ,   pos   = inpBx.selectionStart
        ,   value = inpBx.value;
        
        inpBx.value = value.substring(0, pos-1) + value.substring( pos, value.length );
        $inp.focus();
        inpBx.setSelectionRange( pos+1, pos-1 );
        
        //$inp.val(val.substring(0, val.length-1)).focus();
    });

    $(document).on('click', '.virtual-keyboard .inpt .clr-btn', function(){
        var $parent = $(this).parent().closest('.virtual-keyboard')
        ,   $inp    = $parent.find('.inpt input[type="text"]');

        $inp.val('').focus();
    });

    $(document).on('click', '.virtual-keyboard .rw .cell', function(){
        var $parent = $(this).parent().closest('.virtual-keyboard')
        ,   $inp    = $parent.find('.inpt input[type="text"]')
        ,   val     = ' ';

        if( !$(this).hasClass('spce-btn') ) {
            //if( $(this).find('input').length > 0 ) {
                 val = $(this).attr('data-val');
            /*}else {
                val = $(this).text();//.attr('data-val');
            }*/    
        }

        var inpBx = document.getElementsByClassName('virtual-keybrd-inp')[0]
        ,   pos   = inpBx.selectionStart
        ,   value = inpBx.value;
        
        inpBx.value = value.substring(0, pos) + val + value.substring( inpBx.selectionEnd, value.length );
        $inp.focus();
        inpBx.setSelectionRange( pos+1, pos+1 );
        
        //$inp.val($inp.val()+''+val).focus();
    })
}

function printRec() {
    //alert(pStatus);
    if( pStatus == 'SERVER_DOWN') {
        // Running on Main Server
        window.setTimeout(function(){
            notify("Reminder: Dear Admin, Please check out any of the record need to import from an alternative server.. <br /><a href='"+ baseURL +"general_settings/' class='btn'>Checkout</a>", '', 'info');
        }, 1000);
        
    }else if( pStatus == '0' || pStatus == 'NO' ) {
        // Printing is disabled
        window.setTimeout(function(){
            notify("Printing is disabled");
        }, 1000);
        
    }else if( pStatus == 'NOT' ) {
        // Printing status is not available
        window.setTimeout(function(){
            notify("Printer status is not available", '', 'warning');
        }, 1000);
        
    }else if( pStatus != '' && typeof pStatus != 'undefined' ) {
        if(pStatus == 'N') {
            notify("Printing is disabled", '', 'warning');
        }else {
            var isArchanai = $('#main-content.archanai').length > 0 ? true : false
            ,   s   = pStatus.split('_');
            
            if( (isArchanai && s[1] == "0") || ( !isArchanai && s[2] == "0" ) ) {
                notify("Printer is currently not available!", 10000);
            }else {
                notify("Printing is in progress ...", '', 'info');
            }
        }
        
    }
    
}


/*var page = 0;
function printRec(path, win) {
    
    printPath = typeof path != 'undefined' ? path : printPath;
    //alert('Rec Page: '+page);
    
    if( printPath != '' && typeof printPath != 'undefined' ) {
        // Print
        var s   = printPath.split('`') // || new Array(printPath, 1)
        ,   path = s[0]
        ,   pages   = s[1];
        
        page = typeof page == 'undefined' || page > pages ? '1' : (++page);
       
        var url = base_url + path + '-' + page + '.html'
        ,   msg = 'Printing is in progress ...'+( pages > 1 ? '(<span id="print-sno">'+ (page-1) +'</span>/ '+ pages +')' : '');
        
        
        /*if( $('.msg-box').length > 0 ) {
            $('.msg-box > div:last').after('<div style="padding-left: 55px;">'+msg+'</div>');
        }else {
            msgBox(msg, -1, 'info');
        }*/
        
        // msgBox(msg, -1, 'info');
        
        //console.log(url+' Page: '+page+' Pages: '+pages);
      /*  if( pages > 0 && page <= pages ) {
            /** Print **/
            //console.log(typeof win);
        /*    if( typeof win == 'undefined' ) {
                win = window.open( url, '_blank', 'titlebar=no, menubar=no, toolbar=no, location=no, scrollbars=no, status=no, resizable=no' );
                //win.moveBy(screen.width, screen.height); //  --kiosk --kiosk-printing  http://192.168.1.164/thiruapp/
                //win.moveBy(400, 400);
            }else {
                win.location.href = url;
            }

            //win.print();
            
            /*window.setTimeout(function(){
                console.log('Next');
                printRec(printPath, win, page);
            }, 0);*/

            
             /*var afterPrint = function() {
                var d = new Date();
                console.log('Printed!'+(d.getHours()+':'+d.getMinutes()+':'+d.getSeconds()+':'+d.getMilliseconds()));

                window.setTimeout(function(){
                    console.log('Next');
                    printRec(printPath, window, page);
                }, 2000);


            }
            */
        
        
        /*}else if(page > pages) {
            // All are printed.
            
            // Remove print Tab window.
            $.post(base_url + 'billing_common/ajax/', {act: 'print', 'file_path' : printPath }, function(){});
            //msgBox('Printing is completed', '', 'success');
            win.close();
        }
        
        
        
        /*if( $('#print-dialog').length == 0 ) {
            $('body').append('<iframe id="print-dialog"></iframe>');
            
            var win = window.open( '', '_blank', 'titlebar=no, menubar=no, toolbar=no, location=no, scrollbars=no, status=no, resizable=no' );
            //win.moveBy(screen.width, screen.height);
        }
        
        $('#print-dialog').attr('src', printPath);
        
        $('#print-dialog .page').each(function(p){
            
            var $page = $('#print-dialog .page:eq('+ p +')');
            
            
        });*/
        
        
        
        /*#window.setTimeout(function(){
            // Remove print Tab window.
            $.post(base_url + 'billing_common/ajax/', {act: 'print', 'file_path' : printPath }, function(){});
            msgBox('Printing is completed', '', 'success');
            win.close();
        }, 4300);*/
        
    /*}
}*/


function footerFns() {
    if( $('a.list-btn').length > 0 ) {
        var href = $('a.list-btn').attr('href')
        ,   isAdd= window.location.href.indexOf('/add') != -1 ? false : true;


    }
    
    function getTwoDigits(value) {
        return value < 10 ? '0'+value : value;
    }

    function getMonthNum(mon) {
        mon = mon.length > 3 ? mon.substring(0, 3) : mon;

        switch(mon.toLowerCase()) {
            case 'jan' : return '1'; break;
            case 'feb' : return '2'; break;
            case 'mar' : return '3'; break;
            case 'apr' : return '4'; break;
            case 'may' : return '5'; break;

            case 'jun' : return '6'; break;
            case 'jul' : return '7'; break;
            case 'aug' : return '8'; break;
            case 'sep' : return '9'; break;
            case 'oct' : return '10'; break;    
            case 'nov' : return '11'; break;    
            case 'dec' : return '12'; break;    
        }
    }

    if( $('.time-picker').length > 0 ) {
        $('.time-picker').bootstrapMaterialDatePicker({ date: false, format: 'HH:mm', shortTime: true, cancelText: 'Go Back'});
    }
    
    if( $('.date-picker').length > 0 ) {
        $('.date-picker').bootstrapMaterialDatePicker({ time: false, format: 'DD-MM-YYYY'}).on('dateSelected', function(e){
            var $this = $(this)
            ,   name  = $this.attr('name');  
            if( $this.hasClass('multiple')){
                var parentId = 'multiple-'+(name.replace('_', '-') || $('.date-preview').length);
                if( $this.parent().find('.date-preview').length == 0 ) {
                    $this.after('<div class="date-preview fixed" id="'+parentId+'"></div>');
                }

                var $preview = $this.parent().find('.date-preview')
                ,   $ds = $('.dtp-select-day.selected')
                ,   dd = $('.dtp-picker-calendar .dtp-picker-month').html()
                ,   s   = dd.split(' ')
                ,   d = getTwoDigits(parseInt($ds.html()))
                ,   m = getTwoDigits(getMonthNum( s[0] ) )//$('.dtp-actual-month.p80:last').html() ))
                ,   y = parseInt( s[1] ) //$('.dtp-actual-year.p80:last').html())
                ,   str = d+'-'+m+'-'+y
                ,   id = parentId+'-'+y+''+m+''+d;

                $preview.addClass('fixed');
                if( $ds.hasClass('active') ) {
                    $ds.removeClass('active '+id);
                    $('#'+id).fadeOut('slow', function(){
                        $(this).remove();
                    })

                }else {
                    $ds.addClass('active '+id);
                    if( $('#'+id).length == 0 ) {
                        $preview.append('<div class="option tmp" id="'+id+'"><i class="fa fa-times rm-btn"></i> '+str+'<input type="hidden" name="'+name+'[]" value="'+str+'"></div>');
                    }
                }
            }else {
                $('.dtp-btn-ok').trigger('click');
            
            }

        }).on('change', function(e, date){

            var $this   = $(this)
            ,   str     = ''
            ,   $preview = $this.parent().find('.date-preview');

            if( $this.hasClass('multiple')){

                $preview.find('.option.tmp').removeClass('tmp');
                $preview.removeClass('fixed');
                
                orderDates($this);
            }

            if( $('#kattalai').length > 0 ) {
                setDay();

            }

            $('.dtp-select-day').removeClass('selected');

        });
        
       
    }

    function orderDates($this) {
        var $preview = $this.parent().find('.date-preview');

        var k, i, len, str = ''; 
        var dates = [], keys = [];

        $preview.find('.option').each(function(){
            var val = $(this).find('input').val() || "";
            if( val != '' ) {
                var s = val.split('-')
                ,   key = s[2]+''+s[1]+''+s[0];

                dates.push({key : key, val: val});
            }
        })

        var key = 'key';
        keys = dates.sort(function(a, b){
            var x = a[key]; 
            var y = b[key];

            return x < y ? -1 : ( x > y ? 1 : 0 );
        })

        len = keys.length;

        for(i = 0; i<len; i++) {
            str += keys[i]['val']+',';
        }

        str = str.substring(0, str.length-1);
        $this.val(str);

    }

    $('.dtp-btn-cancel, .dtp-close, .dtp').on('click', function(){
        $('.date-preview .option.tmp').remove();
        $('.date-preview').removeClass('fixed');
    })

    /*$('.dtp-select-year-after, .dtp-select-year-before, .dtp-select-month-after, .dtp-select-month-before').on('click', function(){
        if( $(this).hasClass('multiple')){


        }    

    });*/

    $(document).on('click', '.date-preview .rm-btn', function(){
        var $parent = $(this).parent().closest('.option')
        ,   id      = $parent.attr('id');    
        $parent.fadeOut('slow', function(){
            $('.'+id).removeClass('active '+id);
            $(this).remove();
            orderDates($(this));

            if( $('#kattalai').length > 0 ) {
                setDay();
            }
        })
    })
}

/*
function fillRecSett(isItm) {
        var attr = '';
        
         
        if( isItm ) {
            // Fill Items Details
            attr = $('[name="rs_itm"] option:selected').attr('data-attr') || "";
            
            if( attr != '' ) {
                
                var s = attr.split('`');
                
                $('[name="rs_god_name"]').val(s[0]);
                $('[name="rs_receipt"]').val(s[1]);
                
                $('[name="rs_is_enable"]').iCheck(s[2] == '1' ? 'check' : 'uncheck');
                $('[name="rs_is_inventory"]').iCheck(s[3] == '1' ? 'check' : 'uncheck');
                $('[name="rs_order"]').val(s[4]);
                
            }
            
            
            
        }else{
            // Fill Category Details
            attr = $('[name="rs_cat"] option:selected').attr('data-attr') || "";
            
            if( attr != '' ) {
                
                var s = attr.split('`');
                
                $('[name="rs_grouping"]').val(s[0]);//iCheck(s[0] == '1' ? 'check' : 'uncheck');
                //$('[name="rs_grouping"]').iCheck('update');
                //$('[name="rs_grouping"] .icheckbox').addClass('icheckbox_minimal');
                
                
                $('[name="rs_is_sepr"]').iCheck(s[1] == '1' ? 'check' : 'uncheck');
                $('[name="rs_order"]').val(s[2]);
                
            }
            
        }
        
        if( attr == '' ) {
            // No Results
            
            $('#rec-sett-dialog .ctrls, #rs-right-side').fadeOut('slow', function(){
                $('#rs-msg').html('Nothing to show in here!').fadeIn('slow');
            })
            
        }else {
            
            $('#rs-msg').fadeOut('slow', function(){
                $('#rs-right-side, #rec-sett-dialog .ctrls').fadeIn('slow');
            })
            
        }
    }
    
    function getRecSettItems(){
        var catID   = $('[name="rs_cat"]').val();
        
        // Reset Item details
        resetAll($('#itm-set-blck'));
        
        $('#rs-msg, #rec-sett-dialog .ctrls').fadeOut('slow', function(){
            $('#rs-right-side').fadeIn('slow');
        })
        
        if( catID != '' ) {
        
            var data    = {
                'act'   : 'rec-sett',
                'catID' : catID
            };


            $.post( baseURL + 'billing_common/ajax/', data, function(results){
                results = JSON.parse(results) || "";

                var html = '<option value="">-- Select Item --</option>';
                if( results != '' ) {
                    Object.keys(results).map(function(k , v){
                        var r = results[k];
                        html += '<option value="'+ r['id'] +'" data-attr="'+ r['god_name'] +'`'+ r['receipt'] +'`'+ r['is_enable_footer'] +'`'+ r['is_inventory'] +'`'+ r['order_sequence'] +'">'+ r['name'] +'</option>';

                    })

                }

                $('[name="rs_itm"]').html(html);

            });
        }
        
    }*/

// Fill Calendar
function fillCalendar(){
    $('#booking-cal-wrap table tbody').fadeOut('slow', function(){
        notify('Loading ...', -1, 'info', 'nb');
        $(this).find('.cell').removeClass('active act day nav bked');

        var d       = new Date()
        ,   tD      = d.getDate()
        ,   Y       = d.getFullYear()
        ,   M       = d.getMonth()
        ,   now     = d.getTime()
        ,   iF      = false // Is Future  
        ,   fDate   = $('#booking-cal-y').val()+'-'+$('#booking-cal-m').val()
        ,   date    = fDate+'-'+tD; //'2017-01-11';

        if( date != '' ) {
            var s   = date.split('-');
            Y   = s[0];
            M   = parseInt(s[1])-1;
            tD  = parseInt(s[2]);
        }

        d = new Date(Y, M, 1, 0, 0, 0);

        var D       = d.getDate()
        ,   Y       = d.getFullYear()
        ,   M       = d.getMonth()
        ,   day     = d.getDay()
        ,   sD      = 7-(7-day);

        if( sD > 0 ) {
            // Include Prev. Month Days
            d.setDate(D-sD);
        }

        var data = {
            'act'   : 'booked',
            'date'  : fDate,
            'tbl'   : $('#booking-ctrlr').val() || "",
            'cntrl' : $('#booking-ctrlr').attr('data-load') == 'yes' ? controller : '',

        };
        $.post( baseURL + 'billing_common/ajax/', data, function(res){
            res = JSON.parse(res) || "";

            $('#booking-cal-wrap table tbody .cell').each(function(i){
                D   = d.getDate();
                iF  = d.getTime() > now ? true : false;     

                $(this).attr('data-date', d.getFullYear()+'-'+(d.getMonth()+1)+'-'+D).html(D);
                if( d.getMonth() == M ) {
                    if( d.getDate() == tD ) {
                        $(this).addClass('active');
                    }

                    var isBooked = typeof res['data'] != 'undefined' && res['data'][D] || "";
                    if( !iF || isBooked != '' ) {
                        $(this).addClass('act');
                        
                        if( isBooked != '' ) {
                            // Booking is There
                            var htm = ''
                            ,   total   = res['data'][D]['total'];

                            //if( data.tbl == '' ) {
                                // Only for, if all module
                                delete res['data'][D]['total'];

                                htm  = '<div class="bked-details">';
                                htm += '<div class="hdr"></div>';
                                for( var x in res['data'][D] ) {
                                    var module = x.replace('bill_', '').replace('_', ' ')
                                    ,   sx     =  res['data'][D][x].split('`');
                                    
                                    htm += '<div data-val="'+ sx[1] +'" data-names="'+ sx[2] +'"><span>'+ ( module.charAt(0).toUpperCase() + module.slice(1) ) +'</span><span>'+ sx[0] +'</span></div>';
                                }
                                
                                htm += '</div>';
                                
                            //}

                            $(this).addClass('bked').prepend('<div class="book-lbl">'+ total +'</div>'+htm);
                        }
                        
                    }else {
                        $(this).addClass('day');
                    }

                }else if(!iF){
                    $(this).addClass('nav');
                }

                d.setDate(D+1);
            });
            
            
            // Filter Modules
            if( $('#booking-ctrlr').attr('data-load') == 'yes' ) {
                $('#booking-ctrlr').removeAttr('data-load');
                if( res.tbls ) {
                    var html = '<option value="" style="color: #999;" >-- Module --</option>';
                    
                    Object.keys(res.tbls).map(function(tblName, v){
                        var module = tblName.replace('bill_', '').replace('_', ' ');
                        //html += '<option value="'+ tblName +'">'+ (module.charAt(0).toUpperCase()+ module.slice(1)) +'</option>';
                        var mName = (module.charAt(0).toUpperCase()+ module.slice(1));
                        if(module == 'festival function') {
                            mName = 'Panguni Uthiram'; 
                        }
                       
                        html += '<option value="'+ tblName +'">'+ (mName) +'</option>';
                    });
                    $('#booking-ctrlr').fadeIn().html(html);
                    
                    if( res.tbl ) {
                        $('#booking-ctrlr').val(res.tbl);
                    }
                    
                    $('#booking-ctrlr').on('change', function(){
                        fillCalendar();
                    });
                }
            }
            
            $('.notify-nb').remove();
            $('#booking-cal-wrap table tbody').fadeIn('slow', function(){
                if( $('#booking-cal-wrap table tbody .more-row .cell.act').length > 0 ){
                    $('#booking-cal-wrap').css({'overflow-y': 'scroll'});
                    $('#booking-cal-wrap table tbody .more-row').fadeIn();
                }else {
                    $('#booking-cal-wrap').css({'overflow-y': 'hidden'});
                }
            });

        });

    });
}

$(document).ready(function() {
    keybrdClr = typeof keybrdClr == 'undefined' || keybrdClr == '' ? '#1ba' : keybrdClr;
    
    $(document).on('click', '.bked-details > div', function(){
        // Rec No
        var $parent = $(this).parent().closest('.bked-details')
        ,   dataVal = $(this).attr('data-val') || "";
        $parent.find('.bked-more').remove();
        $('.bked-details > div.active').removeClass('active');
        
        if( dataVal!= '' && !$(this).hasClass('hdr') ) {
            var dataNames= $(this).attr('data-names') || ""
            ,   t       = $parent.offset().top-$(this).offset().top
            ,   html = '<div class="hdr">'+ $(this).find('span:first').text() +'</div>'
            ,   sR       = dataVal.split(',')
            ,   sN       = dataNames.split(',');
            
            $(this).addClass('active');
            
            for( var y in sR ) {
                html += '<div><span>'+ ( sN[y].length > 15 ? sN[y].slice(0, 12) + ' ...' : sN[y] ) +'</span><span>'+ sR[y] +'</span></div>';
            }
            html = '<div class="bked-more" style="margin-top: '+ (t-10) +'px !important; '+ ( y > 5 ? 'overflow-y: scroll;' : '' ) +'">' + html + '</div>';

            $parent.append(html);
            $parent.find('.bked-more').slideDown('slow');
        }
    })
    
    $(document).on('click', '#booking-cal-wrap table .cell', function(){
        var $this       = $(this)
        ,   $bkdDetails = $this.find('.bked-details');
        
        $('.bked-details').not($bkdDetails).fadeOut(400);
        //if( $('#booking-ctrlr').val() == '' && $this.hasClass('bked') ) {
            // All
        if( $this.hasClass('bked') ) {    
            $('#booking-cal-wrap table .cell.active').removeClass('active');
            $this.addClass('active');

            var d = $this.attr('data-date') || ""
            ,   s = d.split('-');

            $bkdDetails.find('.hdr:first').html(s[2]+'/'+(s[1] < 10 ? '0'+s[1] : s[1])+'/'+s[0]);
            $bkdDetails.fadeIn('slow');
        }
        
    });
    
    $(document).on('focus', '.amount', function(){
        if( parseFloat($(this).val()) == 0  ) {
            $(this).val('').attr('placeholder', '');
        }
    });
    
    if(!isNumpad) {
        if(!$('.amount.num-pad').hasClass('float_value')) {
            $('.amount.num-pad').addClass('float_value');
        }
    } else {
        $('.amount.num-pad').removeClass('float_value'); 
    }
    
    $(document).on('keydown', '.float_value', function(e) {
       e = (e) ? e : window.event;
       var charCode = (e.which) ? e.which : e.keyCode;
       if (((charCode >= 96 && charCode <= 105) || charCode == 110) // Number pad
           || ((charCode >= 48 && charCode <= 57) || charCode == 190)
           || ((charCode >= 37 && charCode <= 40) || charCode == 8 || charCode == 9 || charCode == 13 || charCode == 46 ) //  Left, right, top, bottom, Backspace, tap, enter, delete
           ) { // Conditions to check float value
           
           return true;
       }
       
       return false;
   });
   
   $(document).on('keyup', '.float_value', function(e) {
       var value = $(this).val().trim();
       if (value == '') 
           return true;
       
       var pattrn = /^\d+(\.\d{1,2})?$/;
       if (!pattrn.test(value)) {
           var amount_arr = value.split('.');
           var temp_amt_arr = new Array();
           pattrn = /^[0-9]$/;
           //var dot_index = value.indexOf('.');
           var amount = '';
           /*if (pattrn.test(amount_arr[0])) 
               amount = amount_arr[0];
           else {*/
               temp_amt_arr = amount_arr[0].split('');
               for(var i = 0; i < temp_amt_arr.length; i ++) {
                   amount += (pattrn.test(temp_amt_arr[i])) ? temp_amt_arr[i] : '';
               }
           //}
           
           var decimal = (amount_arr[1] !== undefined) ? amount_arr[1] : '';
           if (decimal.length > 0) {
               decimal = decimal.substr(0, 2);
               amount += '.';
               
                   temp_amt_arr = decimal.split('');
                   for(var i = 0; i < temp_amt_arr.length; i ++) {
                       amount += (pattrn.test(temp_amt_arr[i])) ? temp_amt_arr[i] : '';
                   }
           }
           else if (value.indexOf('.') == (value.length - 1)) {
               amount += '.';
           }
           
           /*if (decimal.length > 0) {
               $(this).val(amount);
           }*/
           $(this).val(amount);
       }
   });
    
    $('#rec-sett-dialog .ctrls .bttn.primary').on('click', function(){
        var data = {
            'act'   : 'rec-sett',
            'type'  : 'rec-sett',
            'submit': 'true',
            data : $('[name="rs_form"]').serialize(),
        };
        
        $('#rec-sett-dialog .ctrls').fadeOut('slow', function(){
            $('#rs-msg').html('<span style="letter-spacing: 5px;">Updating ...</span>').fadeIn('slow', function(){
        
                $.post( baseURL + 'billing_common/ajax/', data, function(results){

                    $('#rs-msg').html('<span style="letter-spacing: 5px; color: #1ba;">Information is updated!</span>');
                    //resetAll($('[name="rs_form"]'));
                    if( parseInt($('[name="rs_set_for"]').val()) == 0 ) {
                        
                        $('[name="rs_itm"]').val('');
                    }else {
                        $('[name="rs_cat"]').val('');
                    }
                    setTimeout(function(){
                        $('#rs-msg').fadeOut('slow', function(){
                            $('#rec-sett-dialog .ctrls').fadeIn('slow');

                        })

                    }, 3400);
                });
            });
        });
        
        return false;
        
    });
    
    $('.popup-dialg-clse-btn').on('click', function(){
                
        $(this).parent().closest('.popup-dialg').fadeOut(500, function(){
            $('.over-lay').fadeOut(300);
            $('html, body').css({'overflow' : 'auto'});
            $('body, html').animate({
                scrollTop: '0px'
            }, 1000);

        });
    })
    
    
    $(document).on('click', '.rec-sett-btn', function(){
        var $this = $(this);
        
        $('.over-lay').fadeIn('slow');
        $('#rec-sett-dialog').fadeIn('slow', function(){
            
            if( $this.attr("data-load") != "yes" ) {
                //$this.attr("data-load", "yes");
                
                var data = {
                    'act' : 'rec-sett',
                };

                $.post( baseURL + 'billing_common/ajax/', data, function(results){
                    results = JSON.parse(results) || "";
                    var html = ''; 
                   if( results != '' ) {
                       Object.keys(results).map(function(k, v){
                            html += '<tr>';
                            html +=     '<td><span>'+ results[k]['category_name'] +'</span></td>';
                            html +=     '<td style="text-align: center;"><input type="checkbox" class="form-control" style="min-width: 30px; margin: 0 auto;" value="'+ results[k]['id'] +'" name="cats['+ results[k]['id'] +']" '+ ( results[k]['is_separate'] == "1" ? 'checked' : '' ) +'></td>';
                            html += '</tr>';
                       });
                        
                        $('#rec-sett-dialog .ctrls').fadeIn('slow');
                    }else {
                        // No results
                        html += '<tr><td colspan="2"><div class="no-results">No more categories found!</div></td></tr>';
                        $('#rec-sett-dialog .ctrls').fadeOut('slow');
                    }
                    
                    $('[name="rs_form"] table tbody').html(html);
                    
                });
            }
        });
        
    });
    
    
    /*$('[name="rs_itm"]').on('change', function(){
        // Fill Item
        fillRecSett(true);
        
    });
    
    $('[name="rs_cat"]').on('change', function(){
            
        if( $('[name="rs_set_for"]:checked').val() == '1' ) {
            // Fill Category
            fillRecSett(false);
        }else {
            // Get Items
            getRecSettItems();

        }
        
        
    })
    
    $('[name="rs_set_for"]').on('ifChecked', function(){
        var value = $(this).val();
        
        if( value == '0' ) {
            // Item
            $('#cat-set-blck').slideUp('slow');
            $('#rs-itm, #itm-set-blck').slideDown('slow', function(){
                getRecSettItems();
            });
            
        }else {
            $('#cat-set-blck').slideDown('slow', function(){
                resetAll($('#cat-set-blck'));
            });
            $('#rs-itm, #itm-set-blck').slideUp('slow');
            
        } 
        
        
        //alert(val);
    })
    
    $(document).on('click', '.rec-sett-btn', function(){
        
        $('.over-lay').fadeIn('slow');
        //$('#rec-sett-dialog .wrap').html('Please wait ...');
        $('#rec-sett-dialog').fadeIn('slow', function(){
            
            if( $('[name="rs_cat"]').attr("data-load") != "yes" ) {
            
                var data = {
                    'act' : 'rec-sett',
                };

                $.post( baseURL + 'billing_common/ajax/', data, function(results){
                    results = JSON.parse(results) || "";

                    var html = '<option value="">-- Select Category --</option>';
                    if( results != '' ) {
                        Object.keys(results).map(function(k , v){
                            var r = results[k];
                            html += '<option value="'+ r['id'] +'" data-attr="'+ r['grouping'] +'`'+ r['is_separate'] +'`'+ r['category_order'] +'`'+ r['status'] +'">'+ r['category_name'] +'</option>';

                        })

                    }

                    $('[name="rs_cat"]').attr('data-load', 'yes').html(html);



                });
            }
            
        })
        
    });*/
    
    
    
    $(document).on('click', '.frm-dwnl-btn', function(){
        var url = $(this).attr('data-url') || ""
        ,   $tbl = $('#frm-dwnld-dialog > div.wrap');
        
        if( url != '' ) {
            $tbl.fadeOut('slow', function(){
                if( $('#frm-dwnld-dialog iframe').length == 0 ){
                    $('#frm-dwnld-dialog').append('<iframe src="" align="center" onload="loadFn();"></iframe>');
                }

                var $iframe = $('#frm-dwnld-dialog iframe')
                ,   $iBody  = $iframe.contents().find('body')
                ,   style = 'text-align: center; padding: 17% 0px; color: #999; letter-spacing: 3px; font-size: 24px; text-shadow: 3px 3px 3px #ccc;';

                $iBody.html('<div class="plceholder" style="'+ style+'">File is downloading ...</div>');
    
                $iframe.attr('src', url).fadeIn('slow');
                

            });
        }
        
        
        
    })
    
    $(document).on('click', '.form-dwnld-btn, #frm-dwnld-dialog .paging li',function(){
        var html = ''
        ,   $navAct = $(this);
        
        if($navAct.hasClass('active')){
            return false;
        }
        
        
        $('html, body').css({'overflow' : 'hidden'});
        if( $('#frm-dwnld-dialog').length == 0 ) {
            //html += '<div class="over-lay"></div>';
            
            html += '<div id="frm-dwnld-dialog" class="popup-dialg">';
            html +=     '<i class="fa fa-times popup-dialg-clse-btn" id="frm-dwnl-clse-btn" ></i>';
            html +=     '<div class="wrap">';
            html +=         '<div id="frm-dwnld-title" class="popup-dialg-title">Available Forms<span id="frm-total-cnt" style="margin: 0px 5px;color: #999; font-weight: bold;"></span></div>';
            
            html +=         '<table style="width: 100%;">';
            html +=             '<thead><tr>';
            
            html +=                 '<th style="text-align: center; width: 120px;">&nbsp;</th>';    
            html +=                 '<th style="width: 50%;">Name</th>';    
            html +=                 '<th style="text-align: center;">Download</th>';
            html +=                 '<th style="text-align: center;">Last Modified</th>';
            
            html +=             '</tr></thead>';
            html +=             '<tbody></tbody>';
            html +=         '</table>';
            html +=     '<div id="frm-dwnld-paging" class="paging"></div>';
            html += '</div>';
            html += '</div>';
            $('body').append( html );
            
            $('#frm-dwnl-clse-btn').on('click', function(){
                var $iframe = $('#frm-dwnld-dialog iframe');
                if( $iframe.length > 0) {
                    $iframe.fadeOut(500, function(){
                        $iframe.remove();
                        $('#frm-dwnld-dialog div.wrap').fadeIn('slow');
                    });
                }else {
                    $('#frm-dwnld-dialog').fadeOut(500, function(){
                        $('.over-lay').fadeOut(300);
                        $('html, body').css({'overflow' : 'auto'});
                        $('body, html').animate({
                            scrollTop: '0px'
                        }, 1000);

                    });
                }
            });
        }else if( $(this).parent().closest('.paging').length > 0 ) {
            // Pagination
            if( $(this).hasClass('next-arrow') ) {
                $navAct = $('#frm-dwnld-dialog .paging li.active').next();
            }else if( $(this).hasClass('prev-arrow') ) {
                $navAct = $('#frm-dwnld-dialog .paging li.active').prev();
            }
            
            $('#frm-dwnld-dialog .paging li').removeClass('active');
            $navAct.addClass('active');
            
        }
        
        var $tbody = $('#frm-dwnld-dialog tbody')
        ,   data = {
            'act'    : 'list',  
            'totalCnt': parseInt($('#frm-dwnld-dialog .paging').attr('data-total')) || "",
            'pageNo' : parseInt($('#frm-dwnld-dialog .paging li.active').attr('data-pg-no')) || ""
        };
        
        $('.over-lay').fadeIn(500);
        $('#frm-dwnld-dialog').fadeIn('slow', function(){
            $tbody.html( '<tr><td colspan="4" align="center" class="no-results">Please wait ...</td></tr>' );//.css({'min-height' : ($(window).height()-150)+'px'});
        
            $.post( baseURL + 'form_download/ajax/', data, function(returns){
                returns = JSON.parse( returns ) || "";
                $tbody.fadeOut('slow', function(){
                    
                    html = '<tr><td colspan="4" align="center" class="no-results">Sorry, No results found</td></tr>';
                    
                    var results = returns['results'] || "";
                    if( results != '' ) {

                        html = '';
                        Object.keys( results ).map(function(i, v){
                            var row = results[i];
                            html += '<tr>';
                            html +=     '<td align="center">'+ row['prev_html'] +'</td>';
                            html +=     '<td>'+ row['frm_name'] +'</td>';
                            //html +=     '<td align="center"><a href="'+ baseURL + row['file_url'] +'" target="_self">Download</a></td>';
                            html +=     '<td align="center"><span class="frm-dwnl-btn" data-url="'+ baseURL + row['file_url'] +'" target="_self">Download</span></td>';
                            html +=     '<td align="center">'+ row['updated_on'] +'</td>';

                            html += '</tr>';
                        });
                        
                    }

                    $tbody.html( html ).fadeIn('slow');
                
                }); // fadeOut
                
                var pageNos  = 5
                ,   pageNo = data.pageNo == "" ? 1 : data.pageNo;
                
                //if( $('#frm-dwnld-paging ul').length == 0 || $navAct.hasClass('nav-arr')) {
                    
                    var totalCnt = returns['extra']['totalCnt']
                    ,   perPage  = returns['extra']['perPage']
                    ,   loadedCnt=  pageNo * perPage;
                    
                    $('#frm-total-cnt').html(totalCnt > 0 ? '('+ ( loadedCnt <= totalCnt ? loadedCnt : totalCnt ) +'/'+ totalCnt +')' : '');
                    $('#frm-dwnld-dialog .paging').attr('data-total', totalCnt);
                    if( totalCnt > perPage ) {
                        
                        var pages   = Math.ceil(totalCnt/perPage)
                        ,   isMore  = pages > pageNos ? true : false
                        ,   start   = 1
                        ,   len     = pages
                        ,   html    =  '<ul>';
                        
                        if( isMore ) {
                            
                            var navHalf = Math.ceil(pageNos/2);
                            start = pageNo - navHalf;
                            start = start < pageNo ? pageNo : start;
                            
                            len = pageNo + navHalf;
                            len = len > pages ? pages : len;
                        
                        }
                         
                        if( isMore && pageNo > 1 ) {
                            html += '<li data-pg-no="'+(pageNo-1)+'" class="prev-arrow nav-arr" >&lt;</li>';
                        }

                        for( i = start; i <= len; i++ ) {
                            html += '<li data-pg-no="'+i+'" class="'+( pageNo == i ? 'active' : '' )+'" >'+ i +'</li>';

                        }

                        if( isMore && pageNo < pages ) {
                            html += '<li data-pg-no="'+(pageNo+1)+'" class="next-arrow nav-arr" >&gt;</li>';
                        }

                        html    +=      '<ul>';
                        
                        
                        $('#frm-dwnld-dialog .paging').html( html );
                    }
                    
                    
                /*}else {
                    $('#frm-dwnld-dialog .paging .next-arrow').attr('data-pg-no', pageNo+1);
                    $('#frm-dwnld-dialog .paging .prev-arrow').attr('data-pg-no', pageNo-1);
                }*/

            });
        
        });
        
        
    });
    
    $(document).on('click', '.rm-file-icn', function(){
        var $parent = $(this).parent().closest('.file-preview');
        
        if( window.confirm("Are you sure about to remove?") ) {
            /*var src = $parent.find('img').attr('src') || "";
            
            if( src != '' ) {
                var   s = src.replace('\\', '/').split('/')
                    idd = $parent.attr('id') || "";
                if( idd == '' ) {
                    idd = ++$('.file-remove').length; 
                    $parent.attr('id', 'file-remove-'+idd);
                }
                
                if( $parent.find('#hidden-file-remove-'+idd).length == 0 ) {
                    $parent.append('<input type="hidden" id="hidden-file-remove-'+idd+'" name="file_remove[]" />');
                }
            
                $('#hidden-file-remove-'+idd).val( s[s.length-1] );
            } */   
            
            $parent.find('[name="hidden_file[]"]').attr('name', 'file_remove[]');
            $parent.find('img, .rm-file-icn').remove();
        }else {
            return false;
        }
        
    });
    
    $(document).on('click', '.notify-box .clse-btn', function(){
        var $parent = $(this).parent().closest('.notify-box');
        $parent.slideUp(300, function(){$(this).remove(); adjNotify(); });
    });
    
    /* $('input[type="submit"]').on('click', function(){
        $(this).attr('disabled', 'disabled');
    }); */
    
    footerFns();
    
    $('button[type="reset"]').click(function() {
        
        resetAll($('#prasadam-dialog')); 
    });
    
    if(!check_controller_name()) {
        $('.edit_otp').addClass('no_show_otp');
        $('#confirm .modal-footer .confirm_btn_ok').addClass('no_show_otp');
    }
    
    $('#ptypes-dialog .ptype-box input').each(function() {
        var this_id = $(this).parent().attr('id');
        var this_val = $(this).val();
        if(this_id == 'ptype-box-cheque') {
            set_cheque_details($(this).parent(),this_val);
        }
    });
    
    vitualKeyboardFns();
    /*** Booked Details Search Date - Start ***/
    if( $('.bk_from_date').length > 0 ) {
        $('.bk_from_date').bootstrapMaterialDatePicker({ 
            time: false, 
            format: 'DD-MM-YYYY'
        }).on('change', function(){
            if($('.bk_to_date').val() != '') {
                $('.bk_to_date').val('');
            }
            
            $('.bk_to_date').bootstrapMaterialDatePicker('setMinDate', $('.bk_from_date').val());   
            
        }).on('dateSelected', function(e){
            $('.dtp-btn-ok').trigger('click');
        });

        $('.bk_to_date').bootstrapMaterialDatePicker({ 
            time: false, 
            format: 'DD-MM-YYYY'
        }).on('change', function(){
            
            
        }).on('dateSelected', function(e){
            if($('.bk_from_date').val() == '') {
               $('.bk_to_date').val('');
               msgBox('Please select From Date!'); 
            }else {
                $('.dtp-btn-ok:last').trigger('click');
            }
            
        });
    }
    /*** Booked Details Search Date - End ***/
    
    if( $('.av_from_date').length > 0 ) {
        $('.av_from_date').bootstrapMaterialDatePicker({ 
            time: false, 
            format: 'DD-MM-YYYY'
        }).on('change', function(){
            if($('.av_to_date').val() != '') {
                $('.av_to_date').val('');
            }
            
            $('.av_to_date').bootstrapMaterialDatePicker('setMinDate', $('.av_from_date').val());            
        });

        $('.av_to_date').bootstrapMaterialDatePicker({ 
            time: false, 
            format: 'DD-MM-YYYY'
        }).on('change', function(){
            if($('.av_from_date').val() == '') {
               $('.av_to_date').val('');
               msgBox('Please select From Date!'); 
            }  
        });
    }
    
    if( $(".colorpicker").length > 0 ) {
        //Colorpicker
        $(".colorpicker").colorpicker();
    }
    
    $('input[type="text"][onclick="set_tamil_keypad(this);"], .input-tamil, .lang-tamil').removeAttr('onclick').css({'font-family' : 'amudham'});
    
    //if( isKskBill  ) {
    if( $('section.content-header .major_txt_color').length > 0 ) {
        // Set Devottee Add Icon
        var html = '<div id="dev-icn-grp" class="top-icn-grp">' +
                        '<span class="top_rt_icon2 add-dev-btn" title="Reg. new devotee!"></span>' +
                        '<span class="top_rt_icon3 get-dev-btn" title="Search the devotee!"></span>' +
                        '<span class="rec-sett-btn" title="Receipt Settings"></span>' +
                        '<span class="form-dwnld-btn" title="Download Forms"></span>';
                        //if( controller != 'home' )  {
                            html += '<a href="'+ base_url +'"><span class="top-home-btn" title="Go to Home"></span></a>';
                            $('ol.breadcrumb li a').removeAttr('href');
                        //}
                        
        html    += '</div>';

        $('section.content-header .major_txt_color').after(html);
            
        html  = '<div id="more-tools"  style="background: '+ keybrdClr +'; '+ ( localStorage.getItem("more-tools") == "y" ? 'right: 0px;' : '' ) +'">'; 
        html +=     '<i class="fa fa-times" style="padding: 10px; font-size: 24px; background: #f33; cursor: pointer; position: absolute; right: 5px; margin-top: 48px; color: #fff; border-radius: 30px; min-width: 45px;text-align: center;"></i>';
        html +=     '<div id="more-tools-opener" '+ ( localStorage.getItem("more-tools") == "y" ? 'style="display: none;"' : '' ) +' ><div style="">Short &nbsp; Links</div></div>'; 
        html +=     '<div style="float: left; width: 88%; margin-left: -30px;">';
        html +=         '<ul style="list-style: none;">';
        if(perExpenses == 1) {
            html +=             '<a href="'+ baseURL +'expenses/add/"><li><i class="fa fa-flask"></i> Add Expense</li></a>';
        }
        html +=             '<li class="rec-sett-btn"><i class="fa fa-gear"></i> Rec. Settings</li>';
        html +=             '<li class="booking-cal-btn"><i class="fa fa-calendar"></i> Booking Calendar</li>';
        if(perFormDownload == 1) {
            html +=             '<li class="form-dwnld-btn"><i class="fa fa-download"></i> Form Downloads</li>';
        }
        html +=         '</ul>';
        html +=     '</div>';
        
        html += '</div>';
        
        $('body').prepend(html);
        
        $('#more-tools-opener').on('click', function(){
            
            $('#more-tools-opener').slideUp(100, function(){
                localStorage.setItem("more-tools", "y");
                $('#more-tools').animate({
                    right: '0px',
                }, 400);
            });
            
            
        })
        
        $('#more-tools .fa-times').on('click', function(){
            $('#more-tools').animate({
                right: '-200px',
            }, 200, function(){
                localStorage.setItem("more-tools", "n");
                $('#more-tools-opener').slideDown('slow');
                
            });
            
            
        })
        
        $('.booking-cal-btn').on('click', function(){
            var $this = $(this);
        
            $('.over-lay').fadeIn('slow');
            $('#booking-cal-dialog').fadeIn('slow', function(){
                var days  = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
                
                if( $('#booking-cal-wrap table').length == 0 ) {
                    var html  = '<table>';
                    
                        // Head
                        html += '<thead><tr>';
                        for( i = 0; i < days.length; i++ ) {
                            html += '<th><div class="cell">'+ days[i] +'</div></th>';
                        }
                        html += '</tr></thead>';
                        
                        // Body
                        html += '<tbody>';
                        for( i = 1; i <= 6; i++ ) {
                            html += '<tr '+ (i >= 6 ? 'style="display: none;" class="more-row"' : '') +'>';
                            for( j = 1; j <= 7; j++ ) {
                                html += '<td><div class="cell '+ ( j == 1 ? 'holiday' : '' ) +'">&nbsp;</div></td>';
                            }
                            html += '</tr>';
                        }
                        html += '</tbody>';
                        
                        html += '</table>';
                    $('#booking-cal-wrap').html(html);    
                    
                    
                    $('#booking-cal-y, #booking-cal-m').on('change', function(){
                        fillCalendar();
                    });
                    
                    
                    $(document).on('click', '#booking-cal-wrap table tbody .cell.nav', function(){
                        var date = $(this).attr('data-date') || "";
                        if( date != '' ) {
                            var s = date.split('-');
                            $('#booking-cal-y').val(s[0]);
                            $('#booking-cal-m').val(s[1]);
                            
                            fillCalendar();
                        }
                    });
                    
                }
                
                $('#booking-cal-m').trigger('change');
            });
            
        });
        
        
    }
    
    printRec(pStatus);
    
    $('#sbmt-cancel-btn').on('click', function(){
        $('#pay-amounts-box').slideDown('slow');
        $('#payment-btn').removeClass('dialog-btn').removeAttr('data-target');
        $('.payment-btn').removeAttr('disabled');
        
        if(method == 'add') {
            $('#ptypes-dialog .ptype-box input').val('');
            $('#cheque-box').slideUp('slow');
        }
        
        dialog($('#ptypes-dialog'), true);
    });
    
    $('#ptypes-dialog #sbmt-btn').click(function() {
        var err = 0
        ,   value = $('#ptype-box-cheque input').val();
        
        var mem_value = $('#ptype-box-membership-card input').val();
        
        $('.ptype-box').each(function() {
            if($(this).attr('id') == 'ptype-box-cheque') {
                if( value != '' ) {
                    $('#cheque-box .req').each(function(){
                        if( $(this).val() == '' ) {
                            ++err;
                        }
                    });
                    
                    if( err > 0 ) {
                        // Error
                        msgBox('Please enter Bank name or No!');
                        $('[type="submit"], .sbmt-btn').attr('disabled', 'disabled');
                        exit;
                        return false;
                    }else {
                        $('[type="submit"], .sbmt-btn').removeAttr('disabled');
                        return true;
                    }
                }
             } else if($(this).attr('id') == 'ptype-box-membership-card') {
                if( mem_value != '' ) {
                    $('#membership-card-box .req').each(function(){
                        if( $(this).val() == '' ) {
                            ++err;
                        }
                    });

                    if( err > 0 ) {
                        // Error
                        msgBox('Please enter Card No!');
                        $('[type="submit"], .sbmt-btn').attr('disabled', 'disabled');
                        exit;
                        return false;
                    }else {
                        $('[type="submit"], .sbmt-btn').removeAttr('disabled');
                        return true;
                    }
                }
            }
        });
    });
    
    $('#cheque-box input').on('keyup', function(){
        /* var hidden_edit_id = $('[name="hidden_edit_id"]').val();
        var edit_id = ((hidden_edit_id != '' || hidden_edit_id !== undefined) && $('[name="hidden_id"]').val()) ? $('[name="hidden_id"]').val() : ''; */
        var err = 0
        ,   value = $('#ptype-box-cheque input').val();
        
        if( value != '' ) {
            $('#cheque-box .req').each(function(){
                
                if( $(this).val() == '' ) {
                    ++err;
                }
            });
            //alert(err); 
                   
            if( err > 0 ) {
                // Error
                $('[type="submit"], .sbmt-btn').attr('disabled', 'disabled');
            }else {
                $('[type="submit"], .sbmt-btn').removeAttr('disabled');
            }
            
        }
    });
    
    
    $('.ptype-box').on('click', function(){
        msgBox();
        
       var $this = $(this)
       ,    id = $(this).attr('id')
       ,    s = id.split('-');
       
        if( s[2].indexOf('cheque') >= 0  ) {
           
            //$('#pay-amounts-box').slideUp('slow');//, function(){
                $('#membership-card-box').slideUp('slow');
                $('#membership-card-box input[name="card_no"]').removeClass('req ignore');
                var $date = new Date();
                $('#cheque-box input[name="chq_date"]').val( getTwoDigits($date.getDate()) + '-' + getTwoDigits(($date.getMonth()+1)) + '-' + $date.getFullYear());
                
                $('#cheque-box').slideDown('slow', function(){
                    if( !$('#ptype-box-cheque input').is(':focus') ){
                        $('#cheque-box input:first').focus();
                    }
                })
            //})
       } else if(s[2].indexOf('membership') >= 0) {
            $('#cheque-box').slideUp('slow');
            $('#pay-amounts-box').slideUp('slow');//, function(){
                $('#membership-card-box input[name="card_no"]').addClass('req ignore');
                $('#membership-card-box').slideDown('slow', function(){
                    if( !$('#ptype-box-membership-card input').is(':focus') ){
                        $('#membership-card-box input:first').focus();
                    }
                })
            //})
       
       }else {
           
           var value = $('#ptype-box-cheque input').val();
           var mem_value = $('#ptype-box-membership-card input').val();
           
           if( value != '' && !autoValidate($('#cheque-box')) ) {
                $('[type="submit"], .sbmt-btn').attr('disabled', 'disabled');
                $('#membership-card-box input[name="card_no"]').removeClass('req ignore');
                $('#cheque-box input:first').focus();
                $('#membership-card-box').slideUp('slow');
                return false;
           } else if( mem_value != '' && !autoValidate($('#membership-card-box'))) {
                $('[type="submit"], .sbmt-btn').attr('disabled', 'disabled');
                $('#membership-card-box input[name="card_no"]').addClass('req ignore');
                $('#membership-card-box input:first').focus();
                return false;
           }else {
                
                $('[type="submit"], .sbmt-btn').removeAttr('disabled');
                $('#membership-card-box').slideUp('slow');
                $('#membership-card-box input[name="card_no"]').removeClass('req ignore');
                 $('#cheque-box').slideUp('slow');//, function(){
                    $('#pay-amounts-box').slideDown('slow');
                //})
            }     
          
       }
       
       $this.find('input').trigger('keyup');
       
    });
    
    
    
    $('#membership-card-box input[name="card_no"]').on('keyup', function() {
        get_member_ship_card_details(this,1);
    });
    
    $('#membership-card-box input[name="card_no"]').on('change', function() {
        get_member_ship_card_details(this,2);
    });
    
    $('.ptype-box input').on('click', function(){
        var idd = $(this).parent().attr('id');
        var card_amount = $('#membership-card-box input[name="card_amount"]').val();
        
        var $this   = $(this)
        ,   total   = 0
        ,   payAmt  = parseFloat( $('[name="pay_amount"]').val() );
            
        $('.ptype-box input').each(function(){

            total += parseFloat( $(this).val() ) || 0;
        })
        
        if( $this.val() != '' ) {
            total -= parseFloat( $this.val() );
        }

        var value = payAmt - total;
        if( (idd == 'ptype-box-membership-card') && (parseFloat(value) >= parseFloat(card_amount)) ) {
            $this.val( (parseFloat(card_amount)).toFixed(2) ).trigger('keyup');
        } else if( value > 0 ) {
            $this.val( value.toFixed(2) ).trigger('keyup');
        }
        
    });
    
    $('#ptype-box-cheque input').on('blur', function(){
        var value = $('#ptype-box-cheque input').val();
        if( value != '' ){//&& !autoValidate($('#cheque-box')) ) {
             $('[type="submit"], .sbmt-btn').attr('disabled', 'disabled');
             $('#cheque-box input:first').focus();
             $('#cheque-box input[name="chq_bnk_name"]').addClass('req ignore');
             $('#cheque-box input[name="chq_no"]').addClass('req ignore');
        }else {
             
             $('[type="submit"], .sbmt-btn').removeAttr('disabled');
             $('#cheque-box input[name="chq_bnk_name"]').removeClass('req ignore');
             $('#cheque-box input[name="chq_no"]').removeClass('req ignore');
        }
    });
    
    $('#ptype-box-membership-card input').on('blur', function(){
        var value = $('#ptype-box-membership-card input').val();
   
        if( value != '' ){//&& !autoValidate($('#cheque-box')) ) {
             $('[type="submit"], .sbmt-btn').attr('disabled', 'disabled');
             $('#member-card-box input:first').focus();
             $('#membership-card-box input[name="card_no"]').addClass('req ignore');
        }else {
             
            $('[type="submit"], .sbmt-btn').removeAttr('disabled');
            $('#membership-card-box input[name="card_no"]').removeClass('req ignore');
        }
    });
    
    //$('.ptype-box').on('click', function(){
    $('.pay-box').on('click', function(){    
        var $parent = $(this).parent().closest('.ptype-box');
        var idd = $parent.attr('id');
        var card_amount = $('#membership-card-box input[name="card_amount"]').val();
        
        if( (idd == 'ptype-box-membership-card') && (parseFloat($('[name="pay_amount"]').val()) >= parseFloat(card_amount)) ) {
            $parent.find('input').val(parseFloat(card_amount));
            $('[type="submit"], .sbmt-btn').removeAttr('disabled');
            $('#membership-card-box input[name="card_no"]').addClass('req ignore');
            $('#cheque-box input[name="chq_bnk_name"]').removeClass('req ignore');
            $('#cheque-box input[name="chq_no"]').removeClass('req ignore');
            
        } else {
            $('.ptype-box input').val('');
            $parent.find('input').val($('[name="pay_amount"]').val());
            $('[type="submit"], .sbmt-btn').removeAttr('disabled');
            $('#membership-card-box input[name="card_no"]').removeClass('req ignore');
            $('#cheque-box input[name="chq_bnk_name"]').addClass('req ignore');
            $('#cheque-box input[name="chq_no"]').addClass('req ignore');
        }
        
        
      /*$(this).find('input').focus();  
      $('.ptype-box.active').removeClass('active');
      $(this).addClass('active');*/
      
      /*var   $img      = $('#pay-preview img')
      ,     url       = $(this).attr('data-url') || ""
      ,   defaultUrl  = $img.attr('data-default') || "";
      
      if( defaultUrl == '' ) {
          defaultUrl = $img.attr('src');
          $img.attr('data-default', defaultUrl);
      }
      
      if( url == '' ) {
          url = defaultUrl;
      }else {
          url = baseURL + url;
      }
      
      $img.attr('src', url);
      */
    });
    
    /*$('.ptype-box input').on('blur', function(){
        $(this).parent().closest('.ptype-box').removeClass('active');
        window.setTimeout(function(){
            if( $('.ptype-box.active').length == 0 ) {
                var   $img      = $('#pay-preview img')
                ,   defaultUrl  = $img.attr('data-default') || "";

                if( defaultUrl != '' ) {
                    $img.attr('src', defaultUrl);
                }
            }
        }, 300);
        
    })*/
    
    var inter = '';
    $('.ptype-box input').on('keyup', function(){
        window.clearTimeout(inter);
        var $this   = $(this);
        
        inter = window.setInterval(function(){
            window.clearTimeout(inter);
            var value   = $this.val()
            ,   $errBlck = $this.parent().closest('.modal').find('.err-blck')
            ,   total   = 0
            ,   payAmt  = parseFloat( $('[name="pay_amount"]').val() );
            
            $('.ptype-box input').each(function(){

                total += parseFloat( $(this).val() ) || 0;
            })
            
            if( total <= 0 ) {
                //msgBox('Please enter Amount!');
                $('[type="submit"]').attr('disabled', 'disabled');
            }else if( total > payAmt ) {

                total -= value;

                value = (total - (total-payAmt))-total;
                total += value;
                $this.val((value > 0 ? (parseFloat(value)).toFixed(2) : ''));

                //$('[type="submit"]').attr('disabled', 'disabled');
                $errBlck.html( 'Amount can not be exceeded than payable amount!' ).slideDown('slow');
                window.setTimeout(function(){
                    $errBlck.slideUp('slow', function(){ $(this).html('') }); 
                    $('[type="submit"]').removeAttr('disabled');
                }, 3500);
                
            }else {
                
                $errBlck.slideUp('slow', function(){ $(this).html('') });
                
                if( payAmt == total || $('#ptypes-dialog').hasClass('partial') ) {
                    $('[type="submit"]').removeAttr('disabled');
                }else {
                    $('[type="submit"]').attr('disabled', 'disabled');
                }
            }

            $('[name="paid_amount"]').val( total.toFixed(2));
        }, 400);    
        
    });
    
   /* $(document).on('click', '.pass-code-generate-btn', function(){
        var userId = $(this).attr('data-id') || "";
        
        if( userId == '' ) {
            msgBox('Sorry, Unable to identify the current user. Please refresh/logout the page and try again!');
            return false;
        }
        
       msgBox('Generating pass code, Please wait ... ', -1, 'info'); 
       var data = {
           'act'    : 'pass-code',
           'type'   : 'new',
           'id'     : userId,
       }
       $.get( base_url + 'billing_common/ajax', data, function(results){
           results = JSON.parse(results);
           
           if( results != '' ) {
               msgBox('Pass code is genereated. <br />Please note this pass code: <b>"'+results+'"</b>', -1, 'success'); 
               alert(results);
               return false;
           }else {
               msgBox('Oops, something went wrong.', -1); 
           }
           
           return false;
       });
    });*/
    
    
    $(document).on('click', '.pass-code-generate-btn', function(){
        var id = $(this).attr('data-id') || "";
        if( id == '') {
            msgBox('User ID is missing ...Try again from User Master => Edit option');
            return false;
        }
        
        var data = {
            'act'   : 'pass-code',
            'type'  : 'new',
            'id'    : id
        };
        
        $('.pass-code-generate-btn').attr('disabled', 'disabled');
        msgBox('Generating pass code, Please wait.. ', -1, 'info');
        $.post(baseURL + 'billing_common/ajax', data, function( results ) {
               results = JSON.parse(results) || "";
               $('.pass-code-generate-btn').removeAttr('disabled');
               
                if( results != '' ) {
                    msgBox('Pass code is generated. (<b>"'+ results +'"</b>)', -1, 'success');
                }else {
                    msgBox('Something is went wrong.. Please try again', -1);
                }
               
               return false;
        });       
        
        return false;
    })
    
    /*** Generate OTP Value for Edit Page ***/
    $('.edit_otp').click(function() {
        var ids = $(this).attr('data-otp-ids');
        var auto_id = $(this).closest('tr').find('.auto_id').val();
        var edit_url = $(this).attr('href');
        $('.modal-body .otp_no').val('');
        var _this = $(this);
        
        $.ajax({
            async: false,
            url: base_url + 'otp_login/get_log_otp_details',
            type: 'POST',
            data: {
                ids: ids,
                auto_id: auto_id,
                url: edit_url,
                page_type_id: 2,
                controller: controller,
            },
            dataType: "json"
        })
        .done(function(data) {
            if(data !== null && data !== '') {
                if($(_this).hasClass('no_show_otp')) {
                     window.location.href = edit_url;
                } else {
                    msgBox('Sending SMS.....','','info');
                    if(data.status == 1) {
                        $("#otp-dialog").modal({
                            show: true      
                        });
                        msgBox(data.msg, '', 'success');
                    } else if(data.status == 0) {
                        msgBox(data.msg);
                    } else {
                        $("#otp-dialog").modal({
                            show: true      
                        });
                        msgBox(data.msg,'','info');
                        
                    }
                } 
                $('.modal-body .hidden_id').val(2);
                $('#otp-dialog #sbmt-btn').attr('data-ids',ids);
            } else {
                window.location.href = edit_url;
            }
        })
        .fail(function(jqXHR, status_code, error_thrown) {
            console.log(jqXHR.responseText);
        });
        return false;
    });
    /*** Generate OTP Value for Edit Page ***/
    
    
    $('.edit_booked_data').click(function() {
        //alert('test');
        var ids = $(this).attr('data-otp-ids');
        var auto_id = $(this).closest('tr').find('.auto_id').val();
        var edit_url = $(this).attr('href');
        $('.modal-body .otp_no').val('');
        
        $.ajax({
            async: false,
            url: base_url + 'otp_login/get_log_otp_details',
            type: 'POST',
            data: {
                ids: ids,
                auto_id: auto_id,
                url: edit_url,
                page_type_id: 2
            },
            dataType: "json"
        })
        .done(function(data) {
            if(data !== null && data !== '') {
                msgBox('Sending SMS.....','','info');
                if(data.status == 1) {
                    $("#otp-dialog").modal({
                        show: true      
                    });
                    msgBox(data.msg, '', 'success');
                } else if(data.status == 0) {
                    msgBox(data.msg);
                } else {
                    $("#otp-dialog").modal({
                        show: true      
                    });
                    msgBox(data.msg,'','info');
                }
                
                $('.modal-body .hidden_id').val(2);
                $('#otp-dialog #sbmt-btn').attr('data-ids',ids);
            } else {
                window.location.href = edit_url;
            }
        })
        .fail(function(jqXHR, status_code, error_thrown) {
            console.log(jqXHR.responseText);
        });
        return false;
    });
    
    /*** Submit the OTP Value ***/
    $('#otp-dialog #sbmt-btn').click(function() {
        var otp_value = $(this).closest('div').parent().find('.modal-body .otp_no').val();
        var page_type_id = $(this).closest('div').parent().find('.modal-body .hidden_id').val();
        var ids = $('#otp-dialog #sbmt-btn').attr('data-ids');
        var return_val = true;
        if(otp_value != '') {
            $.ajax({
                async: false,
                url: base_url + 'otp_login/update_otp_status',
                type: 'POST',
                data: {
                    ids: ids,
                    otp_value: otp_value
                },
                dataType: "json"
            })
            .done(function(data) {
                if(page_type_id == 2) { // For Edit Page
                    if(data.status == 0) {
                        // Give current module otp not match
                        msgBox('Incorrect OTP!');
                        return_val = false;
                    } else if(data.status == 2) {
                        // Give Different otp 
                        
                        $('#otp-dialog .otp_btn_cancel').trigger('click');
                        $("#warning-dialog").modal({
                            show: true      
                        });
                        
                        $('#warning-dialog .warning_content').html('<b style="color:red; font-size: 14px;">Given OTP doesn\'t matched with the current module.</b> <br /><br />Correct Module: <span style="color: #0B45B3;">' + firstToUpperCase( data.controller ) + '</span><br /><br />Do you want redirect to that correct module or stay on this page?');
                        
                        $('#warning-dialog .modal-body .correct_url').attr('data-url',data.correct_url);
                        $('#warning-dialog .modal-body .correct_url').val(data.correct_id);
                    } else if(data.status == 1){
                        // Give current module otp
                        window.location.href = data.row.url;
                        return_val = true;
                    } else {
                        // Give Different otp that already used
                        msgBox('OTP is already used or expired!');
                        $('#warning-dialog .redirect_btn_cancel').trigger('click');
                    }
                } else if(page_type_id == 4) { // For Delete Page
                    if(data.status == 0) {
                        // Give current module otp not match
                        msgBox('Incorrect OTP!');
                        return_val = false;
                    } else if(data.status == 2) {
                        $('#otp-dialog .otp_btn_cancel').trigger('click');
                        $("#warning-dialog").modal({
                            show: true      
                        });
                        
                        $('#warning-dialog .warning_content').html('<b style="color:red; font-size: 14px;">Given OTP doesn\'t matched with the current module.</b> <br /><br />Correct Module: <span style="color: #0B45B3;">' + firstToUpperCase( data.controller ) + '</span><br /><br />Do you want delete the data in that correct module or stay on this page?');
                        
                        $('#warning-dialog .modal-body .correct_url').attr('data-url',data.correct_url);
                        $('#warning-dialog .modal-body .correct_url').val(data.correct_id);
                        $('#warning-dialog #sbmt-btn').html('<i class="fa fa-trash-o"> Delete</i>');
                    } else if(data.status == 1){
                        // Give current module otp
                        $('tr').removeClass('remove_row');
                       // location.href = data.row.url;
                       
                        $('.hidden_del_form').attr('action',data.row.url);
                        if($('#confirm .modal-body .del_reason').val() != '') {
                            $('.hidden_del_form').submit();
                        } else { 
                            msgBox('Please enter Reason for Delete the record!');
                            return_val = false;
                        }
                    } else {
                        // Give Different otp that already used
                        msgBox('OTP is already used or expired!');
                        $('#warning-dialog .redirect_btn_cancel').trigger('click');
                    }
                }
            })
            .fail(function(jqXHR, status_code, error_thrown) {
                console.log(jqXHR.responseText);
            });
        } else {
            msgBox('Please enter OTP!');
            return_val = false;
        }
        
        return return_val;
    });
    
    /*** Submit the OTP Value ***/
    
    /*** If submitted OTP value is mismatched, when Redirct the that module***/
    $('#warning-dialog #sbmt-btn').click(function() {
        var correct_url = $('#warning-dialog .modal-body .correct_url').attr('data-url');
        var correct_id = $('#warning-dialog .modal-body .correct_url').val();
        var return_val = true;
        $.ajax({
            async: false,
            url: base_url + 'otp_login/update_otp_status_by_correct_id',
            type: 'POST',
            data: {
                id: correct_id
            },
            dataType: "json"
        })
        .done(function(data) {
            
            window.location.href = correct_url;
            return_val = true;
        })
        .fail(function(jqXHR, status_code, error_thrown) {
            console.log(jqXHR.responseText);
        });
        
        return return_val;
    });
    /*** If submitted OTP value is mismatched, when Redirct the that module***/
    
    /*
     * Billing Scripts
     */
    var html = '<div class="lang bttn primary lang-switch-btn">E</div>';
    //$('#dev-dialog input[name="lang-switch"]').val('E');
    $('.dialog').prepend(html);
    
    multiSelect();
    isNumpad = typeof isNumpad == 'undefined' ? false : isNumpad;
    
    if( isNumpad || $('#ksk-login').length > 0 ) {
        setNumPad();
    }
                
    //$('.draggable').draggable();

    $(document).on('click', '.msg-box .clse-btn', function(){
        msgBox();
    });

    $(document).on('click', '.lang-switch-btn', function(){
        $('.lang-switch-btn').toggleClass('active');
        setTimeout(function(){setKeyPad()},0);
    });

    $(document).on('click', '.cancel_popup', function(){
        resetAll($('#booked-dialog'));
        resetAll($('#avail-dialog'));
        $('.resp-table').hide();
    });

    $(document).on('click', '.dialog .clse-btn', function(){
        var $parent = $(this).parent().closest('.dialog');
        dialog($parent, true);
        resetAll($parent);
        msgBox();
    });

     $('.add-dev-btn').on('click', function(){
         var $this = $(this);
         dialog($('#dev-dialog'));
         resetAll($('#dev-dialog'));   

         if( !$this.hasClass('got-it') ) {

            // Get Stars & SMS Types
            var data = {
               'act'   : 'stars',
           };

           $.post(baseURL + 'billing_common/ajax', data, function( results ) {
               $this.addClass('got-it');

               results = JSON.parse(results);

               var html = '<option value="">-- Select Star --</option>';
               Object.keys(results['stars']).map(function(ik, iv){
                   var obj = results['stars'][ik];
                   html += '<option value="'+ obj['id'] +'">'+obj['name']+' / '+obj['tamil_name']+'</option>';
               });

               $('#dev-dialog .stars').html(html);

               html = '<option value="">-- Select SMS Type --</option>';
               html += '<option value="0" class="all">All</option>';
               //for(i = 0; i <= 100; i++) {
               Object.keys(results['sms_types']).map(function(ik, iv){
                   var obj = results['sms_types'][ik];
                   html += '<option value="'+ obj['id'] +'">'+obj['sms_type_name']+'</option>';
               });
               //}

               var $m = $('#dev-dialog [name="multi-sms_types"]');
               $m.html(html);
               multiSelect($m);
               $lang_switchval = $('#dev-dialog .lang-switch-btn').text();
               $('#dev-dialog [name="lang-switch"]').val($lang_switchval);
           });

         }// !got-it   

     })
     
    if(localStorage.getItem('devotee_controller') != controller) {
        localStorage.removeItem('devotee_contact');
        localStorage.removeItem('devotee_controller');
        $('#get-dev-dialog input:first').val('').focus();
        $('#dev-plot').html('').hide(); 
    }

    $('.get-dev-btn').on('click', function(){
        dialog($('#get-dev-dialog'));
        if(localStorage.getItem('devotee_contact') != undefined && localStorage.getItem('devotee_contact') != ''){
            if(localStorage.getItem('devotee_controller') == controller) {
                $('#get-dev-dialog input:first').val(localStorage.getItem('devotee_contact'));
                $('#get-dev-dialog .dev-search-btn').trigger('click');
                //$('#dev-plot .cell').trigger('click');
            } else {
                /*  localStorage.setItem('devotee_contact','');
                localStorage.setItem('devotee_controller','');*/
                localStorage.removeItem('devotee_contact');
                localStorage.removeItem('devotee_controller');
                $('#get-dev-dialog input:first').val('').focus();
                $('#dev-plot').html('').hide();
            }
        } else {
         $('#get-dev-dialog input:first').focus();
         //$('#get-dev-dialog input:first').val('').focus();
         //$('#dev-plot').html('').hide();
        }
    })
     
    $('.dev-reset-btn').on('click', function() {
        /*localStorage.setItem('devotee_contact','');
        localStorage.setItem('devotee_controller','');*/
        localStorage.removeItem('devotee_contact');
        localStorage.removeItem('devotee_controller');
        $('#get-dev-dialog input:first').val('').focus();
        $('#dev-plot').html('').hide();
    });

     /*$('body').on('click', function(e){
        var e = e ? e : event;

        if(!$(e.target).hasClass('multi-select-expand') && $(e.target).parent().closest('.multi-select-expand').length == 0) {
            //$('.multi-select-expand').fadeOut('slow');
            //msgBox('Please close the select option first!');
            //$('.multi-select-expand .fa.tick-ok').trigger('click');
        }
    })*/

    $(document).on('click', '.multi-select-preview', function(){ 
        $('#'+$(this).attr('data-target')).fadeIn('slow');
    });
    
    $(document).on('click', '.multi-select-expand .fa.tick-ok', function(){
        $(this).parent().closest('.multi-select-expand').fadeOut('slow');
    })

    $(document).on('click', '.multi-select-expand .option', function(){    
        var $this   = $(this)
        ,   $parent = $this.parent().closest('.multi-select-expand')
        ,   isAct   = $this.hasClass('active') ? false : true
        ,   $all    = $parent.find('.option.all')
        ,   len     = $parent.find('.option').length
        ,   ids     = str = ''
        ,   $option = $('select[name="'+$parent.attr('id')+'"] option[value="'+$this.attr('data-val')+'"]');

        if($this.hasClass('all')) {
            $this = $parent.find('.option');
        }

        if( isAct ) {
            // Add
            --len;
            $this.addClass('active');
            $this.find('.fa').removeClass('fa-square-o').addClass('fa-check');
            $option.attr('selected', 'selected');
        }else {
            // Remove
            ++len;
            $this.removeClass('active');
            $this.find('.fa').removeClass('fa-check').addClass('fa-square-o');
            $option.removeAttr('selected');
        }

         var i = 0;   
         $parent.find('> div.active').not('.all').each(function(){
                ids += $(this).attr('data-val')+',';
                str += '<div class="active">'+$(this).text()+'</div>';
                ++i;
         });

         ids = ids != '' ? ids.substring(0, ids.length-1) : '';
         str = str != '' ? str+'<div>Total: '+i+'</div>' : '<div>Nothing is selected</div>';

        $parent.find('input[type="hidden"]').val(ids);
        $parent.prev('.multi-select-preview').html(str);

        if( !$this.hasClass('all') && $all.length > 0) {

            var chkdLen = $parent.find('.option.active').length;

            if( len == chkdLen ){
                // All are checked
                $all.addClass('active');
                $all.find('.fa').removeClass('fa-square-o').addClass('fa-check');
            }else {
                $all.removeClass('active');
                $all.find('.fa').removeClass('fa-check').addClass('fa-square-o');
            }

        }

    });




     $(document).on('click', '#dev-childs .ctrls .add-btn', function(){
         var $blck = $(this).parent().closest('.blck');

         $('#dev-childs .blck:last').after($blck.clone());

         $('#dev-childs .blck .add-btn').remove();
         $('#dev-childs .blck:last .ctrls').append('<i class="fa fa-plus-circle add-btn"></i>');
         $('#dev-childs .ctrls .rm-btn').fadeIn('slow');

         // Clear all fields
         $('#dev-childs .blck:last *:input').val('');
         //$('#dev-childs .blck:last input:first').focus();

        $('html, body').animate({
                scrollTop: $('#dev-childs .blck:last').offset().top+'px'
        },1000);
     })

     $(document).on('click', '#dev-childs .ctrls .rm-btn', function(){
         var $blck = $(this).parent().closest('.blck');
         $blck.slideUp('slow', function(){
             $(this).remove();

             if( $('#dev-childs .ctrls .add-btn').length == 0 ) {
                 $('#dev-childs .blck:last .ctrls').append('<i class="fa fa-plus-circle add-btn"></i>');
             }

             if( $('#dev-childs .ctrls .rm-btn').length <= 1 ) {
                 $('#dev-childs .ctrls .rm-btn').fadeOut();
             }

             if( $blck.find('.db-id').length > 0 ) {
                 if( $('#dev-childs [name="removed-childs"]').length == 0) {
                     $('#dev-childs').prepend('<input type="hidden" name="removed-childs" value="">');
                 }

                 $('#dev-childs [name="removed-childs"]').val($('#dev-childs [name="removed-childs"]').val()+','+$blck.find('.db-id').val());
             }
         })
     });

     $(document).on('click', '#dev-submit-btn', function(){
        var actLen = $('#dev-plot .cell.active').length;
        
        if (typeof(Storage) !== "undefined") {
            // Store
            localStorage.setItem("devotee_contact", $('#get-dev-dialog input[name="cnt_ref_no"]').val());
            localStorage.setItem("devotee_controller", controller);
        }
        
        if( actLen == 0 ) {
            msgBox('Nothing to submit in here');
            return false;
        }else {
            // Reset
            $('#main-content .contact-no, #main-content .email, #main-content .address, #main-content .name, #main-content .tamil-name, #main-content .star').val('');
            
            var details = $('#dev-plot .hidden-details').val() || ""
            ,   $names  = $('#main-content .name')
            ,   isArchanai = $('#main-content.archanai').length > 0 ? true : false;
                 
            
            $names      = $names.length > 0 ? $names : $('#main-content .tamil-name');
            
            if( details != '' ) {
                details = JSON.parse(details);
                
                $('#main-content .contact-no').val(details.contactNo);
                $('#main-content .email').val(details.email);
                $('#main-content .address').val(details.address);
            }
        
            $names.each(function(ik, iv){
                //var text = $('#dev-plot .cell.active:eq('+ ik +') > div span').text();
                var details = $('#dev-plot .cell.active:eq('+ ik +')').attr('data-details') || "";
                if( details != '' ) {
                    details = JSON.parse(details);
                    $(this).val(details.name);
                    
                    $('#main-content .tamil-name:eq('+ ik +')').val(details.tamilName);
                    $('#main-content .star:eq('+ ik +')').val(details.star);
                    
                    if(isArchanai) {
                        $(this).attr('data-lang', isTamil ? details.name : details.tamilName);
                    }
                }
                
                
            });

            //msgBox('Information is submitted successfully', '', 'success');
            dialog($('#get-dev-dialog'), true);
            
            var $name = $('#main-content .name:first');
            window.setTimeout(function(){
                
                if( $name.is(':hidden') ) {
                    var errTrgt = $name.attr('data-err-target') || "";
                    if( errTrgt != '' ) {
                        $(errTrgt).trigger('click');
                    }
                }
                window.setTimeout(function(){
                    //scrollTo( $name );
                    $name.focus();
                }, 500);
                $('.sbmt-btn, [type="submit"]').removeAttr('disabled');
            }, 900);
            
        }

        if($('.contact_no').attr('id') == 'donation_contact') {
            get_pledge_amount_details();
        }
    });
     

     $(document).on('click', '.dev-search-btn', function(){

            var $dialog = $(this).parent().closest('.dialog')  
            ,   value   = $dialog.find('.dev-ref-no').val()
            ,   isAddSearch = $dialog.attr('id') == 'dev-dialog' ? true : false;

            if(value != '') {
                var data = {
                    'act'   : 'search-dev',
                    'include_contact': $dialog.find('.dev-ref-no').hasClass('include-contact') ? true : false,
                    'value' : value
                };

                if( !isAddSearch ) {
                    $('#dev-plot').html('<div class="no-results">Searching ...</div>').fadeIn('slow');
                }


                $.post(baseURL + 'billing_common/ajax', data, function( results ) {
                    results = JSON.parse(results);
                    if( results == '' ) {
                        // No results

                        if( isAddSearch ) {
                            $('#dev-dialog [name="ref_no"]').val('');
                            $('#dev-dialog [name="ref_no"]').trigger('keyup');
                            msgBox('Invalid Ref. No!', -1);
                           
                            $('#dev-childs .blck').not('#dev-childs .blck:last').remove();
                            $('#dev-dialog .db-id').remove();
                        }else {
                            $('#dev-plot').fadeOut('slow', function(){
                                $(this).html('<div class="no-results">Sorry, No record found!</div>').fadeIn('slow');
                            })
                        }

                    }else {

                        // Results found
                        if( isAddSearch ) {
                            msgBox('Record is fetched successfully', 3500, 'success');
                            $('#dev-childs .blck').not('#dev-childs .blck:last').remove();
                            resetMultiSelect($('#dev-dialog'));

                            // Fill all fields
                            Object.keys(results).map(function(ik, iv){

                                var row = results[ik]
                                ,   rowLen = row['items'].length
                                ,   smsTypes = row[0]['bd_sms_types'] || ""
                                ,   html = '<div>None selected</div>';

                                if( $('#dev-dialog [name="db_id"]').length == 0 ) {
                                   $('#dev-dialog form').prepend('<input type="hidden" class="db-id" name="db_id" value="">');
                                }

                                $('#dev-dialog [name="db_id"]').val(row[0]['bd_id']);

                                $('#dev-dialog [name="nric_no"]').val(row[0]['bd_nric_no']);
                                $('#dev-dialog [name="name"]').val(row[0]['bd_name']);
                                $('#dev-dialog [name="tamil_name"]').val(row[0]['bd_tamil_name']);
                                $('#dev-dialog [name="star"]').val(row[0]['bd_star_id']);
                                $('#dev-dialog [name="contact_no"]').val(row[0]['bd_contact_no']);
                                $('#dev-dialog [name="email"]').val(row[0]['bd_email']);
                                $('#dev-dialog [name="address"]').val(row[0]['bd_address']);
                                
                                if( row[0]['lang_switch'] == 'T' && !$('.lang-switch-btn').hasClass('active')) {
                                    // Tamil
                                    $('.lang-switch-btn:first').trigger('click');
                                    /*$('.lang-switch-btn').addClass('active');
                                    setKeyPad();*/
                                }
                                if( smsTypes != '' ) {
                                    var html = ''
                                    ,   s   = smsTypes.split(',');

                                    for( i = 0; i < s.length; i++ ) {
                                        html += '<div class="active">'+ $('[name="multi-sms_types"] option[value="'+ s[i] +'"]').text() +'</div>';
                                        $('#multi-sms_types .option[data-val="'+s[i]+'"]').addClass('active');
                                    }

                                    html += '<div>Total :'+s.length+'</div>';
                                    $('[name="sms_types"]').val(smsTypes);
                                }

                                $('#multi-preview-sms_types').html(html);


                                Object.keys(row['items']).map(function(jk, jv){
                                    // Items
                                     window.setTimeout(function(){
                                         
                                        var subRow = row['items'][jk];
                                        $('#dev-childs .blck:last [name="mem_id[]"]').remove();
                                        $('#dev-childs .blck:last').prepend('<input type="hidden" class="db-id" name="mem_id[]" value="'+ subRow['bdi_id'] +'">');
                                        $('#dev-childs .blck:last [name="mem_name[]"]').val(subRow['bdi_name']);
                                        $('#dev-childs .blck:last [name="mem_tamil_name[]"]').val(subRow['bdi_tamil_name']);
                                        $('#dev-childs .blck:last [name="mem_star[]"]').val(subRow['bdi_star_id']);

                                        if( jk < rowLen-1 ) {
                                            $('#dev-childs .ctrls .add-btn').trigger('click');
                                        }

                                    }, 1000);

                                });



                            });

                            $('#dev-dialog [name="ref_no"]').attr('disabled', 'disabled');
                            /* $('#dev-dialog .save-btn').removeAttr('style');
                            $('#dev-dialog .dev-search-btn').css('display','none'); */
                            
                            // Set Save Btn
                            setDevSaveBtn();



                        }else {
                            // Get devotee search
                            
                            var totalNames = $('#main-content .name').length;
                            totalNames = totalNames > 0 ? totalNames : $('#main-content .tamil-name').length;
                            
                            Object.keys(results).map(function(ik, iv){

                                var row = results[ik]
                                ,   rowLen = row['items'].length
                                ,   addr   = row[0]['bd_address']
                                ,   html = '<div class="no-results" id="chse-mem" data-no="'+ totalNames +'"><div>You can choose <span>'+ totalNames +'</span> member(s) right now!</div></div>';
                                
                                if( addr != '' ) {
                                    addr = addr.replace('\'', '\"').replace('"', '\"');
                                }

                                var details = {
                                    'contactNo' : row[0]['bd_contact_no'],
                                    'email'     : row[0]['bd_email'],
                                    'address'   : addr,
                                };
                                
                                
                                if( $('#dev-plot .hidden-details').length == 0 ) {
                                    html += '<input type="hidden" class="hidden-details" value=\''+ JSON.stringify( details ) +'\'>';
                                }
                                
                                details = {
                                    'name'      : row[0]['bd_name'],
                                    'tamilName' : row[0]['bd_tamil_name'],
                                    'star'      : row[0]['bd_star_id'],
                                }    
                                
                                var style = isTamil ? 'font-family: amudham;' : '';
                                
                                html += '<div class="cell" data-details=\''+ JSON.stringify( details ) +'\'><div><span style="'+style+'" data-lang="'+ ( isTamil ? row[0]['bd_name'] : row[0]['bd_tamil_name'] ) +'">'+( isTamil ? row[0]['bd_tamil_name'] : row[0]['bd_name'] )+'</span></div></div>';

                                //for( i = 0; i < 10; i++ ) {
                                Object.keys(row['items']).map(function(jk, jv){
                                    // Items
                                    var subRow = row['items'][jk];
                                    details.name       = subRow['bdi_name'];
                                    details.tamilName  = subRow['bdi_tamil_name'];
                                    details.star       = subRow['bdi_star_id'];
                                    
                                    html += '<div class="cell" data-details=\''+ JSON.stringify( details ) +'\'><div><span style="'+style+'" data-lang="'+ ( isTamil ? subRow['bdi_name'] : subRow['bdi_tamil_name'] ) +'">'+( isTamil ? subRow['bdi_tamil_name'] : subRow['bdi_name'] )+'</span></div></div>';
                                });

                                //}

                                html += '<div class="row col-xs-12 ctrls"><div class="bttn primary" id="dev-submit-btn"><i class="fa fa-check"></i> Submit</div></div>';

                                $('#dev-plot').fadeOut('slow', function(){
                                    $(this).html(html).fadeIn('slow');
                                    $('#dev-plot').data('details',details);
                                });
                            });
                        }

                    } // Yes.. Results

                });
            }

     })
     
    $(document).on('keyup', '.check-unique', function(){
        check_unique_details(this); 
    })

     $(document).on('click', '#dev-plot .cell', function(){ 
            var isAct = $(this).hasClass('active') ? false : true
            ,   totalAct = $('#dev-plot .cell.active').length
            ,   totalNames = $('#chse-mem').attr('data-no') || 0;

            if( isAct ) {
                // Add
                ++totalAct;
                if( totalAct > totalNames ) {
                    msgBox('Maximum no. of member is reached!', -1);
                    return false;
                }
                $(this).addClass('active').find('> div').prepend('<i class="fa fa-check-circle"></i>');
            }else {
                --totalAct;
                $(this).removeClass('active').find('.fa').remove();
            }

            var rem = totalNames-totalAct
            ,   tW  = $(window).scrollTop()
            ,   tE  = $('#chse-mem').offset().top;

            $('#chse-mem span').text(rem);
            if( tE > tW ) {
                msgBox();
            }else {
                msgBox('You can choose '+rem+' member(s) right now!', '', 'info');
            }

     });

     $('#dev-dialog .save-btn').on('click', function(){
        var $this = $(this)
        ,  isUpdate = ($('#dev-dialog [name="db_id"]').val() !== undefined && $('#dev-dialog [name="db_id"]').val() != '') ? true : false;
        
        if( autoValidate( $('#dev-dialog') ) ) {

            $this.attr('disabled', 'disabled');
            $this.find('span').text((isUpdate ? 'Updating' : 'Saving') + ' ...');
            console.log($('#dev-dialog form').serialize());
            var data = {
                'act'  : 'update',
                'type' : 'devotee',
                'id'   : $('#dev-dialog [name="db_id"]').val(),
                data   : $('#dev-dialog form').serialize(),
                'lang' : $('.lang-switch-btn').hasClass('active') ? 'T' : 'E',
            }

            $.post(baseURL + 'billing_common/ajax', data, function( results ) {
                $this.removeAttr('disabled');
                $this.find('span').text(isUpdate ? 'Update' : 'Save');

                results = JSON.parse(results);
                
                if( isUpdate ) {
                    msgBox('Devotee is updated successfully', '', 'success');
                }else {
                    //msgBox('Devotee is saved successfully', '', 'success');
                    window.setTimeout(function(){
                        msgBox('Devotee is saved successfully....<div>Please note the following Ref. No: <b>"'+ results +'"</b></div>','', 'success');
                    }, 1000);
                }
                //$('.lang-switch-btn').removeClass('active');
                //setKeyPad();
                resetAll($('#dev-dialog'));


            });
         }

     });

     $('#dev-dialog [name="ref_no"]').on('keyup', function(){
            setDevSaveBtn();
            msgBox();
     });


    
    
    
    $(document).on('click', '.reset-btn', function(){
        $(this).parent().closest('form').find(':input').val('');
    })
    
    // Tabs
    
    $('.tabs > div').on('click', function(){
        $('.tabs > div.active #curve, .tabs > div.active #padder').remove();
        $('.tabs > div.active').removeClass('active');
        $(this).addClass('active').append('<div id="curve"></div><div id="padder"></div>');
        
        var $tab = $('.tab');
        if( $('.tab.active').length > 0 ) {
            $tab = $('.tab.active');
        }
        
        $tab.fadeOut(500, function(){
            $('.tab.active').removeClass('active');
            var trgt = $('.tabs > div.active').attr('data-target') || ""
            ,   $trgt = '';
            
            if( trgt == '' ) {
                var  indx = $('.tabs > div.active').index();
                $trgt = $('.tab').eq(indx);
            }else {
                $trgt = $(trgt);
            }     
                
            $trgt.addClass('active').fadeIn('slow');
        })
    })
    
    if( $('.tab').length > 0 ) {
        var max = 1;
        $('.tabs').parent().find('.tab').each(function(){
            if( $(this).height() > max ) {
                max = $(this).height();
            }
        })
        
        $('.tabs').parent().find('.tab').css({'min-height' : max+'px'});
    }
    
    if( $('.tabs > div.active.autoload').length > 0 ) {
        $('.tabs > div.active.autoload').trigger('click');
    }
    
    $(document).on('focus click', '.err-ele', function(){
        clearErrors($(this));
    });
    
     $(document).on('click', '.dialog-btn', function(e){
         e.preventDefault();
         
         // Show Pop up
         var $target = $($(this).attr('data-target')) || "";
         
         if( $target != '' ) {
             if( $('.modal-backdrop').length == 0 ) { 
                 $('body').append('<div class="modal-backdrop fade in"></div>'); 
             }
             $target.css('display', 'block').modal({show: true});
             
         }
         
         return false;
         
     });
     
     $(document).on('click', '.modal-backdrop, .cancel_popup', function(){
        $(".modal-backdrop").remove();
     });
     
    $('.blck .sub-title').on('click', function(){
        var $this       = $(this).find('.ctrl.opener')
        ,   $blck       = $this.parent().closest('.blck')
        ,   $blckContent= $blck.find('.blck-content');
        
        if( $this.hasClass('opened') ) {
            // To close
            
            $blckContent.slideUp('slow', function() {
                $this.removeClass('opened fa-chevron-up').addClass('fa-chevron-down');
            });
        }else {
            // To open
            
            $blckContent.slideDown('slow', function(){
                $this.removeClass('fa-chevron-down').addClass('opened fa-chevron-up');
                
            });
        }
    })
    
    // Billing Scripts - END
    
    
    /*
     * setTimeout() function will be fired after page is loaded
     * it will wait for 5 sec. and then will fire
     */ 
    setTimeout(function() {
        $(".flash_msg").hide();
    }, 5000);
    
    $('.img_file').on('change', function() {
        file_preview($(this));
    });
    
    $('.im_link').on('click', function(e) {
        window.location.href = $(this).attr('data-href');
    });
    
    $('.pop_up_alert').on('click', function(e) {
        var alert_msg = (typeof($(this).data('alert')) !== undefined) ? $(this).data('alert') : '';
        show_alert(alert_msg);
    });
    
    $('.pop_up_confirm').on('click', function(e) {
        e.preventDefault();
        $('#confirm .modal-body .del_reason').val('');
         
        var confirm_msg = (typeof($(this).data('confirm')) !== undefined) ? $(this).data('confirm') : '';
        var service_menu_ids = (typeof($(this).data('otp-ids')) !== undefined) ? $(this).data('otp-ids') : '';
        var auto_id = ($(this).closest('tr').find('.auto_id').val() !== undefined) ? $(this).closest('tr').find('.auto_id').val() : '';
        var redirect_url = (typeof($(this).data('href')) !== undefined) ? $(this).data('href') : '';
        show_confirm(confirm_msg, redirect_url);
        $(this).parents('tr').addClass('remove_row');
        $('#confirm .modal-footer .confirm_btn_ok').attr('data-otp-ids',service_menu_ids);
        $('#confirm .modal-footer .confirm_btn_ok').attr('data-auto-id',auto_id);
        $('#confirm .modal-footer .confirm_btn_ok').attr('data-url',redirect_url);
    });
    
    $('.confirm_btn_cancel').on('click', function() {
        $('tr').removeClass('remove_row');
        $('#confirm .modal-footer input[name="redirect_url"]').val('');
        $('#confirm .modal-body .del_reason').val('');
        $("#confirm").modal('hide');
    });
    
    /*** Generate OTP Value for Delete Page ***/
    $('.confirm_btn_ok').on('click', function() {
        var callBck = $('.remove_row').attr('data-callback') || "";
        if( callBck != '' ) {
            eval(callBck);
            return false;
        }
        
        $('.hidden_del_reason').text($('#confirm .modal-body .del_reason').val());
        var ids =  $(this).attr('data-otp-ids');
        var auto_id =  $(this).attr('data-auto-id');
        var delete_url = $(this).attr('data-url');
        $('.modal-body .otp_no').val('');
        var _this = $(this);
        var return_val = true;
        
        if($('#confirm .modal-body .del_reason').val() != '') {
            $.ajax({
                async: false,
                url: base_url + 'otp_login/get_log_otp_details',
                type: 'POST',
                data: {
                    ids: ids,
                    auto_id: auto_id,
                    url: delete_url,
                    page_type_id: 4,
                    controller: controller
                },
                dataType: "json"
            })
            .done(function(data) {
                if(data !== null && data !== '') {
                    if($(_this).hasClass('no_show_otp')) {
                        $('tr').removeClass('remove_row');
                        //location.href = $('#confirm .modal-footer input[name="redirect_url"]').val();
                        $('.hidden_del_form').attr('action',$('#confirm .modal-footer input[name="redirect_url"]').val());
                        if($('#confirm .modal-body .del_reason').val() != '') {
                            $('.hidden_del_form').submit();
                        } else { 
                            msgBox('Please enter Reason for Delete the record!');
                            return_val = false;
                        }
                        
                    } else {
                        $('#confirm .confirm_btn_cancel').trigger('click');
                        msgBox('Sending SMS.....','','info');
                        if(data.status == 1) {
                            $("#otp-dialog").modal({
                                show: true      
                            });
                            msgBox(data.msg, '', 'success');
                        } else if(data.status == 0) { 
                            msgBox(data.msg);
                        } else {
                            $("#otp-dialog").modal({
                                show: true      
                            });
                            msgBox(data.msg,'','info');
                        }
                        
                        $('.modal-body .hidden_id').val(4);
                        $('#otp-dialog #sbmt-btn').attr('data-ids',ids);
                    }
                } else {
                    $('tr').removeClass('remove_row');
                    //location.href = $('#confirm .modal-footer input[name="redirect_url"]').val();
                    $('.hidden_del_form').attr('action',$('#confirm .modal-footer input[name="redirect_url"]').val());
                    if($('#confirm .modal-body .del_reason').val() != '') {
                        $('.hidden_del_form').submit();
                    } else { 
                        msgBox('Please enter Reason for Delete the record!');
                        return_val = true;
                    }
                    
                }
            })
            .fail(function(jqXHR, status_code, error_thrown) {
                console.log(jqXHR.responseText);
            });
        } else {
            msgBox('Please enter Reason for Delete the record!');
            return_val = false;
        }
        return return_val;
        
    });
    /*** Generate OTP Value for Delete Page ***/
    
    //float_value();
    integer_value();
    
    if ($(".data_table").length > 0) {
        $(".data_table").dataTable({
            aoColumnDefs: [{
                bSortable: false,
                aTargets: [ -1 ]
            }]
        });
    }
    
    //Datepicker
    if ($(".datepicker").length > 0) {
        set_datepicker();
    }
    
    //Timepicker
    if ($(".timepicker").length > 0) {
        set_timepicker();
    }
    
    set_chosen();
    
    //$('input[type="checkbox"]').iCheck();
    String.prototype.ucfirst = function() {
        return this.charAt(0).toUpperCase() + this.slice(1);
    }
    
    if($('.hidden_id').val() == '') {
        $(".grpChkBox > div:nth-child(-n+8) input[type='checkbox']").prop('checked', true);
    }
   
    filtered_columns();
    

    $(".check").each(function() {
        if($(this).is(':checked')) {
            show_filtered_columns($(this));
        } else {
            hide_filtered_columns($(this));
        }
    });
    
    $(".grpChkBox input[type='checkbox']").on('ifChecked', function(event){
        show_filtered_columns($(this));
    });
    
    $(".grpChkBox input[type='checkbox']").on('ifUnchecked', function(event){
        hide_filtered_columns($(this));
    });
    //Working
    if(controller == 'prasadam_sale_report') {
        $('.filterTable:first tfoot tr td:first').attr('colspan',($(".grpChkBox input[type='checkbox']:checked").length - 1));
    } else {
        $('.filterTable:first tfoot tr td:first').attr('colspan',$(".grpChkBox input[type='checkbox']:checked").length);
    }
    

    if( $('.lang-switch-btn').length > 0) {
        if( isTamil ) {
            $('.lang-switch-btn:first').trigger('click');
        }else {
            $('.lang-swap').show();
        }
    
        
    }  
    
    

    $(document).on('click', '.db_truncate', function(){
        $("#truncate-confirm").modal({
            show: true      
        });
    });
    
    $(document).on('click', '#truncate-confirm .confirm_btn_cancel', function(){
        $("#truncate-confirm").modal('hide');
    });
 
    $(document).on('click', '#truncate-confirm .confirm_btn_ok', function(){
        var request = $.ajax({
            async: false,            
            url: base_url + 'general_settings/truncate_billing_table',
            type: 'POST',
            dataType: "json",
            beforeSend: function () {
                //$('#db_truncate button[data-loading-text]').button('loading');
                console.log('beforeSend');
                $('#truncate_load .inprogress').show();            
                $('#truncate_load .completed').hide(); 
                $('#truncate_load').modal('show');            
                           
                //alert('start');
            },
            success: function (data) {
                //alert('Success');            
                console.log(data);
            },
            complete: function () {
                $('#truncate_load .inprogress').hide();            
                $('#truncate_load .completed').show(); 
                //$('#truncate_load .modal-footer').show();
                //$('#db_truncate. button[data-loading-text]').button('reset');
            },
            error: function () {
                alert('Error');
            },
        });        
    });
}); // Ready End


function filtered_columns() {
    if( controller.substring(controller.length-7, controller.length) == "_report" ) {
        var html =  '';
        var data_th_name = '';
       
        if(controller == 'donation_report' && $('.hidden_print_pledge').val() !== undefined && $('.hidden_print_pledge').val() == 1) {
            $('#filterTable>thead>tr>th').not(':first').each(function(index,element){
                var $this =  $(this);
                field_name = $(this).text().replace(/ /g , "_");
                var field_name = field_name.replace('_/_', '_');
                field_name = field_name.replace('(', '_');
                field_name = field_name.replace(')', '');
                field_name = field_name.replace('_&_', '_');
                $(this).addClass(field_name.replace(/_+$/, ''));
                $(this).parents().find('.filterTable tbody tr td.expand_container table thead tr th').removeClass();
                
                var checked = '';
                if($('.hidden_print').val() == 1) { 
                    $('.hidden_filter_array').each(function() {
                        if($(this).val() == $this.text()) {
                            checked = 'checked ';
                        }
                    });
                } else {
                    if(index < 8 ||  $(this).text() == 'Amount') {
                        checked = 'checked ';
                    } 
                }
                
                html +=  '<div class="col-md-2" style="margin: 1%;">';
                html +=  '<input type="hidden" name="filter_columns[]" value="' + field_name.replace(/_+$/, '') + '" />';
                html +=  '<input type="checkbox" class="check" value="' + $(this).text() + '" name="' + field_name.replace(/_+$/, '') + '"' + checked + '/>&nbsp;' + $(this).text();
                html += '</div>';
                data_th_name += field_name.replace(/_+$/, '') + ',';
           });
        }            
        else {
            
            $('.filterTable:first thead tr th').not(':first').each(function(index,element){
                var $this =  $(this);
                field_name = $(this).text().replace(/ /g , "_");
                var field_name = field_name.replace('_/_', '_');
                field_name = field_name.replace('(', '_');
                field_name = field_name.replace(')', '');
                field_name = field_name.replace('_&_', '_');
                if(field_name != 'S.No') {
                    $(this).addClass(field_name.replace(/_+$/, ''));
                }
                $(this).parents().find('.filterTable tbody tr td.expand_container table thead tr th').removeClass();
                
                var checked = '';
                if($('.hidden_print').val() == 1) {
                    $('.hidden_filter_array').each(function() {
                        if($(this).val() == $this.text()) {
                           checked = 'checked ';
                        }
                    });
                } else {
                    if(index < 8 ||  $(this).text() == 'Amount') {
                        checked = 'checked ';
                    } 
                }
                if(field_name != 'S.No') {
                    html +=  '<div class="col-md-2" style="margin: 1%;">';
                    html +=  '<input type="hidden" name="filter_columns[]" value="' + field_name.replace(/_+$/, '') + '" />';
                    html +=  '<input type="checkbox" class="check" value="' + $(this).text() + '" name="' + field_name.replace(/_+$/, '') + '"' + checked + '/>&nbsp;' + $(this).text();
                    html += '</div>';
                }
                data_th_name += field_name.replace(/_+$/, '') + ',';
            })
         
        }
        
        $('.filterTable').attr('data_th_name',data_th_name);
        $('.filterTable:first tbody tr').not('.remove_container').each(function(index,element){
            var th_name = $('.filterTable').attr('data_th_name').split(',');
            var field_name = '';
            for(var i = 0; i < th_name.length; i++) {
                field_name = th_name[i].replace(/ /g , "_")
                field_name = field_name.replace('_/_', '_');
                field_name = field_name.replace('(', '_');
                field_name = field_name.replace(')', '');
                field_name = field_name.replace('_&_', '_');
                $(this).not('.subTable').find('td').not(':first').eq(i).addClass(field_name.replace(/_+$/, ''));
            }
            
        })
        
        $('.grpChkBox').html(html);
        $('.grpChkBox').iCheck();
        $('.grpChkBox .icheckbox').addClass('icheckbox_minimal');
    }
    
}


function show_filtered_columns(_this) {
    var colToShow = $("#filterTable").find("." + $(_this).attr("name"));
    /* var row_index = colToShow.index();
    var column = $('.filterTable tbody tr td').eq(row_index); */
    $(colToShow).show();
    //$(column).show();
    
    if($(_this).attr("name") == 'Amount') {
        $('.filterTable:first tfoot').show();
    }
    //Working
    if(controller == 'prasadam_sale_report') {
        if($(_this).attr("name") != 'Quantity') {
            var $checked_length = ($(".grpChkBox input[type='checkbox']:checked").length - 1);
        } else {
            var $checked_length = ($(".grpChkBox input[type='checkbox']:checked").length - 1);
            $('.filterTable:first tfoot tr td:nth-child(2)').show();
        }
    } else if(controller == 'donation_report' && $(_this).attr("name") == 'Paid_Amount') {
        var $checked_length = ($(".grpChkBox input[type='checkbox']:checked").length - 1);
        $('.filterTable:first tfoot').hide();
    }else {
        var $checked_length = $(".grpChkBox input[type='checkbox']:checked").length;
    }
    $('.filterTable:first tfoot tr td:first').attr('colspan',$checked_length);
   
}

function hide_filtered_columns(_this) {
    var colToHide = $("#filterTable").find("." + $(_this).attr("name"));
    /* var row_index = colToHide.index();
    var column = $('.filterTable tbody tr td').eq(row_index); */
    $(colToHide).hide();
    //$(column).hide();
    
    if($(_this).attr("name") == 'Amount') {
        $('.filterTable:first tfoot').hide();
    }
    
    if(controller == 'prasadam_sale_report') {
        //Working
        if($(_this).attr("name") != 'Quantity') {
            var $checked_length = ($(".grpChkBox input[type='checkbox']:checked").length - 1);
            
        } else {
            var $checked_length = $(".grpChkBox input[type='checkbox']:checked").length;
            $('.filterTable:first tfoot tr td:nth-child(2)').hide();
        }
    } else if(controller == 'donation_report' && $(_this).attr("name") == 'Paid_Amount') {
        var $checked_length = ($(".grpChkBox input[type='checkbox']:checked").length);
        $('.filterTable:first tfoot tr td:nth-child(3)').hide();
    } else {
        var $checked_length = $(".grpChkBox input[type='checkbox']:checked").length;
    }
    $('.filterTable:first tfoot tr td:first').attr('colspan',$checked_length);
    
}


/*function set_tamil_keypad(_this) {
    var layouts = '',t, o = '',
    showKb = function(layout){
        var kb = $(_this).getkeyboard();
        kb.options.layout = layout;
        kb.redraw();
    };
    setTimeout(function(){
        $(_this).keyboard({
            layout: 'qwerty',
            stayOpen: true
        })
        //.previewKeyset();
        
        var kb = $(_this),
        $this = $(_this),
        layout = 'tamil-tamil99-mod';
        showKb( layout );
    }, 100);
}*/

function set_tamil_keypad(_this) {
    virtualKeyboard();
    
    /*var layouts = '',t, o = '',
    showKb = function(layout){
        var kb = $(_this).getkeyboard();
        kb.options.layout = layout;
        kb.redraw();



        /*setTimeout(function(){

            var $ele = $('.ui-keyboard-input-current') || "";
            if( $ele == '' ) {
                $ele = $('.ui-keyboard-input.active');
            }

            /*$('.ui-keyboard-has-focus').css({
                top: $ele.offset().top+'px !important',
                left: $ele.offset().left+'px !important',
            });*/

          /*  $('.ui-keyboard-has-focus').attr('style', 'top: '+$ele.offset().top+'px !important; left: '+( $ele.offset().left-( $('.ui-keyboard-has-focus').width()/4 ) )+'px !important;');
            $('html, body').css({
                scrollTop: $ele.offset().top+'px'
            },100);




            //alert('top: '+$ele.offset().top+'px !important;');

        }, 300);*/

    /*};
    setTimeout(function(){
        $(_this).keyboard({
            layout: 'qwerty',
            stayOpen: true
        })
        //.previewKeyset();

        var kb = $(_this),
        $this = $(_this),
        layout = 'tamil-tamil99-mod';
        showKb( layout );
    }, 100);*/
    
    
}

function setKeyPad(){
    $('[data-lang], .lang-tamil, .keyboard, .tstyle').fadeOut(200);
    
    if( !$('.lang-switch-btn').hasClass('active') ) {
        // Eng
        isTamil = false;
        if( $('#main-content .name').length == 0 ) {
            $('.tamil-name').removeClass('tamil-name').addClass('name');
        }
        
        $('.keyboard').removeClass('lang-tamil ui-keyboard-input ui-widget-content ui-corner-all').off('mousedown focus keyup touchstart');
        $('input.lang-tamil').not('.name').removeClass('input-tamil');
        //$('#dev-dialog input[name="lang-switch"]').val('E');
        $('.lang').html('E');
        
    }else {
        // Tamil
        isTamil = true;
        if( $('#main-content .tamil-name').length == 0 ) {
            $('.name').removeClass('name').addClass('tamil-name');
        }
        
        $('.keyboard').addClass('lang-tamil');
        $('input.lang-tamil').not('.name').addClass('input-tamil');
        //$('#dev-dialog input[name="lang-switch"]').val('T');
        $('.lang').html('T');
        
    }
    setFont();
    
    $('[data-lang]').each(function(){
        var dataLang = $(this).attr('data-lang')
        ,   isInput = $(this).is(':input') ? true : false;
        $(this).attr('data-lang', isInput ? $(this).val() : $(this).text());
        if( isInput ) {
            $(this).val(dataLang);
        }else {
            $(this).text(dataLang);
        }
    });

}

function rand(end, start) {
    var end = end || 10
    ,   start = start || 0;
    
    return Math.floor(Math.random()*Math.abs(start-end))+start;
}

function setFont() {
    if( isTamil ) {
        // Tamil
        $('[data-lang], .lang-tamil, .keyboard').addClass('tstyle');//.css({'font-family' : 'amudham', 'font-weight' : 'bolder', 'font-size' : '18px'});
        $('.input_name.keyboard').attr('placeholder', 'jkpH; bgah;');
        
    }else {
        $('[data-lang], .lang-tamil, .keyboard').removeClass('tstyle').css({'font-family' : ''});//, 'font-weight' : 'bolder', 'font-size' : '18px'});
        $('.input_name.keyboard').attr('placeholder', 'Name');
    }
    $('[data-lang], .lang-tamil, .keyboard, .tstyle').fadeIn(50);
    
}

function dialog($this, toClose){
    var $this = typeof $this != 'undefined' ? $this : $('.dialog:first')
    ,   toClose = typeof toClose == 'undefined' ? false : true;

    if( toClose ) {
        // close 
        if( $('#main-content').hasClass('fixed') ) {
            $('body').css({'overflow':'hidden'});
        }else {
            $('body').css({'height': 'auto', 'overflow-y':'auto'});
        }
        $this.fadeOut(500, function(){
            $(this).removeAttr('style');
            //$('#main-content').removeClass('overlay');
            //$('#overlay').remove();

            //$('#name-sec .input_set input').removeAttr('disabled');
        });



    }else {
        // open


        var Hgt = $this.outerHeight()
        ,   W = $(window).width()
        ,   H = $(document).height()
        ,   t = H/4 - (Hgt/2)
        ,   styles = {
            'opacity'   : 1,
            //'min-width' : (W)+'px',
            'min-height': (H)+'px',
            top         : '0px',
            left        : '0px'
            //'top'       : t+'px',
            //'left'      : ( W/4 - ($this.width()/2) )+'px'
        };

        if( Hgt < (W-t) ) {
            $('body, html').animate({
                scrollTop: $this.offset().top+'px'
            }, 1000);
            //$('body').css({'height': '100%','overflow':'hidden'});
        }
        //$('#main-content').addClass('overlay');
        //$('body').prepend('<div id="overlay" style="min-height: '+ $(document).height() +'px;">&nbsp;</div>');
        $this.css(styles).fadeIn('slow');
        if( $this.height() > $(window).height() ) {
            $('body').css({'overflow-y':'auto'});
        }

       //$('#name-sec .input_set input').attr('disabled', 'disabled');
    }
}

function setNumPad() {
    
    if( isNumpad ) {
        var style="background: repeating-radial-gradient(#fff, "+ keybrdClr +");";
        //var style="background: repeating-radial-gradient(#fff, #ccc);";
    //if( $('#ksk-login').length == 0 ) {
        var html   = '<div class="pad">' +
                    '<div class="ctrls">' +
                        '<div class="cell clr-btn">C</div>' + '<div class="cell clr-all-btn">X</div>' + '<div class="cell ok-btn">OK</div>' + 
                    '</div>' +
                    
                    '<div class="num">' +
                        '<div class="row"><div class="cell" style="'+ style +'"><span>7</span></div>' + '<div class="cell"  style="'+ style +'"><span>4</span></div>' + '<div class="cell"  style="'+ style +'"><span>1</span></div>'+ '<div class="cell swap">&nbsp;<span>00</span></div>' + '</div>' +
                        '<div class="row"><div class="cell"  style="'+ style +'"><span>8</span></div>' + '<div class="cell"  style="'+ style +'"><span>5</span></div>' + '<div class="cell"  style="'+ style +'"><span>2</span></div>'+ '<div class="cell"  style="'+ style +'"><span>0</span></div>' + '</div>' +
                        '<div class="row"><div class="cell"  style="'+ style +'"><span>9</span></div>' + '<div class="cell"  style="'+ style +'"><span>6</span></div>' + '<div class="cell"  style="'+ style +'"><span>3</span></div>'+ '<div class="cell swap">&nbsp;<span>.</span></div>' + '</div>' +
                    '</div>' +
                    
                    
                '</div>';
    
    
        /*html = '<div class="inp multiple">' +
                    '<input type="text" data-limit="1">' +
                    '<input type="text" data-limit="1">' +
                    '<input type="text" data-limit="1">' +
                    '<input type="text" data-limit="1">' +
               '</div>'+html; 
    }else {*/
        html = '<div class="inp">' +
                    '<input type="text">' +
                '</div>'+html; 
        
        $('body').prepend('<div class="number-pad num-pad">'+html+'</div>');
        
        $(document).on('focus', '.contact-no, .amount, .number', function(){
            
            if($(this).is('[readonly]') || $(this).is('[disabled]')) {
                return false;
            }

            $('body').prepend('<div id="overlay" style="min-height: '+ $(document).height() +'px;">&nbsp;</div>');

            var value = $(this).val();
            $('input').removeClass('active');
            $(this).addClass('active');
            if( $(this).hasClass('contact-no') ) {
                $('.number-pad .swap').removeClass('cell');
                $('.number-pad .swap span').hide();
            }else {
                $('.number-pad .swap').addClass('cell');
                $('.number-pad .swap span').show();
            }

            $('.number-pad').fadeIn('slow', function(){
                $('.number-pad .inp input:first').val(value).focus();
            })
        });
        
    //}
    } // isNumpad
    
    
    
    $('#ksk-login .num-pad .clr-all-btn').html('0').removeClass('clr-all-btn').addClass('zero');
   
    $('#ksk-login .num-pad .cell').on('click', function(){
       msgBox(); 
    });
   
    $('.num-pad .inp input').on('click', function(e){
        var $parent = $(this).parent().closest('.num-pad');
        $parent.find('.inp input.active').removeClass('active');
        $(this).addClass('active');
    });
    
    $('.num-pad .inp input').on('blur', function(e){
        $('.num-pad .inp input').each(function(){
            var   val = $(this).val()
            ,  dotLen = (val.match(/\./g) || []).length;

            if( dotLen >= 1 ) {

                var s = val.split('.');
                if( s[1].length == 0 ) {
                    // Empty after "."
                    $(this).val(val.replace('.', ''));
                }
            }
        })
        
    });
   
    $('.num-pad .inp input').on('keyup', function(e){
        var $parent = $(this).parent().closest('.num-pad')
        ,   val = $(this).val()
        ,   limit = parseInt( $(this).attr('data-limit')) || 0
        ,   dotLen = (val.match(/\./g) || []).length
       // alert(limit);
        if((val.match(/^[a-zA-Z_^%$#!~@,-]+$/g)) || (val.match(/[`~,<>;':"/[\]|{}()=_+-]/))) {
        //if((val.match(/^[a-zA-Z!@#%^”$%&’()*\+=?,\/;\[\\\]\^_`{|}~]+$/)) || (val.match(/[`~,<>;':"/[\]|{}()=_+-]/))) {
            $(this).val('');
            return false;
        } else { 
            if( dotLen >= 2  ) {
                // Repeated Dots
                return false;
            }else if( dotLen >= 1 ) {
                
                var s = val.split('.');
                if( s[0].length < limit ) {
                    limit = s[0].length;
                }
                        
                if( s[1].length <= 4 ) {
                    limit += s[1].length+(5-s[1].length); 
                }
            }
           
            
            //alert(dotLen+' , '+limit);
            
            if( limit != 0 && val.length >= limit) {
                $(this).val(val.substring(0, limit));
                $parent.find('.inp input.active').removeClass('active');
                $(this).next().focus().addClass('active');
                return false;
            }
        }
        
    });
   
    $('.num-pad .num .cell, .num-pad .zero').on('click', function(){
        if( !$(this).hasClass('cell') ) {
            return false;
        }
        var $parent = $(this).parent().closest('.num-pad')
        ,   num = $(this).find('span').text();
        
        if( num != '.' ) {
            $parent.find('.inp input').each(function(){
                var val = $(this).val()
                ,   limit = parseInt( $(this).attr('data-limit') ) || 0
                ,   str   = val+''+num
                ,   dotLen = (val.match(/\./g) || []).length;
               
                //alert(str.indexOf('.'));
                
                if( dotLen >= 1 ) {
                    var s = str.split('.');
                    if( s[0].length < limit ) {
                        limit = s[0].length;
                    }
                    
                    if( s[1].length <= 4 ) { // 2
                        limit += s[1].length+(5-s[1].length); //3
                    }
                    
                }
                
                num = num.substring(0, limit);
                if( val == '' || limit == 0 || val.length < limit) {
                    $parent.find('.inp input.active').removeClass('active');
                    $(this).val(str).focus().addClass('active');
                    return false;
                }
                
            })
        }else {
            //alert($parent.find('.inp input:focus').length);
            var $focus = $parent.find('.inp input.active');
            if( $focus.length == 0 ) {
                $focus = $parent.find('.inp input:first');
            }
            
            $focus.val($focus.val()+''+num);
            
        }
        
    })
    
    $('.num-pad .clr-all-btn').on('click', function(){
        var $parent = $(this).parent().closest('.num-pad');
        $parent.find('.inp input').val('').removeClass('active');
        
    });    
    
    $('.num-pad .clr-btn').on('click', function(){
        var $parent = $(this).parent().closest('.num-pad')
        ,   len     = $parent.find('.inp input').length
        ,   $inp    = $parent.find('.inp input.active');
        
        $parent.find('.inp input.active').removeClass('active');
        
        if( len > 2 ) {
            var val = $inp.val() || "";
            if( $inp.length > 0 && val != '' ) {
                // Currently focused input.
                var val = $inp.val();
                $inp.val(val.substring(0, val.length-1)).focus().addClass('active');
            }else {
            
                for( i = len; i > 0; i-- ) {
                    var $inp    = $parent.find('.inp input:eq('+(i-1)+')')
                    ,   val     = $inp.val() || "";

                    if( val != '' ) {
                        $inp.val(val.substring(0, val.length-1)).focus().addClass('active');
                        return false;
                    }
                }
            }
        
        
        }else {
            // Single field
            val = $parent.find('.inp input').val();
            
            $parent.find('.inp input').val(val.substring(0, val.length-1)).focus().addClass('active');
        }
        
    });     
    
    $('.num-pad .ok-btn').on('click', function(){
        // Submit
        var $this   = $(this)
        ,   $parent = $this.parent().closest('.num-pad')
        ,   code    = msg = '';
        
        $parent.find('.inp input.active').removeClass('active');
        
        if( $('#numpad-login').length > 0 ) {
            
            $('#ksk-login .num-pad .inp input').each(function(){
                var val = $(this).val() || "";
                
                if( val == '' ) {
                    msg = 'Please enter the full code';
                    $(this).focus();
                    return false;
                }else {
                    code += ''+val;
                }
            });
            
            if( msg != '' ) {
                // Error
                msgBox(msg);
                return false;
            }


            var data = {
                'act'   : 'pass-code',
                'type'  : 'login',
                'code'    : code
            };
            
            $this.attr('disabled', 'disabled');
            $('#ksk-login').attr('data-wait', 'yes');
            setTimeout(function(){
                if( $('#ksk-login').attr('data-wait') == 'yes' ) {
                    msgBox('Please wait.. ', -1, 'info');
                }
            }, 1500);
            
            $.post(baseURL + 'billing_common/ajax', data, function( results ) {
                    results = JSON.parse(results) || "";
                    $('#ksk-login').removeAttr('data-wait');
                    $this.removeAttr('disabled');
                   
                    if( results != '' ) {
                        if( results['status'] == '0' ) {
                            // Blocked
                            msgBox('Your Account has been Blocked. Please contact the site administrator!', -1);
                        }else {
                            var role    = results['role']
                            ,   status  = parseInt( results['status'] ) || 1
                            ,   msg     = 'Your don\'t have any access for billing!';
                            
                            $('#ksk-menu-dialog .user_role_id').val(role);
                            $('#ksk-menu-dialog .user_role_id').attr('data-id',results['id']);
                            
                            if( status == '2' ) {
                                // No more Permissions 
                                msg     = 'Sorry, You don\'t have any access. Please contact the site administrator!';
                                msgBox(msg, -1);
                                return false;
                            }
                            
                            msgBox();
                            
                            if( role != '1' ) {
                                // Admin
                                dialog($('#ksk-menu-dialog'));
                                $('#ksk-menu-dialog #name').html(results['name']); 
                                
                                if( status == 21 ) {
                                    // No Permission for Billing
                                    
                                    $('#ksk-menu-dialog #bill-btn').removeAttr('href').addClass('disabled').attr('onclick', 'javascript: msgBox("'+msg+'", -1); return false;');
                                }else {
                                    // 
                                    $('#ksk-menu-dialog #bill-btn').attr('onclick', 'javascript: open_balance_dialog(this);');
                                }
                                
                                if( status == 22 ) {
                                    // No Permission for Administration
                                    msg     = 'You don\'t have enough privileges!';
                                    $('#ksk-menu-dialog #admin-btn').removeAttr('href').addClass('disabled').attr('onclick', 'javascript: msgBox("'+msg+'", -1); return false;');
                                }else {
                                     $('#numpad-login').remove();
                                     $('#ksk-menu-dialog #admin-btn').attr('onclick', 'javascript: open_balance_dialog(this);');
                                }
                               
                            } else if( role == '1' ) {
                                // NOrmal User 
                                if( status == 21 ) {
                                    // No Permission for Billing
                                    msgBox(msg, -1);
                                }else if(results['redirect']){
                                    //window.location.href = results['redirect'];
                                    $('#numpad-login').remove();
                                    open_balance_dialog($('.dialog .open_amt'));
                                }else {
                                    msgBox('Oops: Something is went wrong!', -1);
                                }
                                return false;
                            }
                        }

                    }else {
                        msgBox('Passcode is not valid.. Please try again', -1);
                        return false;
                    }

            });      
        
        }else {
            var $inp = $('input.active, input:focus');
            $inp.val($parent.find('.inp input:first').val());
            $parent.fadeOut('slow', function(){
                $parent.find('.inp input').val('');
                $('#overlay').remove();
                if( $inp.hasClass('amount') ) {
                    $inp.trigger('keyup');
                }
            });
        }
        
        /*if($('#ptypes-dialog').is(':visible')) {
            if($('#ptypes-dialog .ptype-box input.active')) {
                $('#ptypes-dialog .ptype-box input.active').trigger('keyup');
            }
        }*/

        if($('.contact_no.active').attr('id') == 'donation_contact') {
            get_pledge_amount_details();
        }
       
        $('.check-unique').trigger('keyup');
        
        /* if($('#ptypes-dialog .ptype-box input').hasClass('active')) { 
            var this_val = $('#ptypes-dialog .ptype-box input.active');
            set_cheque_details($('#ptypes-dialog .ptype-box input.active').parent(),this_val);
        }  */
        $('#cheque-box input').trigger('keyup');
        
        $('#ptypes-dialog .ptype-box input').each(function() {
            var this_id = $(this).parent().attr('id');
            var this_val = $(this).val();
            if(this_id == 'ptype-box-cheque') {
                set_cheque_details($(this).parent(),this_val);
            }
        });
        
        return false;
    })
    

    
}

function set_cheque_details(_this,this_val) {
    var $this = $(_this)
    ,    id = $(_this).attr('id')
    ,    s = id.split('-');
    
    if( s[2].indexOf('cheque') >= 0 && this_val != '') {
        //$('#pay-amounts-box').slideUp('slow');//, function(){
            //$('#membership-card-box').slideUp('slow');
            $('#cheque-box').slideDown('slow', function(){
                if( !$('#ptype-box-cheque input').is(':focus') ){
                    $('#cheque-box input:first').focus();
                }
            })
        //})
    } else {
        $('[type="submit"], .sbmt-btn').removeAttr('disabled');
         $('#cheque-box').slideUp('slow');//, function(){
            $('#pay-amounts-box').slideDown('slow');
        //})
    }
    
}


function multiSelect($multi) { 
    var $multi = typeof $multi != 'undefined' ? $multi : $('.multi-select');
    
    $multi.each(function(){
        var $this = $(this)     
        ,   id    = $this.attr('name') || $this.attr('id')
        ,   id    =  id.replace('multi-', '')
        ,  target = 'multi-'+ id;

        
        // Remove Prev. one
        $('#multi-'+id+', #multi-preview-'+id).remove();

        //if( $('#'+ target ).length == 0 ) {
            var html  = '<div class="multi-select-expand" id="'+ target +'">';//  onblur="javascript: hideMultiSelect(this);">';
            html += '</div>';

            
            $this.after(html);
            var wt = $this.width()
            ,   styles = {
                'width' : (wt > 340 ? 340 : wt)+'px',
                'margin-top': -(1*$this.height())+'px',    
            }
            $('#'+ target ).css(styles);//.fadeIn('slow');

            //$this.removeAttr('name').attr('data-target', target);
            $this.after('<div id="multi-preview-'+id+'" class="multi-select-preview '+$this.attr('class').replace('multi-select', '')+'" data-target="'+ target +'"><div>Nothing is selected</div></div>').attr('name', 'multi-'+id).attr('multiple', 'multiple').hide();
       
        //}
        
        var html = '<i class="fa fa-check tick-ok"></i><input type="hidden" name="'+ id +'" value="">';
        $(this).find('option').each(function(){
            var value = $(this).attr('value');
            html += '<div data-val="'+value+'" class="'+(value != '' ? 'option' : '' )+' '+ ($(this).attr('class') || "") +'">'+(value != '' ? '<i class="fa fa-square-o"></i> ' : '' )+$(this).text()+'</div>';
        })
        
        $('#'+ target ).html(html);
   })
}

function resetMultiSelect($parent) {
    var $parent = typeof $parent != 'undefined' ? $parent : $('body');

    $parent.find('.multi-select').val('');
    $parent.find('.multi-select-expand input[type="hidden"]').val('');
    $parent.find('.multi-select-preview').html('<div>None selected</div>');
    $parent.find('.multi-select-expand .option.active').removeClass('active').find('.fa').removeClass('fa-check').addClass('fa-square-o');

}

function setDevSaveBtn() {
    var value = $('#dev-dialog [name="ref_no"]').val();
    if( value != '' && $('#dev-dialog [name="db_id"]').val() === undefined) {
        // Search
        $('#dev-dialog .save-btn').hide().find('span').text('Save');
        $('#dev-dialog .dev-search-btn').fadeIn('slow');

        $('#dev-dialog .req-mark').remove();
    }else {
        // Save | Update
        var lbl = 'Save';
        if( $('#dev-dialog [name="db_id"]').length > 0 ) {
            // Update
            lbl = 'Update';
        }

        $('#dev-dialog .dev-search-btn').hide();
        $('#dev-dialog .save-btn').fadeIn('slow').find('span').text(lbl);

        $('#dev-dialog .req').each(function(){
            if( $(this).prev('label').find('.req-mark').length == 0 ) {
                $(this).prev('label').append('<span class="req-mark"> * </span>');
            }
        });
    }
}

function resetAll($parent) {
   var $parent = typeof $parent != 'undefined' ? $parent : $('form') 
   $parent.find('*:input').val('');
   $parent.find('.db-id').remove();

   if( $parent.hasClass('dialog') ) {
       $parent.find('[name="ref_no"]').removeAttr('disabled').trigger('keyup');
       $('#dev-childs .blck').not('#dev-childs .blck:last').remove();

   }

   resetMultiSelect($parent);
}

function get_member_ship_card_details(_this,eve){
    var card_no = $(_this).val();
    var paid_amt = parseFloat($('#ptype-box-membership-card input').val()) || 0;
    $.ajax({
        async: false,
        url: base_url + 'billing_membership_card/get_t_card_details',
        type: 'POST',
        data: {
            card_no: card_no
        },
        dataType: "json"
    })
    .done(function(data) {
        //alert($('#ptype-box-membership-card input').val());
        if(data != '') {
            $('#membership-card-box input[name="card_name"]').val(data.name);
            $('#membership-card-box input[name="mem_id"]').val(data.id);
            $('#membership-card-box input[name="card_amount"]').val(data.amount);
            if(parseFloat(data.amount) <= parseFloat(0)) {
                msgBox('Insufficient Fund in this Card!', -1);
                $('#ptype-box-membership-card input').val('');
            }
            if(parseFloat(paid_amt) > parseFloat(data.amount)) {
                $('#ptype-box-membership-card input').val((parseFloat(data.amount)).toFixed(2));
            }            
        } else {
            if(eve == 2) {
                msgBox('Invalid Card No', -1);
                $('#membership-card-box input[name="card_name"]').val('');
                $('#membership-card-box input[name="mem_id"]').val('');
                $('#membership-card-box input[name="card_amount"]').val('');
            }
        }
    })
    .fail(function(jqXHR, status_code, error_thrown) {
        console.log(jqXHR.responseText);
    });
}

function check_unique_details(_this) {
    if($(_this).hasClass('contact-no')) {
        var field_name = 'Contact No';
    } else if($(_this).hasClass('email')) {
        var field_name = 'Email';
    } else {
        var field_name = 'Nric No';
    }
    var edit_id = $('[name="hidden_id"]').val();
    
    if(edit_id == '' && controller != 'billing_donation') {
        $.ajax({
            async: false,
            url: base_url + 'billing_common/check_unique_details',
            type: 'POST',
            data: {
                val: $(_this).val(),
                field_name: field_name
            },
            dataType: "json"
        })
        .done(function(data) {
            if(data == 1) {
                msgBox(field_name + ' already Exists');
                $(_this).focus();
                //return false;
            } else {
                return true;
            }
        })
        .fail(function(jqXHR, status_code, error_thrown) {
            console.log(jqXHR.responseText);
        });
    }
}


$(window).on('beforeunload', function()  
{  
	$("button[type=submit], button[type=button], input[type=submit], input[type=button]").prop("disabled", "disabled");  
});