$(document).ready(function() {

    localStorage.removeItem('jarvisWidgets_settings_/app/leads/search/');
        
        // Modal Link
	$('#changeStatus').click(function() {
		var selected = $(".leadCB:checked").map(function(){
                                                          return $(this).val();
                                                        }).get();
        if(selected.length > 0) {
            $('#dialog_changeStatus').dialog('open');    
        } else {
            $.smallBox({
            	title : "לא נבחרו רשומות!",
            	//content : "<i class='fa fa-clock-o'></i> <i>2 seconds ago...</i>",
            	color : "#C46A69",
            	iconSmall : "fa fa-pointer bounce animated",
                timeout : 2500
            }); 
        }      
		return false;
	});

    $("#dialog_changeStatus").dialog({
		autoOpen : false,
		width : 300,
		resizable : true,
		modal : true,
		title : "<div class='widget-header'><h4><i class='fa fa-edit'></i> עדכון סטטוס</h4></div>",        
        buttons : [{
			html : "<i class='fa fa-edit'></i>&nbsp; שמירה",
			"class" : "btn btn-success",
			click : function() {
                if($('#statusSelect').val() == 'בחר סטטוס') {
                    $('#statusSelect').parent().addClass('has-error');
                    return false;    
                } else {
                    $('#statusSelect').parent().removeClass('has-error');
                    var data = {};
                    data.status = $('#statusSelect').val();
                    //data.leadId = leadId;
                    data.leadId = $(".leadCB:checked").map(function(){
                                                                  return $(this).val();
                                                                }).get().join();
                    $.post(root + 'app/leads/changeLeadsStatus', { 'data': data }, function(d) {
                        if(d.result){
                            window.location.reload();
                        }
                        if(!d.result) alert('פניה זו כבר משויכת ללקוח!');
                    }, 'json');
                    $(this).dialog("close");
                }   
			}
		}, {
			html : "<i class='fa fa-times'></i>&nbsp; ביטול",
			"class" : "btn btn-default",
			click : function() {
			    //$('.deliveryRow[rel="' + id + '"]').removeClass('highlightTD'); 
				$(this).dialog("close");
			}
		}]
	});

    // Modal Link
	$('#leadsToCampaign').click(function() {
	    var selected = $(".leadCB:checked").map(function(){
                                                          return $(this).val();
                                                        }).get();
        if(selected.length > 0) {
		  $('#dialog_editDelivery').dialog('open');
        } else {
            $.smallBox({
            	title : "לא נבחרו רשומות!",
            	//content : "<i class='fa fa-clock-o'></i> <i>2 seconds ago...</i>",
            	color : "#C46A69",
            	iconSmall : "fa fa-pointer bounce animated",
                timeout : 2500
            }); 
        }   
		return false;
	});

    $("#dialog_editDelivery").dialog({
		autoOpen : false,
		width : 300,
		resizable : true,
		modal : true,
		title : "<div class='widget-header'><h4><i class='fa fa-edit'></i> שיוך רשומות לקמפיין</h4></div>",
        buttons : [{
			html : "<i class='fa fa-check'></i>&nbsp; אישור",
			"class" : "btn btn-primary",
			click : function() {
                if($('#campaignSelect').val() == 'בחר קמפיין') {
                    $('#campaignSelect').parent().addClass('has-error');
                    return false;    
                } else {
                    $('#campaignSelect').parent().removeClass('has-error');
                    var data = {};
                    data.campaignId = $('#campaignSelect').val();
                    data.statusSelectQ = $('#statusSelectQ').val();
                    data.copyLeads = $('#copyLeadsCB').is(':checked');
                    //data.leadId = leadId;
                    data.leadId = $(".leadCB:checked").map(function(){
                                                                  return $(this).val();
                                                                }).get().join();                    
                    $.post(root + 'app/leads/addLeadToCampaign', { data: data }, function(d) {
                        if(d.result){
                            window.location.href = root + 'app/leads/search';
                        }
                        if(!d.result) alert('אירעה שגיאה!');
                    }, 'json');
                    $(this).dialog("close");
                }   
			}
		}, {
			html : "<i class='fa fa-times'></i>&nbsp; ביטול",
			"class" : "btn btn-default",
			click : function() {
			    //$('.deliveryRow[rel="' + id + '"]').removeClass('highlightTD'); 
				$(this).dialog("close");
			}
		}]
	});

  
    
    $('body').on('click', '#dt_basic1 tbody tr td:not(:first-child, :last-child)', function() {
        var id = $(this).parent().find('input.leadCB').val();
        //window.location.href = root + 'admin/leads/viewLead/' + id;
    });    
            /*
			$('ul.pagination li').on('click', function() {
			    alert($(this).find('a').text()); 
		        if($(this).hasClass('active')) localStorage.currentPage = $(this).find('a').text();
                console.log(localStorage.currentPage);    
			});
            */
                        
            var oTbl1 = $('#dt_basic1').dataTable({
                "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'f><'col-sm-6 col-xs-12 hidden-xs'l>r>"+
        				"t"+
        				"<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "processing": true,
                "deferRender": true,
                /*
                
                "serverSide": true,
                "ajax": {
                           "url": root + 'app/ajax/getDataForSearchTable',
                           "type": 'POST',
                           "data": function ( d ) {
                                    return $('#search-form').serialize();
                                    }
                       },
                */
                "bProcessing": true,
                "bDeferRender": true,
                "bStateSave": true,
                "fnStateSave": function (oSettings, oData) {
                    localStorage.setItem( 'DataTables_'+window.location.pathname, JSON.stringify(oData) );
                },
                "fnStateLoad": function (oSettings) {
                    return JSON.parse( localStorage.getItem('DataTables_'+window.location.pathname) );
                },
                "order": [[ 1, 'desc' ]], 
                "pagingType": "full_numbers",
                "lengthMenu": [ [10, 25, 50, 100, 500, 1000, 2000, -1], [10, 25, 50, 100, 500, 1000, 2000, "All"] ],
                "oLanguage": {
                    "sProcessing":   "מעבד...",
                    //"sLengthMenu":   "הצג _MENU_ פריטים",
                    "sZeroRecords":  "לא נמצאו רשומות מתאימות",
                    "sInfo": "_START_ עד _END_ מתוך _TOTAL_ רשומות" ,
                    "sInfoEmpty":    "0 עד 0 מתוך 0 רשומות",
                    "sInfoFiltered": "(מסונן מסך _MAX_  רשומות)",
                    "sInfoPostFix":  "",
                    //"sSearch":       "search",
                    "sUrl":          "",
                    "oPaginate": {
                        "sFirst":    "ראשון",
                        "sPrevious": "קודם",
                        "sNext":     "הבא",
                        "sLast":     "אחרון"
                    }
                },              
			});            
            $('input[aria-controls="dt_basic1"]').attr('placeholder', 'חיפוש...');

            $('#dt_basic1_info').css('float', 'left').parent().css('float', 'left');
            $('.dataTables_paginate ').parent().css('float', 'right');
            $('.dataTables_paginate ').css('text-align', 'right');
            /*
            $("input[data-status-filter]").on("click", function() {
	            var filters = getTypeFilters();
	            oTbl1.fnFilter(filters.join("|"), 7, false, false);
	        });
            */
    /*        
    //superbox select
    $('body').on('change', '.leadCB', function() {
        if($(this).is(":checked")) {
            $(this).parent().parent().addClass('leadRow_selected');
            $('#wid-id-1').show(500);
        } else {
            $(this).parent().parent().removeClass('leadRow_selected');
            //if($('.superbox').find('input.superbox_cb:checked').length == 0) $('#wid-id-0').hide(500);
        }
        if($('.leadCB:checked').length == 0) $('#wid-id-1').hide(500);
        //$('#textbox1').val($(this).is(':checked'));        
    });
    */
    $('body').on('click', '.selectAllCB', function () { 
        $('input[name="selectedLeads[]"]').prop('checked', true);
        $('input[name="selectedLeads[]"]').parent().parent().addClass('leadRow_selected');        
    });
    $('.unselectAllCB').on('click', function () { 
        $('input[name="selectedLeads[]"]').prop('checked', false);
        $('input[name="selectedLeads[]"]').parent().parent().removeClass('leadRow_selected');        
    });
    
     // Date Range Picker
    $("#from").datepicker({
        dateFormat: 'dd/mm/yy',
        defaultDate: "now",
        changeMonth: true,
        numberOfMonths: 2,
        isRTL: true,
        prevText: '<i class="fa fa-chevron-left"></i>',
        nextText: '<i class="fa fa-chevron-right"></i>',
        onClose: function (selectedDate) {
            $("#to").datepicker("option", "minDate", selectedDate);
        }
    
    });
    $("#to").datepicker({
        dateFormat: 'dd/mm/yy',
        defaultDate: "+1d",
        changeMonth: true,
        numberOfMonths: 2,
        isRTL: true,
        prevText: '<i class="fa fa-chevron-left"></i>',
        nextText: '<i class="fa fa-chevron-right"></i>',
        onClose: function (selectedDate) {
            $("#from").datepicker("option", "maxDate", selectedDate);
        }
    });
    
    $('*[data-poload]').click(function() {
        var e=$(this);
        //e.off('click');
        if (e.next('div.popover:visible').length){
            $('.popover').removeClass('in'); 
            return;
        } else {
            $.post(e.data('poload'), { lcId: e.attr('data-lcId') }, function(d) {
                if(d.result) {
                    e.attr('data-content', d.out);
                    e.popover({content: d.out, html: true}).popover('show');    
                }            
            }, 'json');
        }
    });
    
    $('#copyLeadsCB').on('click', function() {
        if($(this).is(':checked'))
           $('#statusSelectQ').find('option:nth-child(2)').prop('selected',true).trigger('change');
    });
    
    $('#deleteLeads').on('click', function () { 
        var data = {};
        data.leadId = $(".leadCB:checked").map(function(){
                                                      return $(this).val();
                                                    }).get();
        if(data.leadId.length > 0) {
            if(confirm('האם למחוק את הרשומות? לא ניתן לשחזר פעולה זו!')) {
    
                
                $.post(root + 'app/ajax/deleteLeads', { 'data': data }, function(d) {
                    if(d.result){
                        window.location.href = root + 'app/leads/search';
                    }
                    if(!d.result) alert('שגיאה!');
                }, 'json');
            }
        } else {
            $.smallBox({
            	title : "לא נבחרו רשומות!",
            	//content : "<i class='fa fa-clock-o'></i> <i>2 seconds ago...</i>",
            	color : "#C46A69",
            	iconSmall : "fa fa-pointer bounce animated",
                timeout : 2500
            }); 
        }   
		return false;         
    });
    
});
/*
function exportSearchResults() {
    
    var query = "<?php print $q; ?>";
    $.post(root + 'app/leads/exportLeads', { query: query }, function(d) {
        window.location.assign(root + 'assets/export/' + d);
    }, 'json');    
}
*/
function getTypeFilters() {
    var aSearchTypes = [];
    $("input[data-status-filter]").each(function(index, value) {
        if ($(this).prop("checked")) {
            var city = $(this).val();
            aSearchTypes.push(city);
        }
    });
    return aSearchTypes;
}

function editLead(leadId) {
    window.open(root + 'app/leads/viewLead/' + leadId);
}

function clearAll() {
    $('input').val('');
    $("select").select2("val", "");
    $('.checkbox').removeAttr('checked');
}