$(document).ready(function() {
    
    $('[name="category_id"]').on('change', function(){
            var catID = $(this).val();
            $('[name="item_id[]"]').html('<option value="" disabled>Please choose the category first!</option>');
            
            if(catID != "") {
                var data = {
                    'catID' : catID,
                    'pageID': $('[name="category_id"] option:selected').hasClass('page-load') ? $('[name="hidden_id"]').val() : ""
                }
                
                $('[name="item_id[]"]').html('<option value="" disabled>Please wait ...</option>');
                
                if($('[name="category_id"] option:selected').attr("data-group") == "1") {
                    $('[name="item_id[]"]').attr("multiple", "multiple");
                }else {
                    $('[name="item_id[]"]').removeAttr("multiple");
                }
                $.post( baseURL + "price/get_cat_items/", data, function(results){
                    var html = ''
                    ,   results = JSON.parse(results);
                    if( results != '' ) {
                        var priceIdsStr = "";
                        Object.keys(results).map(function(i, j){
                            if( results[i]['price_id'] != null ) {
                                priceIdsStr += results[i]['price_items_id']+",";
                            }
                            var selected = priceIdsStr.indexOf(results[i]['id']+",") >= 0 ? 'selected style="color: #1ba;"' : '';
                            html += '<option value="'+ results[i]['id'] +'" '+ selected +'>'+ results[i]['name'] +'</option>';
                        })
                    }else {
                        html = '<option value="" disabled style="color: #f33;">No results found</option>';
                    }
                    $('[name="item_id[]"]').html(html);
                });
            }
        
    });
    
    
    
    $('.start_date').datepicker({
        format: 'dd-mm-yyyy',
        autoclose: true,
        todayHighlight: true
    })
    .on('changeDate', function (e) {
        change_todate();
    });

    $('.end_date').datepicker({
        format: 'dd-mm-yyyy',
        autoclose: true,
        todayHighlight: true
    })
    .on('changeDate', function (e) {
    });
    change_todate();
    
    
    $.validator.addMethod("already_exist_price_name", function(value, element) {
        var return_val = true;
        var category_name = $('select[name="category_id"]').val();
        var item_name = $('select[name="item_id"]').val();
        var start_date = $('input[name="start_date"]').val();
        var end_date = $('input[name="end_date"]').val();
        var id = $('input[name="hidden_id"]').val();
        $.ajax({
            async: false,
            url: base_url + 'price/price_name_exists',
            type: 'POST',
            data: {
                category_name: category_name,
                item_name: item_name,
                start_date: start_date,
                end_date: end_date,
                id: id
            },
            dataType: "json"
        })
        .done(function(data) {
            if(data == 1) {
                return_val = false;
            }
        })
        .fail(function(jqXHR, status_code, error_thrown) {
            console.log(jqXHR.responseText);
        });
        
        return return_val;
    });
    
   
    $('form[name="price_form"]').validate({
        errorElement: "li",
        errorLabelContainer:'.error_container',
        validClass: 'valid',
        focusInvalid: true,
        rules: {
            category_id: {
                required: true
            },
            item_id: {
                required: true
            },
            start_date: {
                required: true
            },
            end_date: {
                required: true
            },
            price: {
                required: true
            }
        },
        messages: {
            category_id: {
                required: 'Please select Category Name!'
            },
            item_id: {
                required: 'Please select Item Name!'
            },
            start_date: {
                required: 'Please select Start Date!'
            },
            end_date: {
                required: 'Please select End Date!'
            },
            price: {
                required: 'Please enter Price!'
            }
        }
      });
      
      $('[name="category_id"]').trigger('change');
});

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

function change_todate() {
    if (($('.start_date').val() != '') && ($('.start_date').val()!= undefined)) {
        var start_date_arr = $('.start_date').val().split('-');
        var start_date_obj = new Date(start_date_arr[2], (start_date_arr[1] - 1), start_date_arr[0]);
        var end_date_start_obj = new Date(start_date_obj.getTime());// - (1 * 24 * 60 * 60 * 1000));
        
        var start_date = end_date_start_obj.getDate() + '-' + (end_date_start_obj.getMonth() + 1) + '-' + end_date_start_obj.getFullYear();
        $('.end_date').datepicker('setStartDate', start_date);
    }
}

function validate(){
    var itemsLen = $('select[name="item_id[]"] option:selected').length;
    if( itemsLen == 0 ) {
        notify('Please choose atleast one item!');
        return false;
    }
}