/* 
 * Author       : Jai K
 * Purpose      : Script for Send SMS
 * Created On   : 2016-10-18 15:47
 */


function disable(toDisable) {
        var toDisable = typeof toDisable != 'undefined' ? toDisable : true;
        $('#sent-btn, [name="stypes"]').prop('disabled', toDisable);
}

function countChars(toHide) {
    
    var $this   = $('[name="msg"]')
    ,   len     = $this.val().length
    ,   $msg    = $this.parent().find('.cnt-msg');
    
    if( len > 0 && typeof toHide == 'undefined') {
        
        if( $msg.length == 0 ) {
            $this.after('<div class="cnt-msg">No. of characters: <span>0</span><span style="float: right;">Msg(s): <span>0</span></span></div>');
            $msg    = $this.parent().find('.cnt-msg');
        }
        
        $msg.find('>span:first').html(len);
        var msgCnt = Math.ceil(len/160);
        
        $msg.find('>span:nth-child(2) span').html(msgCnt < 10 ? '0'+msgCnt : msgCnt);
        if( msgCnt > 1 ) {
            $msg.addClass('warning').css({color: '#fff'});
        }else {
            $msg.removeClass('warning').css({color: '#999'});;
        }
        
        $msg.slideDown('slow');
    }else {
        $msg.slideUp('slow');
    }
    
    
}

$(document).on('ready', function(){
    countChars();
    
    $('[name="msg"]').on('keyup focus', function(){
        countChars();
    });
    
    $('[name="msg"]').on('blur', function(){
        countChars(false);
    });
    
    $(document).on('click', '.msg-box .clse-btn', function(){
        if( $('#sent-btn').hasClass('sending') ) {
            if( window.confirm("Do you want to cancel the current operation..? \n\nClick \"Cancel\" to send remaining ...") ){
                window.location.reload();
            }else {
                
                $('#sent-btn').trigger('click');
            }
            return false;
        }
    });
    
    $('#sent-btn').on('click', function(){
					
        var chkLen 	= $('.nos:checked').length
        ,	msg     = $('[name="msg"]').val()
        ,	totalToSent = $('#sent-btn').attr('data-to-sent') || ""
        ,	step 	= 40 // No. of msg to send at a time
        ,	isSending = $('#sent-btn').hasClass('sending') ? true : false;

        totalToSent = totalToSent != '' ? $('#sent-btn').attr('data-to-sent') : chkLen; 

        if( !isSending ) {
            if( $('[name="stypes"]').val() == '' ) {
                msgBox('Please choose the SMS type');
                scrollTo($('#multi-preview-stypes'));
                return false;
            }else if(chkLen == 0 ) {
                msgBox('Please choose atleast one contact no');
                return false;
            }else if(msg == '') {
                msgBox('Please enter the message');
                return false;
            }

            isSending = true;
            totalToSent = chkLen;
            $('#sent-btn').addClass('sending').attr('data-to-sent', totalToSent);
            
            scrollTo($('#cnt-blck'));    
            if( $('#cnt-blck .blck-content').is(':hidden') ) {
                $('#cnt-blck .sub-title').trigger('click');
            }
        }else {
                // Sending

            disable();
            $('.nos').not(':checked').parent().closest('div').remove();
        }


        $('#no-cnts').html(chkLen);

        var data = {
                'act'	: 'sent',
                'msg'	: msg,
                'nos'	: [],
        };

        for(var i = 0; i < step; i++ ) {
                var no = $('.nos:checked:eq('+i+')').addClass('sent').val();
                data.nos.push(no);

        }


        var sentNos = totalToSent - chkLen+step;

        //msgBox('<span id="sms-status-msg">Sending ...</span> ('+(sentNos >= 0 ? sentNos : totalToSent)+'/'+totalToSent+')<button id="sms-pause-btn" style="float: right; background: #f33; margin-right: 50px; min-width: 100px; border: none; height: 32px;">Pause</button>', -1, 'info');
        
        msgBox('<span id="sms-status-msg">Sending ...</span> ('+(sentNos >= 0 ? sentNos : totalToSent)+'/'+totalToSent+')<i id="sms-pause-btn" class="fa fa-pause"></i>', -1, 'info');
        $.post( baseURL + controller +'/ajax/', data, function(results){

                results = JSON.parse(results) || "";

                if( results.status == 'error' ) {
                        // Error
                        msgBox(results.msg, '-1');
                }else {
                        // Sent
                        var $sent = $('#plot .sent');
                        $sent.parent().closest('.cell').addClass('active');

                        if( $('#plot .cell.active:last').length > 0 ) {
                            var top = $('#plot .cell.active:last').offset().top
                            ,   extra = ($(window).height()/2) + $('.msg-box').height()+60;

                            if( top > extra ) {
                                $('html, body').animate({
                                        scrollTop: (top-extra)+'px'
                                }, 300);
                            }	
                        }

                        $sent.fadeOut(500);
                        window.setTimeout(function(){
                            
                            $sent.remove();	
                            var chkLen = $('.nos:checked').length;
                            if( isSending && chkLen == 0 ) {
                                    // All done
                                    disable(false);
                                    $('#sent-btn').removeClass('sending').removeAttr('data-to-sent');
                                    $('#no-cnts').html('0');
                                    /*var html = '<div class="status" style="width: 100%; box-shadow: none; border: none;">All are sent!</div>';
                                    $('#plot .status').remove()
                                    $('#plot').prepend(html);
                                    if( top > extra ) {
                                            $('#plot').append(html);
                                    }*/
                                    msgBox('All are sent!', -1, 'success');
                                    
                                    resetMultiSelect($('[name="multi-stypes"]').parent());
                                    //$('#sent-btn').removeClass('sending');

                                    //$('[name="stypes"]').val('');
                            }else if( chkLen > 0 && !$('#sms-pause-btn').hasClass('paused')){
                                    disable(false);
                                    $('#sent-btn').trigger('click');
                                    disable();	
                            }

                        }, 550);	

                }



        });			

    }); // Sent-btn
    
    $(document).on('click', '#sms-pause-btn', function(){
        if( $(this).hasClass('paused') ) {
            // Run
            $(this).removeClass('paused fa-play').addClass('fa-pause');//text('Pause');
            $('.msg-box').addClass('info').removeClass('warning');
            $('#sms-status-msg').html('Sending ...');
            $('#sent-btn').trigger('click');
        }else {
            // Pause
            $(this).addClass('paused fa-play').removeClass('fa-pause');//.text('Run');
            $('.msg-box').removeClass('info').addClass('warning');
            $('#sms-status-msg').html('Paused');
        }
    });
    
    $(document).on('ifClicked', '.nos', function(){
        var chkdLen = $('.nos:checked').length
        ,   total   = html = $('.nos').length;
        
        if( $(this).is(':checked') ) {
            --chkdLen;
        }else {
            ++chkdLen;
        }
        
        if( chkdLen != total ) {
            html = chkdLen+' / '+$('.nos').length;
        }
        
        $('#no-cnts').html(html);
    })
    
    $('#multi-stypes .fa.tick-ok').on('click', function(){
        var total = 0
        ,   html = 'Nothing is selected.'
        ,   value = $('[name="stypes"]').val() || "";
        
        if( value == '' ) {
            $('#plot').html(html);
            $('#no-cnts').attr('data-total', total).html(total);
            
            disable();
        }else {
            // Get Contacts
            var data = {
                'act'   : 'contacts',
                'value' : value,
                'from'  : $('#lmt-frm').val(),
                'to'    : $('#lmt-to').val(),
                'sort'  : $('#opt-sort').val(),
                'by'    : $('#opt-by').val(),
            }
            $.post( baseURL + controller +'/ajax/', data, function(results){
                results = JSON.parse(results) || "";
                
                if( results == '' ) {
                    html = 'None of the contact(s) found.';
                }else {
                    disable(false);
                    
                    html = '';
                    total = results.length;
                    //html += '<div class="col-md-12">';
                    //for( var c = 0; c < 92; c++ ) {
                    Object.keys(results).map(function(ik, iv){
                            var row = results[ik]; 
                            html += '<div class="cell">';
                            html += '<input type="checkbox" name="nos[]" class="nos" value="'+ row['bd_contact_no'] +'" checked>';
                            html += '<span>'+ row['bd_contact_no'] +'</span>';
                            html += '</div>';
                            
                            /*if( (ik+1) % 12 == 0 ) {
                                html += '</div><div class="col-md-12">';
                            }*/
                    })
                    //}
                    //html += '</div>';
                }
                
                $('#plot').html(html);
                $("input[type='checkbox'], input[type='radio']").iCheck({
                    checkboxClass: 'icheckbox_minimal',
                    radioClass: 'iradio_minimal'
                });
                
                $('#no-cnts').attr('data-total', total).html(total);
            });
        }
        
    });
});


