<script type="text/javascript">

    function readURL(i,t) {

        input = document.getElementById(i);

        var result = 'error';

        if (input.files && input.files[0]) {

            var reader = new FileReader();

            reader.onload = function (e) {
                var image = new Image();
                image.src = reader.result;

                image.onload = function() {
                    var imgwidth = image.width;
                    var imgheight = image.height;
                    var isize = imgwidth*imgheight;
                    if(isize < 3600) {
                        alert("{{__('adminforms.products.image_to_small')}} ("+imgwidth+"x"+imgheight+") ");
                        return false;

                    } /*else if(isize > 1200000){
                        alert("{{__('adminforms.products.image_to_big')}} ("+imgwidth+"x"+imgheight+") ");
                        return false;
                    }*/ else {
                        t.attr("src",e.target.result);
                        result = 'sucess';
                    }
                }; //image.onload

            }; // reader.onload 

            reader.readAsDataURL(input.files[0]);
        } // if files

        setTimeout(function(){
            $('#imgres').val(result);
        }, 200);


    } // readURL


    function getImgProcResult() {
        var result = $('#imgres').val();
        return result;

    }


    function imageInputChange(e){

        $('#imgres').val('');
        var targetimg = e.parent().find("img");
        var ciiId = e.attr('id');
        readURL(e.attr('id'),targetimg);

        setTimeout(function(){
            var iresult = getImgProcResult();
            if(iresult == 'error'){
                $('#'+ciiId).val('');
                $('#'+ciiId).parent().find('input.form-control').val('');
                $('#'+ciiId).parent().find("img").attr('src', '{{asset('assets/img/admin-image-placeholder.jpg')}}');
            }
        }, 250);

    }


    function strip_tags (input, allowed) {
        // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
        allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
        var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
            commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
        return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
            var trimed =  allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
            var result = trimed.replace(/<br\s?\/?>/, '').replace( /[\s\n\r]+/g, ' ' ).replace(/\s+/g, " ");
            return result;
        });
    }


    function scrollToError(e){
        $('html, body').animate({
            scrollTop: (parseInt(e.offset().top) - 50 )
        }, 500);
    }


    $(document).ready( function() {

        // On cat change
        $("#catid").change( function(){
            getCatAttributes($(this).val());
        });

        function getCatAttributes(catid){

            var loaderdiv = '<div style="width:100%; height:30px; text-align:center"><img src="{{asset('assets/img/loading.gif')}}" width="16" height="16" vspace="5" /></div>';

            $("#filters").empty();
            if(catid == ''){
                $("#filters").html('{{__('adminforms.products.attr_cat_not_sel')}}')
                return false;
            } else {

                $("#filters").html(loaderdiv);

                $.get('/panel/ajax-getatrselects', {'catid' : catid }, function(data){

                    var resp = data.split(',');
                    $("#filters").empty().html(resp[0]);

                }); // end post
                return false;
            }


        }

        // On image input change input.filestyle
        $("input.imginput").on("change", function() {
            imageInputChange($(this));
        });

        // Delete image
        $('.delimg').click(function() {

            var defImg = $(this).parent().parent().find("input[name='defaultimg']").is(':checked');

            if (defImg) {
                alert('{{__('adminforms.products.cant_del_def_img')}}');
                return false;
            }

            var imgbox = $(this).closest('.imgb');
            //var container = $(this).parent().parent();
            var prodid = $(this).data('prodid');
            var imgid = $(this).data('imgid');
            var addimgfld = '<div class="form-group col-md-3">' +
                '<div class="imgprew"><img src="{{asset('assets/img/admin-image-placeholder.jpg')}}"></div>' +
                '<input type="file" value="" name="images[]" class="filestyle input-sm imginput" data-icon="false" data-buttonText="{{__('adminforms.products.select_img')}}">' +
                '</div>';

            if (!confirm('{{__('adminforms.products.confirm_img_delete')}}')) {

                return false;

            } else {

                $.get('/panel/ajax-delimg', {
                    'prodid': prodid,
                    'imgid': imgid
                }, function(data) {

                    var resp = data.split(',');

                    if (resp[0] == 'sucess') {

                        imgbox.slideUp(1000, function() {
                            imgbox.remove();
                            alert(resp[1]);
                            $(addimgfld).appendTo('#imagesinput');
                            var addedInput = $('.filestyle:last');
                            addedInput.filestyle({
                                icon: false,
                                'buttonText': '{{__('adminforms.products.select_img')}}'
                            });
                            addedInput.on("change", function() {
                                imageInputChange($(this));
                            });
                        });

                    } else {
                        alert(resp[1]);
                    }

                });

            }

        });

        // Set image as default
        $("input.dic").on("change", function() {

            var dimgd = $(this).val();

            $.get('/panel/ajax-setdefimg', {
                'defaultimg': dimgd
            }, function(data) {

                alert(data);

            });
        });

        // Insertion of specification table in description
        $('.gst').click( function () {

            var catid = $(this).data('catid');


            if(catid < 1){
                alert('{{__('adminforms.products.not_valid_cat_id')}}');
                return false;
            } else {

                var curentHtml = CKEDITOR.instances.prodspec.getData();

                $.post('/panel/ajax-getspectable', {'catid' : catid }, function(data) {

                    var resp = data.split(',');

                    if(resp[0] == 'success'){
                        var newHtml = curentHtml+resp[1];
                        CKEDITOR.instances.prodspec.setData(newHtml);
                        alert('{{__('adminforms.products.spec_table_added')}}');
                    } else {
                        alert(resp[1]);
                    }




                }); // end post
                return false;
            }


        } );


        // Dodavanje novog polja za unos fajlova za download
        $('#addtuf').click( function() {

            var adiv = $('#addtuf');
            var unused = 0;

            var pdfuf =  '<div class="col-xs-6 col-sm-3 col-md-2 pdfuw">'
                +'<div class="pdfprew"><img src="{{asset('assets/img/pdf.png')}}" class="img-responsive"></div>'
                +'<input type="file" value="" name="pdfdoc[]" class="filestyle input-sm pdfinput" data-icon="false" data-buttonText="{{__('adminforms.products.select_doc')}}">'
                +'</div>';


            $('.pdfinput').each(function(i, e) {
                var cval = $.trim($(this).val());
                if(cval == ''){
                    unused++;
                    alert('{{__('adminforms.products.doc_fld_exist')}}');
                    return false;
                }
            });

            if(unused == 0){
                $(pdfuf).insertBefore(adiv);
                var addedInput = $('.pdfinput:last');
                addedInput.filestyle({icon: false, 'buttonText': '{{__('adminforms.products.select_doc')}}'});
            }

        });


        // brisanje dokumenta
        $('.deldoc').click( function() {


            var docbox    = $(this).closest('.pdfuw');
            var prodid    = $(this).data('prodid');
            var docid     = $(this).data('pdid');


            if(!confirm('Da li ste sigurni da zelite da obrisete ovaj dokument')){

                return false;

            } else {

                $.get('/panel/ajax-deldoc', {'prodid': prodid, 'docid' : docid}, function(data){

                    var resp = data.split(',');

                    if(resp[0] == 'sucess'){

                        docbox.slideUp(1000, function(){
                            docbox.remove();
                            alert(resp[1]);
                        });

                    } else {
                        alert(resp[1]);
                    }

                });

            }

        });

        // submit check
        $("#prodsbmtbutt, #prodsbmtbutt2").on('click', function() {

            var errors = 0;


            // Attribute selection check
            var atrErrors = 0;
            if($('select.atsel').length){
                $('.atsel').each(function() {
                    var atrval = jQuery.trim($(this).val());
                    if(atrval == ''){
                        errors++;
                        atrErrors++;
                        var atrname = 	$(this).parent().find('label').text();
                        alert("{!!__('adminforms.products.attr_not_selected')!!}");
                        scrollToError($(this));
                        return false;
                    }

                });
            }

            if(atrErrors > 0){
                return false;
            }

            // prod_name check
            var prodname = jQuery.trim($('#prodname').val());

            if(prodname == ''){
                errors++;
                alert('{{__('adminforms.products.no_prodname')}}');
                scrollToError($('#prodname'));
                return false;
            }

            // brand_id check
            var brandid  = jQuery.trim($('#brandid').val());

            if(brandid == ''){
                errors++;
                alert('{{__('adminforms.products.no_brandid')}}');
                scrollToError($('#brandid'));
                return false;
            }

            // cat_id check
            var catid  = jQuery.trim($('#catid').val());

            if(catid == ''){
                errors++;
                alert('{{__('adminforms.products.no_catid')}}');
                scrollToError($('#catid'));
                return false;
            }


            // prod_price check
            var price = jQuery.trim($('#prodprice').val());

            if(price == ''){
                errors++;
                alert('{{__('adminforms.products.no_price')}}');
                scrollToError($('#prodprice'));
                return false;
            }
            var corectprice = $.isNumeric(price);
            if(!corectprice){
                errors++;
                alert('{{__('adminforms.products.incorect_price')}}');
                scrollToError($('#prodprice'));
                return false;
            }


            // prod_weight check
            var weight = jQuery.trim($('#prodweight').val());

            if(weight == ''){
                errors++;
                alert('{{__('adminforms.products.no_weight')}}');
                scrollToError($('#prodweight'));
                return false;
            }
            var corectweight = $.isNumeric(weight);
            if(!corectweight){
                errors++;
                alert('{{__('adminforms.products.incorect_weight')}}');
                scrollToError($('#prodweight'));
                return false;
            }

            // Images check

            var emptyImg = 0;
            var curentImgs = $('.iold').length;
            emptyImg = emptyImg+curentImgs;

            $('.imginput').each( function() {
                var imgVal = jQuery.trim($(this).val());
                if( imgVal != '' && imgVal.length > 4){
                    emptyImg++;
                }

            });
            if(emptyImg < 1){
                errors++;
                alert('{{__('adminforms.products.no_image')}}');
                scrollToError($('#imagesinput'));
                return false;

            }


            // prod_mdesc check

            /*var marketingdesc  =  CKEDITOR.instances.prodmdesc.getData();
            var mdcleantext    =  jQuery.trim(strip_tags(marketingdesc , '').replace(/\s+/g, ' ').replace( /[\s\n\r]+/g, ' ' ));
            var mdLength       =  mdcleantext.length;
            var mdwords      = 0;
            if(mdLength){
                mdwords = mdcleantext.split(/\s+/).length;
            }

            if(mdcleantext == ''){
                errors++;
                alert('{{__('adminforms.products.no_mdesc')}}');
                scrollToError($('#mdh'));
                return false;
            }

            if(mdwords < 15){
                errors++;
                alert('{!!__('adminforms.products.too_short_mdesc', ['wordsnum' => 15])!!}');
                scrollToError($('#mdh'));
                return false;
            }
*/

            // prod_desc check

            var maindesc  =  CKEDITOR.instances.prodspec.getData();
            var mdcleantext    =  jQuery.trim(strip_tags(maindesc , '').replace(/\s+/g, ' ').replace( /[\s\n\r]+/g, ' ' ));
            var mdLength       =  mdcleantext.length;
            var mdwords      = 0;
            if(mdLength){
                mdwords = mdcleantext.split(/\s+/).length;
            }

            if(mdcleantext == ''){
                errors++;
                alert('{{__('adminforms.products.no_fdesc')}}');
                scrollToError($('#mdh'));
                return false;
            }

            if(mdwords < 15){
                errors++;
                alert('{!!__('adminforms.products.too_short_fdesc', ['wordsnum' => 15])!!}');
                scrollToError($('#mdh'));
                return false;
            }





            // End check

            if(errors == 0){
                $('#prodform').submit();
            }





        });

    });// dr

</script>