/* 
 * Author       : Jai K
 * Purpose      : Main script for "Archanai"
 * Created On   : 2016-08-22 15:02
 */

$(document).on('ready', function(){
    
    $('body').addClass('arch-body');
    
    if( $('.bxslider').length > 0 ) {
    
        var config = {
            auto: false,
            responsive: true,
            mode: 'horizontal',
            useCSS: false,
            infiniteLoop: false,
            hideControlOnEnd: true,

            autoDirection: 'next',
            preloadImages: 'all',
            autoDelay: 0,
            randomStart: false,
            moveSlideQty: 1,

            //easing: 'swing',//'easeInQuart',//'easeOutElastic',
            //speed: 2000,
            //pause: 4000,

            //autoControls: false,
            //controls: false,
            //minSlides: 2,
            pager: false,
        };

        $('.cat-blck').show();
        var slider = $('#cat-bxslider').bxSlider(config);
        var itm_slider = $('#item-bxslider').bxSlider(config);
    
    }
    
    $('.dialog .title .clse-btn').on('click', function(){
        var $parent = $(this).parent().closest('.dialog')
        ,   idd     = $parent.attr('id');
        
        $parent.fadeOut('slow', function(){
            if( idd == 'with-name-dialog' ) {
                $('.notify-box').remove();
                $('.item-cell.active').trigger('click');

            }else if( idd == 'change-pass-dialog' ) {
                // Change Password
                $('#content').fadeIn('slow');
                
            }else if( idd == 'mini-state-dialog' ) {
                // Mini Statement
                $('#content').fadeIn('slow');
                
            }else{
                $('#sliders').fadeIn('slow');
            }
        });
        
    });
    
	/*
    $(document).on('click', '#apply-names-btn', function(){
        var $this   = $(this)
        ,   name1 = (isTamil) ? ( $('.input_name:first').val() || "" ) : ( $('.name:first').val() || "" );        
        
        if( name1 == '' ) {
            notify("Please enter the Name first!");
            $('.name:first').focus();
            return false;
        }
        
        var cnt   = 0  
        ,   star1 = $('.star:first').val() || ""
        ,   name2 = $('.input-3').val() || ""
        ,   star2 = $('.input-4').val() || ""
        ,   names = [];
        
        names.push([ (isTamil ? 'TAM' : 'ENG')+name1,star1]);
        if( name2 != '' ) {
            names.push([ (isTamil ? 'TAM' : 'ENG')+name2,star2]);
        }
        
        names = JSON.stringify( names );
        $('#amt-grid .amt-row').not('.named').addClass('naming').each(function(){
            ++cnt;
            $(this).addClass('named').attr('data-names', names);
        });
        
        if(cnt > 0){
            $('.input-1, .input-2, .input-3, .input-4').val('');
            //notify('Names are Applied!', 1500, 'info');
        }
        
        setTimeout(function(){
            $('#amt-grid .naming').removeClass('naming');
            
            
        }, 2000);
    });
	*/
	
	$(document).on('click', '#apply-names-btn', function () {
        var $this = $(this)
                /* ,   name1   = $('.name:first').val() || ""; */
                , name1 = (isTamil) ? ($('.input_name:first').val() || "") : ($('.name:first').val() || "");

        if (name1 == '') {
            notify("Please enter the Name first!");
            $('.name:first').focus();
            return false;
        }

        var cnt = 0
                , star1 = $('.star:first').val() || ""
                , name2 = $('.input-3').val() || ""
                , star2 = $('.input-4').val() || ""
                , names = [];

        names.push([(isTamil ? 'TAM' : 'ENG') + name1, star1]);
        if (name2 != '') {
            names.push([(isTamil ? 'TAM' : 'ENG') + name2, star2]);
        }

        names = JSON.stringify(names);
        $('#amt-grid .amt-row').not('.named').addClass('naming').each(function () {
            ++cnt;
            $(this).addClass('named').attr('data-names', names);
            var godval = $(this).closest(".named").find(".amt_name").html();
            var godnewval = $(this).closest(".named").attr('id');
            var splitnameval = godnewval.split("-");
            var return_first = function () {
                var tmp = null;
                $.ajax({
                    url: base_url + 'billing_archanai/get_sanctum_name',
                    data: {godnewval: splitnameval[1]},
                    dataType: 'JSON',
                    type: 'post',
                    'global': false,
                    'async': false,
                    success: function (output) {
                        tmp = output;
                    }
                });
                return tmp;
            }();
            if (return_first.cat_slug != 'others') {
                if (isTamil == false) {
                    var catname = return_first.category_name;
                } else {
                    catname = return_first.cat_tamil_name;
                }
                if (name2 != '') {
                    var name1val = '<span style="color:#000">(' + name1 + '</span>';
                    var name2val = '<span style="color:#000"> , ' + name2 + ')</span>';
                    var cat_val = '<p style="color:#000;font-size:13px">' + catname + '</p>';
                } else {
                    name1val = '<span style="color:#000">(' + name1 + ')</span>';
                    name2val = '';
                    cat_val = '<p style="color:#000;font-size:13px">' + catname + '</p>';
                }
                var godvals = '<p >' + godval + '</p>';
                $(this).closest(".named").find(".amt_name").html(name1val + name2val + cat_val + godvals);
            }

        });

        if (cnt > 0) {
            $('.input-1, .input-2, .input-3, .input-4').val('');
            //notify('Names are Applied!', 1500, 'info');
        }

        setTimeout(function () {
            $('#amt-grid .naming').removeClass('naming');


        }, 2000);
    });
    
	$(document).on("click", ".amt-row", function () {
        var names = $(this).attr("data-names");
//        alert(names.toString());
        var splitvalues = names.split('],');
        var splitvaluesname1 = splitvalues[0].split(',');
        if (typeof splitvalues[1] != 'undefined') {
            var splitvaluesname2 = splitvalues[1].split(',');
        } else {
            splitvaluesname2 = '';
        }
        var splitlan1 = isTamil ? 'TAM' : 'ENG';
        var splitname1 = splitvaluesname1[0].split(splitlan1);
        if (splitvaluesname2 != '') {
            var splitname2 = splitvaluesname2[0].split(splitlan1);
        } else {
            splitname2 = '';
        }

        if (typeof splitvaluesname2[1] != 'undefined') {
            var star2split = splitvaluesname2[1].split("]]");
            var star2 = (star2split[0].replace(/["']/g, ""));
        } else {
            star2 = '';
        }
        if (splitname2 != '') {
            var name2 = (splitname2[1].replace(/["']/g, ""));
        } else {
            name2 = '';
        }
        var name1 = (splitname1[1].replace(/["']/g, ""));
        if (typeof splitvaluesname1[1] != 'undefined') {
            var star1split = splitvaluesname1[1].split("]]");
            var star1 = (star1split[0].replace(/["']/g, ""));
        } else {
            star1 = '';
        }
        $('.input_name:first').val(name1);
        $('.input-3').val(name2);
        $('.star:first option').each(function () {
            if ($(this).val() == star1) { // EDITED THIS LINE
                $(this).prop("selected", "selected");
            }
        });
        $('.input-4 option').each(function () {
            if ($(this).val() == star2) { // EDITED THIS LINE
                $(this).prop("selected", "selected");
            }
        });
//        var name1 = (isTamil) ? ($('.input_name:first').val() || "") : ($('.name:first').val() || "");
    });
	
    $(document).on('click', '#gods-dialog .cell, #with-name-dialog .cell', function(){
        if( isScan ) {
            var $parent = $(this).parent().closest('.dialog')
            ,   len     = $parent.find('.chk').length
            ,   isNameDialg = $parent.attr('id') == 'with-name-dialog' ? true : false;
                
            if( $(this).hasClass('active') ) {
                --len;
                $(this).find('.chk').remove();
                $(this).removeClass('active');
            }else {
                
                if( isNameDialg && len >= 2 ) {
                    notify("Maximum 2 members are allowed!");
                    return false;
                }
                
                ++len;
                $(this).prepend('<i class="fa fa-check chk"></i>');
                $(this).addClass('active');
            }  
            
            if( isNameDialg ) {
                if( len > 0 ) {
                    $('#with-name-dialog .clse-btn').html('&nbsp; Ok&nbsp;').addClass('active');
                }else {
                    $('#with-name-dialog .clse-btn').html('Skip').removeClass('active');
                }
            }
            
            $('.notify-box').remove();
        }else {
            $(this).toggleClass('active');
        }
        
       msgBox();
    });
    
    $('#gods-dialog .ok-btn').on('click', function(){
        if( $('#gods-dialog .cell.active').length == 0 ) {
            msgBox('Please choose atleast one god');
            return false;
        }else {
            // Ok
            var gods = '';
            $('#gods-dialog .cell.active').each(function(){
                gods += $(this).attr('data-id') + ',';
            })
            gods = gods.substring(0, gods.length-1);
            
            if( isScan ) {
                $('#gods-dialog .title .clse-btn').trigger('click');
            }else {
                dialog( $('#gods-dialog'), true );
            }
            
            $('.item-cell.active').attr('data-gods', gods).trigger('click');
        }
        
    })
    
    $('.cat-blck').on('click', function(){
        
        var $this = $(this)
        ,   clr   = $this.attr('data-clr') || ""  
        ,   sclr = clr.split('`')
        ,   data = {
            act     : 'cat-items',
            catId   : $this.attr('data-id'),
        };
        
        
        $.post( baseURL + controller + '/ajax/', data, function(results){
            results = JSON.parse(results);
            var html = '';
                
            if( results != '' ) {    
                
                var html = '<ul class="bxslider" id="item-bxslider"><li>'
                    ,   len = results.length
                    ,   lmt = isScan ? 10 : 15
                    ,   step = len < lmt ? len : lmt;
                    
                   
                    for(var x = 1; x <= len; x++ ) {
                        //Object.keys(results).map(function(i, iK){
                            var item    = results[x-1]
                            ,   price   = item['date_price'] != null ? item['date_price'] : item['price'];

                            html += '<div class="item-cell id-'+x+' archanai_list_div" data-id="'+ item['cat_id'] +'-'+ item['item_id'] +'-'+ item['grouping'] +'-'+ item['god_name'] +'-'+ item['is_inventory'] +'-'+ item['inv_item_id'] +'-'+ item['avail_counter_qty'] +'-'+ item['receipt'] +'" data-price="'+ price +'" style="background: linear-gradient('+ sclr[0] +' 50%, '+ sclr[1] +' 50%);">';
                                html += '<div class="archanai_name_eng">'+ item['name'] +'</div>';
                                html += '<div class="event_middle">';
                                
                                if( item['image'] != '' ) {
                                    html += '<span class="event_icon cat-ico" style="background: #f5fb85; border-radius: 0px 5px 5px 0px;">';
                                    html += '<img src="'+ baseURL + '' + item['image'] +'" style="width: 100%;  height: 100%;">';
                                }else {
                                    html += '<span class="event_icon cat-ico">';
                                }
                                
                                html += '</span>';
                                html += '<span class="event_amount">$'+price+'</span>';
                                html += '</div>';
                                html += '<div class="archanai_name_tm">'+ item['tamil_name'] +'</div>';
                    
                            html += '</div>';
                        //});    
                        
                        /*if( x % step == 0 ) {
                            html = '<div class="owl-item">'+html+'</div>';
                            
                            $owl.trigger('add.owl.carousel', [$(html), 0]).trigger('refresh.owl.carousel');
                            
                            $('#plot .owl-item.dummy').remove();
                            
                            html = '';
                        }*/
                        
                        
                        /*if( ++i > 1 ) {
                            i = 0;
                        }*/
                        
                        html += ( x % step == 0 ) ? ((x == len) ? '</li>' : '</li><li>') : '';
                       // html += ( x % step == 0 ) ? '</li><li>' : '';
                    }
                    
                    html += '</li></ul>';
                    
                    config.pager = true;
                    
                    $('#plot > div').html(html);
                    $('#item-bxslider').bxSlider(config);//.reloadSlider();
                    
                    
                    //if( x <= len ) {html += '</div>';}
                    
                   // $owl.trigger('add.owl.carousel', [$(html), 10]).trigger('refresh.owl.carousel');
                   
                    //$('#plot .owl-item.dummy, #plot .owl-item:last').remove();
                    
                    /*
                
                for( z = 0; z < 3; z++ ) {
                    var html = '<div class="owl-item">'; 
                
                    for( x = 0; x < 10; x++ ) {
                    Object.keys(results).map(function(i, iK){
                        var item    = results[i]
                        ,   price   = item['date_price'] != null ? item['date_price'] : item['price'];

                        html += '<div class="item-cell archanai_list_div" data-id="'+ item['cat_id'] +'-'+ item['item_id'] +'" data-price="'+ price +'">';
                            html += '<div class="archanai_name_eng">'+ item['name'] +'</div>';
                            html += '<div class="event_middle">';
                            html += '<span class="event_icon cat-ico"><img src="'+ baseURL + '' + itemImgDir +''+ item['image'] +'" style="width: 100%;  height: 100%;"></span>';
                            html += '<span class="event_amount">$'+price+'</span>';
                            html += '</div>';
                            html += '<div class="archanai_name_tm">'+ item['tamil_name'] +'</div>';
                        html += '</div>';

                        //html += '<div class="item owl-item"><h4>'+(++$('.item').length)+'</h4></div>';
                    });    
                    }
                    
                    html += '</div>';
                    owl.trigger('add.owl.carousel', [$(html), 0]).trigger('refresh.owl.carousel');
                }*/
                
                /*var $owlItem = $('#plot .owl-carousel .owl-item:first');
                $owl.find('.nav-owl').css({'margin-top': ($owlItem.height()/2-30)+'px'});*/
                
                if( !isScan ) {
                    $('#num-pad .num-cell .rm-btn').each(function(){
                        $(this).trigger('click');
                    });
                }
                
                
            }else {
                html = '<div class="no-results" style="margin: 55px auto; width: 80%; ">Sorry, No results found!</div>';
                if( !isScan ) {
                    $('#num-pad').slideUp('slow', function(){
                        $('#num-pad .num-cell .rm-btn').each(function(){
                           $(this).trigger('click');
                       });
                    });
                }
                $('#plot > div').html(html);
            }    
            
            $('#plot h1').html( (isTamil ? $this.find('.event_name_tm').text() : $this.attr('data-name')) ).attr( 'data-lang', ( isTamil ? $this.attr('data-name') :  $this.find('.event_name_tm').text() )  ).css({color: (sclr[0] != '' ? sclr[0] : '#a01c1c')});
                
            setFont();    
            
        });
        
    });
    
    $(document).on('click', '.item-cell', function(){
        var $this   = $(this)
        ,   price   = parseFloat( $this.attr('data-price') ) || 0 
        ,   dataId  = $this.attr('data-id') 
        ,   name    = $this.find('.archanai_name_eng').text()
        ,   tamilName = $this.find('.archanai_name_tm').text()
        ,   $amtRow = $('#amt-'+dataId)
        ,   isAct   = !$this.hasClass('active') ? true : false
        ,   gods    = ''
        ,   names   = [];
        
        
        $('.item-cell, #amt-grid .amt-row').removeClass('active');
        $(this).addClass('active');
        
        if($('.item-cell.active').length > 0) {
            $('.notify-box.notify-x').remove();
            
            var s = dataId.split('-')
            ,   isInvQty   = s[4] == '1' && s[5] != null ? true : false;
            
            
            if( isInvQty && parseInt(s[6]) == 0 ) {
                notify('Sorry, Temporarily out of stock!', 2500, 'err', 'x');
                return false;
            }else if( isScan && s[7] == '1' && !$this.hasClass('names-setted') ) {
                // With Name
                if( $this.hasClass('set') ) { 
                     
                    $this.removeClass('set');
                    $this.addClass('names-setted');
                }else {
                    $('#with-name-dialog .chk').remove();
                    $('#with-name-dialog .cell.active').removeClass('active');
                    $('#with-name-dialog .clse-btn').html('Skip').removeClass('active');
                    $('#sliders').fadeOut(500, function(){
                        $('#with-name-dialog').fadeIn('slow', function(){
                            $this.addClass('set');
                        });
                    });
                    return false;
                }
            }
            
            if( s[3] == '1' ){
                // With God Name
                
                //if( !$this.hasClass('gods-setted') ) { 
                    $('#num-pad').slideUp('slow');
                    if( $this.hasClass('set') ) { 
                        gods = $this.attr('data-gods');
                        $this.removeClass('set');
                        $this.addClass('gods-setted');
                    }else {
                        // Show Gods Dialog
                        
                        $this.addClass('set');
                        $('#gods-dialog .cell.active').removeClass('active');
                        
                        if( isScan ) {
                            $('#gods-dialog .chk').remove();
                            $('#sliders').fadeOut(0, function(){
                                $('#gods-dialog').fadeIn('slow', function(){
                                    if( !$(this).hasClass('loaded') ) {
                                        $(this).addClass('loaded');
                                        $('#gods-bxslider').bxSlider(config);
                                    }
                               });
                            });
                        }else {
                            var gds = $('#amt-'+dataId).attr('data-gods') || "";
                            if( gds != "" ) {
                                var ss = gds.split(',');
                                for( var i = 0; i < ss.length; i++ ) {
                                    $('#gods-dialog .cell[data-id="'+ss[i]+'"]').addClass('active');
                                }
                            }
                            
                            dialog( $('#gods-dialog') );
                        }

                        return false;
                    }
                //}
            }else {
                $this.removeAttr('data-gods');
                $('#num-pad').slideDown('slow');
            }
            
            if( $this.hasClass('names-setted') ) {
                $('#with-name-dialog .plot .cell.active').each(function(){
                    var mem = JSON.parse($(this).attr('data-details')) || "";
                    if( mem != '' ) {
                        names.push([
                            isTamil ? 'TAM'+mem['tamil_name'] : 'ENG'+mem['name'],
                            mem['star_id']
                        ]);
                    }
                });
            }
            
            $('#sliders').fadeIn('slow');
            $this.removeClass('gods-setted names-setted');
            
        }else if( !isScan ) {
             $('#num-pad').slideUp('slow', function(){
                 $('#num-pad .num-cell .rm-btn').each(function(){
                    $(this).trigger('click');
                });
             });
        }
        
        var $grid  = $('#amt-grid')
        ,   qty = 1;
        
        if( gods != '' ) {
            qty = gods.split(",").length; 
        }/*else if( $amtRow.length != 0 && !isScan ) {
            qty = $amtRow.attr('data-qty') || 1;
            ++qty;
        }*/
        
        if( qty > 999 ) {
            return false;
        }else if( isScan ) {
            /*
             * Check Card Balance is available
             */
            var cardBal = parseFloat($('#avail-bal').text())
            ,   total   = parseFloat($('#total-amt').text());

            if( (total+(qty*price)) > cardBal ) {
                notify('Sorry, You don\'t have enough balance in your card! <span style="font-size: small;">(Avail. Bal: S$ '+ cardBal.toFixed(2) +')</span>', 15000, 'err', 'x');
                return false;
            }
        }
        
        if( isInvQty && qty > s[6] ) {
            notify('Maximum available quantity is :'+ s[6], 2500, 'warning', 'x');
            qty = s[6];

            // Reduce Gods
            if( gods != '' ) {
                
                var s   = gods.split(',')
                ,   gods= '';
                for( i = 0; i < qty; i++ ) {
                    gods += s[i]+',';
                }
                gods = gods.substring(0, gods.length-1);
            }
        }
        
        //if( $amtRow.length == 0 || isScan ) {
           
            var rowAttr = 'id="amt'+ $amtRow.length +'-'+dataId+'" data-qty="'+ qty +'" data-price="'+price+'" data-gods="'+ gods +'" data-names=\''+ JSON.stringify( names ) +'\' class="amt-row active ';
            if( isScan ) {
                $grid.find('.no-results').remove();
                var len    = $grid.find('tr').length
                ,   html = '<tr '+ rowAttr +' " >';
                    html +=     '<td class="rm-btn center"><i class="fa fa-times"></i> <span>'+ (len+1) +'</span></td>';
                    html +=     '<td>'+ name +'</td>';
                    html +=     '<td class="center amt-qty" data-price="'+ (qty*price).toFixed(2) +'">'+ qty +'</td>';
                    html +=     '<td class="right price">'+ price.toFixed(2) +'</td>';
                    html += '</tr>';
            }else {
            
                var html = '<div '+ rowAttr +' amt_strip1" >';
                    html +=     '<span class="rm-btn"><i class="fa fa-times"></i></span>';
                    //html +=     '<span class="amt-qty">1</span>';
                    html +=     '<span class="amt_name" data-lang="'+( isTamil ? name : tamilName )+'">'+ ( isTamil ? tamilName : name ) +'</span>';
                    html +=     '<span class="amt-qty amt_txt" data-price="'+ ( (qty*price).toFixed(2) ) +'">'+qty+'</span>';
                    html += '</div>';
            }
            
            $grid.append(html);
            
            setFont();
        
        /*}else {
           
            $amtRow.attr('data-qty', qty).attr('data-gods', gods);
            //$amtRow.find('.amt-qty').html(qty);
            $amtRow.find('.amt-qty').attr('data-price', (qty*price).toFixed(2)).html(qty);
            
            $amtRow.addClass('active');
        }*/
        
        setTotal();
        
    });
    
    $(document).on('click', '#amt-grid .rm-btn', function(){
        
        if( isScan ) {
            $(this).parent().closest('tr').fadeOut('slow', function(){
                $(this).remove();
                setTotal();

                // Set Serial No
                var sNo = 0;
                $('.item_list_table tbody .rm-btn').each(function(){
                    $(this).find('span').html(++sNo);
                });

                if( sNo == 0 ) {
                    // Show Dummy
                    var html = '<tr class="no-results">';
                        html += '<td>&nbsp;</td><td class="no-records">No Records</td><td>&nbsp;</td><td>&nbsp;</td>';
                        html += '</tr>';
                    $('.item_list_table tbody').append(html);    
                }

            });
        }else {
            
            var $amtRow = $(this).parent().closest('.amt-row');
            $amtRow.slideUp('slow', function(){
                $(this).remove();
                $('.item-cell, #amt-grid .amt-row').removeClass('active');
                $('#num-pad').slideUp('slow', function(){
                    $('#num-pad .num-cell .rm-btn').each(function(){
                       $(this).trigger('click');
                   });
                });
                setTotal();

            });
        }
        
    });
    
    $('#amt-section .amt_close').on('click', function(){
        $('#amt-grid .rm-btn').each(function(i){
            $(this).trigger('click');
        })
        
    })
    
    $('#num-ok-btn > div:first').on('click', function(){
        var pickQty  = parseInt( $('#num-ok-btn').attr('data-value') ) || 0;
        
        $('#num-pad').slideUp('slow', function(){
            $('#num-pad .num-cell .rm-btn').each(function(){
               $(this).trigger('click');
           });
        });
        
        if( pickQty > 0 ) {
            var   $itemCell = $('.item-cell.active')
            ,   dataId    = $itemCell.attr('data-id')
            ,   $amtRow   = $('.amt-row.active') //$('#amt-'+dataId)
            ,   prevQty   = 0;//parseInt( $amtRow.attr('data-qty') ) || "";  
            
            if( $amtRow.length == 0 ) {
                return false;
            }
       
            var s       = dataId.split('-')
            ,   totalQty = (pickQty + prevQty)
            ,   price = $itemCell.attr('data-price') || 0
            ,   isInvQty   = s[4] == '1' && s[6] != null ? true : false;  
            
            if( isInvQty && totalQty > s[6] ) {
                if( parseInt(s[6]) == 0 ) {
                    notify('Sorry, This item is not available right now!', 2500, 'err', 'x');
                    return false;
                }else {
                    notify('Maximum available quantity is :'+ s[6], 2500, 'warning', 'x');
                }
                totalQty = s[6];
            }
            
            $amtRow.attr('data-qty', totalQty);
            //$amtRow.find('.amt-qty').html(totalQty);
            $amtRow.find('.amt-qty').attr('data-price', (totalQty*price).toFixed(2)).html(totalQty);
            
            setTotal();
        }
        
        var text  = $('#num-ok-btn').attr('data-value') || "";
        if( $('#num-pad .num-cell .rm-btn').length == 1 && text.length > 1 ) {
            // All characters are same
            text = '';
            $('.num-cell.active .rm-btn').remove();
            $('.num-cell.active').removeClass('active');
            
            $('#num-ok-btn').attr('data-value', text);
            $('#num-ok-btn > div:nth-child(2)').html(text);
        }else {
            $('#num-pad .num-cell .rm-btn').each(function(){
                $(this).trigger('click');
            });
        }
        
    });
    
    $(document).on('click', '#num-pad .num-cell .rm-btn', function(){
        var text    = ''
        ,   $parent = $(this).parent().closest('.num-cell')
        ,   value = $parent.attr('data-value') 
        ,   text  = $('#num-ok-btn').attr('data-value') || "";
        
        //alert(text);
        var lstIndx = text.lastIndexOf(value);
        text = text.substring(0, lstIndx)+text.substring(lstIndx+1, text.length);
        
        var intText = parseInt(text);
        if( text.indexOf( value ) == -1 || intText <= 0 ) {
            
            $(this).remove();
            $parent.removeClass('active');
            
            if(intText <= 0) {
                // Empty..
                text = '';
                $('.num-cell.active .rm-btn').remove();
                $('.num-cell.active').removeClass('active');
            }
        }
        
        $('#num-ok-btn').attr('data-value', text);
        $('#num-ok-btn > div:nth-child(2)').html(text);
        
    });
    
    $('#num-pad .num-cell .add-btn').on('click', function(){
        
        var $parent = $(this).parent().closest('.num-cell')
        ,   value = $parent.attr('data-value') 
        ,   text  = $('#num-ok-btn').attr('data-value') || ""
        ,   isAct = !$parent.hasClass('active') ? true : false;

        // Add
        text += ''+value;
        
        var intText = parseInt( text );
        if( intText > 999 || intText <= 0 ) {
            return false;
        }
        
        if( isAct ) {    
            $parent.addClass('active');
            $parent.prepend('<div class="rm-btn">X</div>');
        }
        
        $('#num-ok-btn').attr('data-value', text);
        $('#num-ok-btn > div:nth-child(2)').html(text);
        
        
    })
    
    
    /*$('#name-sec').on('click', function(){
        copy(true);
        dialog($('#name-sec-dialog'));
    });
    
    
    
    $(document).on('click', '#name-sec-dialog .save-btn', function(){
        var $parent = $(this).parent().closest('.dialog');
        
        //$('#name-sec').html($('#name-sec-dialog .cloned').clone());
        copy();
        
        dialog($parent, true);
        
    });*/
	
	$('#balance-btn').on('click', function(){
		var paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
        ,   payAmt  = parseFloat($('[name="pay_amount"]').val()) || 0;
        
        // Go to payment
        if( payAmt <= 0 ) {
            msgBox('Please choose the Archanai!');
            return false;
        }else{
			var msg = '';	
			
			if( msg != '' ) {
                msgBox(msg);
                dialog($('#name-sec-dialog'));
                return false;
            }
            
            $('#remaining-dialog .pay-type:first, [name="paid_amount"]').val($('#to-pay').val());
           
		    dialog($('#remaining-dialog'));
			
			$('#received_amt').val("");
			$('#balance_amt').val("");
		}
	});
    
    $('#payment-btn').on('click', function(){
                
        var paidAmt = parseFloat( $('[name="paid_amount"]').val()) || 0
        ,   payAmt  = parseFloat($('[name="pay_amount"]').val()) || 0;
        
        // Go to payment
        if( payAmt <= 0 ) {
            msgBox('Please choose the Archanai!');
            return false;
        }else {
            // Validate Names
            var msg = ''
            /*# NOT Needed
             * ------------------
             * for(i=1; i<=6; i++) {
                var value = $('#i-'+i).val();
                if( value == '' ) {
                    if( i % 2 != 0 ) {
                        // Name
                        msg = 'Please enter the Name';
                    }else {
                        msg = 'Please choose the Star';
                    }
                    break;
                }
            }*/
            
            if( msg != '' ) {
                msgBox(msg);
                dialog($('#name-sec-dialog'));
                return false;
            }
            
            $('#ptypes-dialog .pay-type:first, [name="paid_amount"]').val($('#to-pay').val());
            dialog($('#ptypes-dialog'));
            
            
        }
        
    });
    
    /*$('.tender-btn').click(function() {
        $('#amt-grid .amt-row').each(function(ik, iv){
            var id = $(this).attr('id');
            var s = $(this).attr('id').split('-');
             ,   obj = {
                        'catId' : s[1],
                        'itemId': s[2],
                        'grouping': s[3],
                        'qty'   : $(this).attr('data-qty'),
                        'price' : $(this).attr('data-price'),
                    };
                    
                    data.items.push(obj); 
        });
    });*/
    
    $('.sbmt-btn').on('click', function(event) {
        // Check Amount
        
		event.stopImmediatePropagation();
		
		
		if($('#paybutton').is('[disabled=disabled]')){ $('#paybutton').removeAttr('disabled'); } else {
			$('#paybutton').attr('disabled', 'disabled');
		}
		
		if($('#pybtn').is('[style="display:none"]')){ $('#pybtn').removeAttr('style'); } else {
			$('#pybtn').attr('style', 'display:none');
		} 
		
        var isTender 	= $(this).hasClass('tender-btn') ? true : false
        ,	isBalance 	= $(this).hasClass('balance-btn-sub') ? true : false
        ,	paidAmt 	= parseFloat( $('[name="paid_amount"]').val()) || 0
        ,   payAmt  	= parseFloat($('[name="pay_amount"]').val()) || 0;
        //console.log("isBalance: "+isBalance);
		//return false;
        // Go to payment
        if( payAmt <= 0 ) {
			$('#paybutton').removeAttr('disabled'); $('#pybtn').removeAttr('style');
            msgBox('Please choose the Archanai!');
            return false;
        }else{
            
            // Check is Card Balance
            if( isScan ) {
                // Pay Using Card
                isTender = false;
                paidAmt = parseFloat($('#avail-bal').text());
                
                if( paidAmt < payAmt ) {
                    msgBox('Sorry, You don\'t have enough balance in your card!');
                    return false;
                }
            }
            
            if( paidAmt == payAmt || isTender || isScan ) {
                // Ok
                /*var namedLen = $('#amt-grid .amt-row.named').length;
                console.log('Named Len: '+namedLen);
                if( namedLen > 0 && $('#amt-grid .amt-row').length !=  namedLen ) {
                    console.log('Named Incl: '+ $('#amt-grid .amt-row').length);
                    
                    $('#apply-names-btn').addClass('trigger-submit').trigger('click');
                    return false;
                }*/
                
                var msg = ''
                ,   data = {
                    'act'   : 'submit',
                    'isTender' : isTender,
                    'isTamil' : isTamil || false,
                    'items' : [],
                    'payments': [],
                    'contact_no': $('#devotee_contact').val()
                };
                
                if( isScan ) {
                    data.isScan     = true;
                    data.payId      = $('#pay-id').val();
                    data.cardDetails = {
                        mem_id      : $('#mem-id').val() || "",
                        name        : $('#mem-name').val(),
                        card_no     : $('#mem-card-no').val(),
                        amount      : paidAmt,
                    }
                    
                }
                
                for(i=1; i<=6; i++) {
                    var value = $('#i-'+i).val();
                    if( value == '' ) {
                        /*if( i % 2 != 0 ) {
                            // Name
                            msg = 'Please enter the Name';
                        }else {
                            msg = 'Please choose the Star';
                        }
                        break;*/
                    }else {
                        value = i % 2 != 0 ? ( isTamil ? 'TAM' : 'ENG' ) + value : value;
                        data['input_'+i] = value;
                    }
                }

                if( msg != '' ) {
                    msgBox(msg);
                    dialog($('#ptypes-dialog'), true);
                    return false;
                }else {

                    $('#amt-grid .amt-row').each(function(ik, iv){
                        var id = $(this).attr('id');
                        var s = $(this).attr('id').split('-')
                        ,   obj = {
                            'catId' : s[1],     // Index is
                            'itemId': s[2],     //* GREATER than one
                            'grouping': s[3],    //* ...
                            'isInventory' : s[5], // Because id starts by id="amt-x-x-x-x-x-" */
                            'invItemId' : s[6],

                            'qty'   : $(this).attr('data-qty'),
                            'price' : $(this).attr('data-price'),
                            'gods'  : $(this).attr('data-gods') || "",
                            'names' : $(this).attr('data-names') || "",

                        };



                        data.items.push(obj);
                    }); 

                    if( !isBalance ) {
						//console.log("isPayment");
                        $('#ptypes-dialog .pay-type').each(function(){
                            var value = $(this).val() || "";

                            if( value != '' ) {
                                var $parent = $(this).parent().closest('.ptype-box')  
                                ,   idd   = $parent.attr('id') || ""
                                ,   details = {}
                                ,   member = {};

                                if( idd == 'ptype-box-cheque' ) {
                                    // Cheque Details
                                    details.name = $('[name="chq_bnk_name"]').val();
                                    details.no   = $('[name="chq_no"]').val();
                                    details.date = $('[name="chq_date"]').val();
                                }

                                if( idd == 'ptype-box-membership-card' ) {
                                    // Membership Card Details
                                    member.card_no = $('[name="card_no"]').val();
                                    member.name   = $('[name="card_name"]').val();
                                    member.amount = $('[name="card_amount"]').val();
                                    member.mem_id = $('[name="mem_id"]').val();
                                }

                                data.payments.push({
                                    'id'    : $(this).attr('data-id'),
                                    'val'   : $(this).val(),
                                    'details': details,
                                    'member': member,
                                });
                            }
                        });
                    }
					
					if( isBalance ) {
						console.log("isBalance");
						$('#remaining-dialog .pay-type').each(function(){
                            var value = $(this).val() || "";
							console.log(value);
                            if( value != '' ) {
                                var $parent = $(this).parent().closest('.ptype-box')  
                                ,   idd   = $parent.attr('id') || ""
                                ,   details = {}
                                ,   member = {};

                                data.payments.push({
                                    'id'    : $(this).attr('data-id'),
                                    'val'   : $(this).val(),
                                    'details': details,
                                    'member': member,
                                });
                            }
                        })
                    }

                    $('.sbmt-btn').attr('disabled', 'disabled');    
                    ///msgBox('Submitting ...', -1, 'info');
                    
                    notify("Submitting ...", -1, 'info', 'x');
                    $.post(baseURL + controller + '/ajax' , data , function(results){
                        $('.sbmt-btn').removeAttr('disabled');

                        results = JSON.parse(results);
                        //notify("Submitted", '', 'success');

                        //if( results != '' && results != '`' ) {
                            //var s = results.split('`');
                            /*msgBox('Archanai is created..<div>Please note the following Ref. No: <b>"'+s[0]+'"</b></div>', -1, 'success');
                            $('.msg-box .clse-btn').attr('onclick', 'javascript: window.location.reload();');
                            $('#ptypes-dialog .modal-content, #main-content').fadeOut('slow'); */
                            /*setTimeout(function(){
                                window.location.reload();
                            }, 5000);*/

                            //printRec(results);
                            //window.setTimeout(function(){
                            //notify("For testing purpose, disabled reload ", -1, 'info');
                            if( isScan ) {
                                window.location.href = $('.logout-btn:first').attr('href');
                            }else {
                                window.location.reload();
                            }
                            //}, 1000);

                        /*}else {
                            msgBox('Something went wrong..');
                        }*/


                    });

                }

            }else {
                var msg = 'Amount doesn\'t matched';
                msgBox(msg);
            }
        }
        
        return false;
        
        
        
    })
	
	$('#received_amt').on('keypress, keydown, keyup', function(){
		var rec_amt 	= $(this).val();
		var paid_amt	= $('#to-pay').val();
		var bala_amt	= "";
		
		bala_amt		= parseFloat(rec_amt) - parseFloat(paid_amt);
		
		$('#balance_amt').val(bala_amt.toFixed(2));
	});
    
    $('.lang-switch-btn').on('click', function(){
        if( $('.lang-switch-btn').hasClass('active') ) {
            // Eng
            $('.input_name').addClass('name').removeClass('input-tamil tamil-name');
        }else {
            // Tamil
            $('.input_name').removeClass('name').addClass('tamil-name');
        }
    
    });
    
    
    var html = '<div class="ctrls">';
        html += '<div class="btn primary save-btn"><i class="fa fa-check"></i> Ok</div>';
        html += '<div class="btn clse-btn"><i class="fa fa-times"></i> Cancel</div>';
        html += '</div>';            
                    
    /*#$('#name-sec-dialog').html($('#name-sec').clone()).prepend(html);
    $('#name-sec-dialog').find('#name-sec').removeAttr('id').addClass('cloned');
    $('#name-sec-dialog input').addClass('keyboard');*/
    $('#name-sec input').addClass('keyboard');
    
    /*#$('#name-sec-dialog .clse-btn').on('click', function(){
        $('#name-sec .input_set select, #name-sec .input_set select option').show();
    })*/
    
    if( isScan ) {
        
        /*
         * Numpad
         */
        
        $('.keypad.cell').on('click', function(){
            var code = $(this).find('.keypad_txt').text();

            if( $(this).hasClass('clr-btn') ) {
                // Clear
                for( var i = $('.pwd_bullet').length-1; i >= 0; i-- ) {
                    var $bull = $('.pwd_bullet:eq('+i+')');
                    if( $bull.val() != '' ) {
                        $bull.val('');
                        return false;
                    }
                }

            }else if( $(this).hasClass('ok-btn') ) {
                // Submit
                
                if( $('.pwd_bullet:invalid').length > 0 ) {
                    msgBox("Please enter the full password");
                    return false;
                }else {

                    var passcode = ''
                    ,   isLogin = $('#login-wrap').length > 0 ? true : false;
                    
                    $('.pwd_bullet').each(function(){
                        passcode += $(this).val();
                    });
                    
                    if( !isLogin ) {
                        
                        if( $('#change-pass-dialog').hasClass('confirmed') ) {
                            // Match
                            var newPass = $('#change-pass-dialog').attr('data-pass') || "";
                            if( passcode != newPass ) {
                                $('.pwd_bullet').val('');
                                $('#change-pass-dialog').removeClass('confirmed').removeAttr('data-pass');
                                $('#change-pass-dialog .lbl').html('New Password');
                                msgBox();
                                notify('Password(s) doesn\'t matched', '', '', 'x');
                                return false;
                            }
                            
                        }else {
                            // Show Confirm Password
                            $('.pwd_bullet').val('');
                            $('#change-pass-dialog').addClass('confirmed').attr('data-pass', passcode);
                            $('#change-pass-dialog .lbl').html('Confirm Password');
                            return false;
                        }
                        
                        
                    }
                    
                    var ajax = true   
                    ,   data = {
                        act     : 'scan',
                        type    : isLogin ? 'pass' : 'change',
                        id      : $('#mem-id').val(),
                        passcode: passcode,
                    };

                    window.setTimeout(function(){ if( ajax ) {
                        notify('Please wait ...', -1, 'info', 'x');
                    }}, 700);
                    
                    $.post( baseURL + 'billing_archanai/ajax/', data, function(results){
                        ajax    = false;
                        $('.notify-box').remove();
                        results = JSON.parse(results);
                        
                        if( isLogin ){
                            /*
                             * Login Page
                             */
                            if( results != '' ) { 
                                var msg = '';
                                if( results['errNo'] == '3' ) {
                                    $('.pwd_bullet').val('');
                                    msg = 'Password is incorrect!';
                                }

                                if( results['errNo'] == '0' ) {
                                    // Load Scan Archanai page
                                    window.location.href = baseURL + 'billing_archanai/scan/';

                                }else {
                                    msgBox(msg);
                                }
                            }
                        }else {
                            $('.pwd_bullet').val('');
                            $('#change-pass-dialog .clse-btn').trigger('click');
                            notify('Password is changed!', '', 'success');
                        }
                    });


                }

            }else {

                $('.pwd_bullet').each(function(){
                    if( $(this).val() == '' ) {
                        $(this).val(code);
                        return false;
                    }
                });
            }


        });
    }
    
    
    
});


function copy(isReverse, from, to) {
    var from = typeof from == 'undefined' ? '#name-sec-dialog' : from
    ,   to   = typeof to   == 'undefined' ? '#name-sec' : to
    ,   isReverse  = typeof isReverse == 'undefined' ? false : true;
    
    if( isReverse ) {
        var t = to;
        to = from;
        from = t;
        
        $('#name-sec .input_set select').hide();
        //$('#name-sec .input_set select, #name-sec .input_set select option').show();
    }else {
        $('#name-sec .input_set select, #name-sec .input_set select option').show();
    }
    
    
    
    for(var i = 1; i <= 6; i++) {
        $(to+' .input-'+i).val($(from + ' .input-'+i).val());
    }
}


function setTotal() {
    var total = 0;
    $('#amt-grid .amt-qty').each(function(){
        total += parseFloat($(this).attr('data-price'));
    })
    
    $('#total-amt').html(total.toFixed(2));
    $('#to-pay').val(total.toFixed(2));
}