/* 
* Author        : Jai K
* Purpose       : Script for Billing Settings
* Created On    : 2016-12-23 17:00
 */

function addAd(type, addNew){
    var k    = $('#'+type).attr('data-len');
    
    if( addNew ) {
        //
        var $row = $('#'+type+' table tbody .rw:first');
        $row.find('[name="'+type+'_chk['+ k +']"]').show().removeAttr('readonly');//.trigger('click');
        $row.find('.add-btn').removeClass('fa-plus add-btn').addClass('fa-times rm-btn');
        
        var $name = $row.find('.name')
        ,   name = $row.find('.name').val() || "";
        
        if( name == '' ) {
            $row.find('.name').val((type == 'ad' ? 'Advertisement ' : 'Event ' )+(k-1));
            
        }else if(type == 'event' && $row.find('[name="swap_inp_event_name-'+ k +'-"]').length == 0)  {
            
            if( name.substring(0, 3) == 'TAM' ) {
                // Tamil Text
                $name.addClass('input-tamil');
                $name.before('<input type="hidden" name="swap_inp_event_name-'+ k +'-" value="TAM">');
            }
            
            $name.val( name.substring(3) );
        }
        
    }
    
    $('#'+type).attr('data-len', ++k);
    // Append Empty row
    var html = '<tr class="rw">';
        html +=     '<td><input type="checkbox" name="'+ type +'_chk['+ k +']" checked readonly style="display: none;" /></td>';
        html +=     '<td><input type="text" class="name '+ ( type == 'event' ? 'inp-lang-swap' : '' ) +' " name="'+ type +'_name['+ k +']" placeholder="' + (type == 'event' ? 'Event Name' : '(Optional)') +'" value="" /></td>';
        
        if( type == 'ad' ) {
            html +=     '<td colspan="2"><input type="file" name="'+ type +'_file['+ k +']" value="" /></td>';
        }else if( type == 'event' ) {
            var d = new Date()
            ,   eventDate = getTwoDigits(d.getDate()) + '-' + getTwoDigits(d.getMonth()+1) + '-' + d.getFullYear();
            
            html += '<td><input type="text" class="date-picker" name="'+ type +'_start_date['+ k +']" value="'+ eventDate +'" placeholder="dd-mm-yyyy" /></td>';
            html += '<td><input type="text" class="date-picker" name="'+ type +'_end_date['+ k +']" value="'+ eventDate +'" placeholder="dd-mm-yyyy" /></td>';
            html += '<td><select class="form-control" name="'+ type +'_period['+ k +']"><option value="1">Morning</option><option value="2">Evening</option></select></td>';
        }
        html +=     '<td class="ctrls"><i class="fa fa-plus add-btn"></i> </td>';
        html += '</tr>';
        
    $('#'+type+' table tbody').prepend(html);
    $('.date-picker').bootstrapMaterialDatePicker({ time: false, format: 'DD-MM-YYYY'}).on('dateSelected', function(){
        $('.dtp-btn-ok').trigger('click');
    });;
    
}

function validate(){
    $('#ad [type="file"]').each(function(){
        if( $(this).val() != '' ) {
            var $parent = $(this).parent().closest('tr');
            if( $parent.find('.name').val() == '' ) {
                $parent.find('.name').val('Advertisement');
            }
        }
    });
    
    return true;
}

$(document).on('ready', function(){
        
        $(document).on('click', '.tiny-blck table .rm-btn', function(){
            var $this = $(this);
            
            if( window.confirm("Are you sure about to remove...?") ) {
                var $parent = $(this).parent().closest('tr');
                
                $parent.fadeOut('slow', function(){
                    var adId = $parent.find('.load-id').val() || "";
                    if( adId != '' ) {
                        var type = $parent.attr('id') || "ad";
                        if( type == 'ad' ) {
                            $('#ad tbody').prepend('<input type="hidden" name="ad_rm['+ adId +']" value="'+ $parent.find('.load-id').attr('data-src') +'" />');                            
                        }else {
                            if($('[name="rm_id"]').length == 0){
                                $('body').append('<input type="hidden" name="rm_id" value="" />');
                            }
                            
                            var rmId = $('[name="rm_id"]').val();
                            $('[name="rm_id"]').val( rmId + ','+adId );
                        }
                    }
                    
                    $(this).remove();
                })
            }
            
        });
        
        
        $(document).on('click', '.tiny-blck table .add-btn', function(){
            var type = $(this).parent().closest('.content').attr('id') || "ad";
            addAd(type, true);
        });
        
        
        
        //if( $('#ad tbody .rw').length == 0 ) {
            $('.tiny-blck table').each(function(){
                var type = $(this).parent().closest('.content').attr('id') || "ad";
                
                var len = $('#'+type).attr('data-len') || ++$('#'+type+' .rw').length;
                $('#'+type).attr('data-len', len);
                addAd(type);
            });
        //}
        
        var results = $('#ad tbody').attr('data-val') || "";
        if( results != '' ) {
            results = JSON.parse(results) || "";
                
            if( results != '' ) {
                var len = results.length
                ,   DIR = $('#ad tbody').attr('data-dir')
                ,   k     = 1  
                ,   inter = window.setInterval(function(){
                    --len;
                    ++k;
                    
                    if( len < 0 ) {
                        window.clearInterval( inter );
                        setEvents();
                        return false;
                    }
                    
                    var $row = $('#ad table tbody .rw:first')
                    ,   result = results[len];
                    
                    $row.find('[name="ad_name['+ k +']"]').val(result['name']);
                    
                    $row.find('[type="file"]').after('<img src="'+ baseURL + DIR + result['value'] +'" class="thumb-img" />');
                    $row.prepend('<input type="hidden" class="old-id" name="ad_old['+ k +']" value="'+ result['value'] +'" />');
                    $row.prepend('<input type="hidden" class="load-id" name="ad_id['+ k +']" value="'+ result['id'] +'" data-src="'+ result['value'] +'" />');
                    
                    
                    if( result['status'] == '1' ) {
                        $row.find('[name="ad_chk['+ k +']"]').prop('checked', true);
                    }else {
                        $row.find('[name="ad_chk['+ k +']"]').prop('checked', false);
                    }
                 
                    addAd('ad', true);
                }, 400);
            }
            
        }
        
        
        /** Event **/
        function setEvents(){
            
            var data = {
                act : 'events',
            };
            $.post( baseURL + controller +'/ajax/', data, function(results){
                results = JSON.parse(results) || "";
                    
                if( results != '' ) {
                    var len = results.length
                    ,   k     = 1  
                    ,   inter = window.setInterval(function(){
                        --len;
                        ++k;
                        if( len <= 0 ) {
                            window.clearInterval( inter );

                            /*$('#event [data-lang="TAM"]').each(function(){
                                $(this).trigger('focus');
                            });*/
                        }

                        var $row = $('#event table tbody .rw:first')
                        ,   result = results[len];

                        $row.find('[name="event_name['+ k +']"]').val(result['name']);
                        $row.prepend('<input type="hidden" class="load-id" name="event_id['+ k +']" value="'+ result['id'] +'" />');
                        $row.find('[name="event_period['+ k +']"]').val(result['value']);

                        // Set Start & End date
                        var d   = new Date( result['created_on'] );
                        $row.find('[name="event_start_date['+ k +']"]').val(getTwoDigits(d.getDate())+'-'+getTwoDigits(d.getMonth()+1)+'-'+d.getFullYear());

                        d   = new Date( result['updated_on'] );
                        $row.find('[name="event_end_date['+ k +']"]').val(getTwoDigits(d.getDate())+'-'+getTwoDigits(d.getMonth()+1)+'-'+d.getFullYear());

                        if( result['status'] == '1' ) {
                            $row.find('[name="event_chk['+ k +']"]').prop('checked', true);
                        }else {
                            $row.find('[name="event_chk['+ k +']"]').prop('checked', false);
                        }

                        addAd('event', true);
                    }, 400);
                }
                
            });
            
        } /** Event **/
        
        
        $(document).on('focus', '.inp-lang-swap', function(){
            var $this   = $(this)
            ,   name    = $(this).attr('name')
            ,   idd     = "swap_inp_"+name.replace('[', '-').replace(']', '-');
            
            $('.inp-lang-swap-icn').not('#'+idd).slideUp('slow');
            
            if( $('#'+idd).length == 0 ) {
                $(this).before('<div id="'+ idd +'" class="inp-lang-swap-icn" style="position: absolute;">E</div>');
                
                if( $this.hasClass('input-tamil') ) {
                    $('#'+idd).addClass('active').text('T');
                }else {
                    $(this).before('<input type="hidden" name="'+ idd +'" value="ENG" />');
                }
            }
            
            if( $this.attr('data-lang') == "TAM" ) {
                $this.removeAttr('data-lang');
                $('#'+idd).trigger('click');
            }
            
            if($('[data-lang]').length == 0) {
                $('#'+idd).slideDown('slow');
            }
        })
        
        $(document).on('click', '.inp-lang-swap-icn', function(){
            var id      = $(this).attr('id')
            ,   name    = id.replace("swap_inp_", "")
            ,   s       = name.split('-')
            ,   $inp    = $('[name="'+ ( s.length > 1 ? s[0]+'['+s[1]+']' : name ) +'"]');
                    
            if( $(this).hasClass('active') ) {
                // To ENG
                $(this).removeClass('active').text('E');
                $inp.removeClass('input-tamil').removeAttr('style');
                $('[name="'+id+'"]').val('ENG');
                
            }else {
                // To Tamil
                $(this).addClass('active').text('T');
                $inp.addClass('input-tamil');
                $('[name="'+id+'"]').val('TAM');
            }
            
            
        });
        
         $('[data-lang="TAM"]').each(function(){
            $(this).trigger('focus');
        });
        
        //$('input[type="checkbox"]').iCheck();
});


