jQuery(document).ready(function() {


    jQuery("#uploadfile_btn").live('click',function(e) {
        e.preventDefault();
        fileInputElement = jQuery('#uploadfiles').prop("files")[0];
        if(fileInputElement!=undefined){
            //var textType = /.+\.(xlsx|xls|csv)/;  /*/excel.*/;
            //if (fileInputElement.type.match(textType)) {
                jQuery('.main_block').html('<div id="upload_loader" ' +
                'style="width: 1000px;border: 1px solid #0074A2;position: relative;float: left;height: 30px;line-height: 30px;border-radius: 21px;">' +
                '<b style="width:1000px;text-align:center;position: absolute;" class="reduced_process"></b><span style="height: 30px;display: block;width: 0px;background-color: #7AD03A;border-radius: 21px;text-align: center;">' +
                '</span></div>');
                var reader = new FileReader();
                reader.onload = function (e) {
                    var lines = reader.result.split('\n');
                    lines_length = lines.length - 1;
                    var lines_array = Array();
                    for (var line = 1; line < lines_length; line++) {
                        if (lines[line] != '') {
                            if (line == 1) {
                                lines_array.push(lines[line]);
                            } else {
                                lines_array.push('@S@' + lines[line]);
                            }
                        }
                    }
                    circle =Math.ceil(lines_length/20);
                    var size = 20;
                    main_lines_array =Array();
                    for (var i = 0; i <lines_array.length;  i += size) {
                        var smallarray = lines_array.slice(i, i + size);
                        main_lines_array.push(smallarray);
                    }
                    import_ajax(main_lines_array,0);
                }
                reader.readAsText(fileInputElement, 'CP1251');
            /*} else {
                console.log("File not supported!");
            }*/
        }
        return false;
    });





    function import_ajax(main_lines_array,i){
        smallarray =main_lines_array[i];
        var formData = new FormData();
        formData.append("action", 'import_ajax_request');
        formData.append("postNonce", ImportAjax.postNonce);
        formData.append("formData", fileInputElement);
        formData.append('CsvPart', smallarray);
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                if((i+1)<circle ){
                    import_ajax(main_lines_array,i+1);
                }else{
                    if(i!=0){
                        return false;
                    }
                }
                var perc_width =1000/circle;
                var percent =((i+1)/circle)*100;
                var percent_show=    percent.toFixed(2);
                if(percent_show>99.8){
                    percent_show =100;
                }
                var progress_width = jQuery('#upload_loader span').width();
                var width =parseInt(perc_width)+parseInt(progress_width);
                jQuery('#upload_loader span').css('width',width+'px');
                jQuery('#upload_loader .reduced_process').text('Number of songs importing '+(lines_length)+' ('+percent_show+'%)');
                if(((i+2)==circle && circle!=1) || ((i+1)==circle && circle==1)){
                    jQuery('#upload_loader .reduced_process').text('Number of songs importing '+(lines_length)+' (100%)');
                    jQuery('#upload_loader span').css('width','1000px');
                    jQuery( ".main_block" ).append("<span style='float: left;width: 1000px;text-align: center;margin-top: 10px;'>Done!</span><br> <a style='  display: inline-block;width: 100%;' href=''>Import More</a>");
                    return false;
                }

            }
        }
        xhr.open("POST", ImportAjax.ajaxurl, true);
        xhr.send(formData);
    }


    function delete_csv(delete_circle,i){

        jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            async: true,
            cache:false,
            url: ImportAjax.ajaxurl, // there on the admin side, do-it-yourself on the front-end
            data: {
                'action':'delete_csv',
                'postNonce': ImportAjax.postNonce
            },
            success: function(data){
                if(jQuery.isNumeric(data)){
                    if(data==0){
                        jQuery("#status").css('display', 'none');
                        jQuery(".done").css('display', 'block');
                        jQuery(".delete_csv").val(0);

                        return false;
                    }else if( data>0){
                        jQuery(".delete_csv").val(data);
                    }
                }

                if((i+1)<delete_circle ){
                    delete_csv(delete_circle,i+1);
                }else{
                    if(i!=0){
                        return false;
                    }
                }

            },
            error:function(thrownError){
                if(thrownError.status==502){
                    jQuery("#resetsongs_btn").click();
                }
            }
        });

    }



    jQuery("#resetsongs_btn").live('click', function () {

        jQuery(".done").css('display', 'none');
        var delete_circle =jQuery('.delete_csv').val();

        if(delete_circle!=0){

            jQuery("#status").css('display', 'block');
            delete_csv(delete_circle,0);

            return false;

        }else{
            return false;
        }

    });














});
