$(document).ready(function () {
    var fileArray = Array();

    $('#imageVideo_file').change(function () {
        var file = this.files[0];
        var fileName = file.name;
        var postType = $('#postType').val();
        var allowedFileType = "mp4 flv jpeg gif png bmp jpg";
        var fileExtention = fileName.split('.').pop().toLowerCase();
        var n = allowedFileType.search(fileExtention);

        if (n > -1) {
            var allowedImageFileType = "jpeg gif png bmp jpg";
            var allowedVedioFileType = "mp4 flv";
            var nImage = allowedImageFileType.search(fileExtention);
            var nVedio = allowedVedioFileType.search(fileExtention);

            if (nImage > -1) {
                if (postType === '' || postType === '4') {
                    if (file.size < 2097152) {
                        var reader = new FileReader();
                        reader.onload = function () {
                            var img = new Image;
                            img.onload = function () {

                                viewSingleImage(img.src, file);  // upload image file

                            };
                            img.onerror = function () {
                                $('#uploadVideoErrorMessage').show();
                                $('#errorMessageText').html('<span style="color:#767676">Invalid Image File. Try uploading valid image instead</span>');
                            };
                            img.src = reader.result;

                        };
                        reader.readAsDataURL(file);
                    } else {
                        $('#uploadVideoErrorMessage').show();
                        $('#errorMessageText').html('<span style="color:#767676">Image size must less then 2 Mb</span>');
                    }
                } else {
                    $('#uploadVideoErrorMessage').show();
                    $('#errorMessageText').html('<span style="color:#767676">Invalid Image file type. Try uploading <strong>jpg</strong>, <strong>gif</strong>, <strong>png</strong>, <strong>bmp</strong> image file instead</span>');
                }
            } else if (nVedio > -1) {
                if (postType === '' || postType === '5') {
                    if (file.size < 26214400) {

                        takeVideoSnapshot(); // upload video file

                    } else {
                        $('#uploadVideoErrorMessage').show();
                        $('#errorMessageText').html('<span style="color:#767676">Video size must less then 25 Mb</span>');
                    }
                } else {
                    $('#uploadVideoErrorMessage').show();
                    $('#errorMessageText').html('<span style="color:#767676">Invalid video file type. Try uploading <strong>jpg</strong>, <strong>gif</strong>, <strong>png</strong>, <strong>bmp</strong> image file instead</span>');
                }
            }
        } else {
            $('#uploadVideoErrorMessage').show();
            $('#errorMessageText').html('<span style="color:#767676">That kind of file isn\'t supported yet. Try uploading <strong>video</strong>, or <strong>picture</strong> instead</span>');
        }
    });


    /*
     * @Function            : takeVideoSnapshot 
     * @Used IN             : @function-'view/user/post_ajax/add_video_from.php
     * @Description         : take video span shot
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 01-07-2016 09:31 AM 
     * @Parameter           : videoFile[FILE]
     * @Return              : NULL      
     * @Status              : available      
     */
    var takeVideoSnapshot = function () {
        var defaultVideoPlayer = $('#defaultVideoPlayer').val();
        $('#imageView').show().
                css({'padding': "10px",
                    'height': "250px",
                    'overflow-y': "scroll"});

        var output;
        var div = document.createElement('div');
        $(div).attr('id', 'singleVideoView');
        $(div).attr('class', 'col-xs-6 col-sm-7');
        output = '<a href="javascript:void(0)" class="thumbnail" style="margin-bottom: 0px;border: none">';
        output += '<img src="' + defaultVideoPlayer + '" alt="Image Title" class="img-rounded box-shadow" style="height: 230px;width: 100%">';
        output += '</a><a href="javascript:void(0)" id="removeImageView" onclick="removeVideoView()"><span class="badge" style="position: absolute;z-index: 9999;right: 22px;top: 6px;"><i class="fa fa-times"></i></span></a>';
        $(div).html(output);
        $('#imageView').append(div);
        $('#postType').val(5);
        $('#imageVideo_file').attr('disabled', 'disabled');
    };

    /*
     * @Function            : viewSingleImage 
     * @Used IN             : @function-'view/user/post_ajax/add_video_from.php
     * @Description         : view single image 
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 29-06-2016 03:38 PM 
     * @Parameter           : imageSource[STRING]
     * @Return              : NULL      
     * @Status              : available      
     */
    var viewSingleImage = function (imageSource, imageFile) {
        var counter;
        var imageCounter = $('#imageCounter').val();
        $('#postType').val(4);
        $('#imageVideo_file').val('');

        if (imageCounter === '') {
            $('#imageView').show().
                    css({'padding': "10px",
                        'height': "160px",
                        'overflow-y': "scroll"});
            counter = 1;
            $('#imageCounter').val(counter);
        } else {
            var allCounter = new Array();
            allCounter = imageCounter.split(',');
            var counter1;
            var tempArray = new Array();
            if (allCounter.length === 1) {
                counter1 = allCounter[0];
            } else {
                for (var i = 0; i < allCounter.length; i++) {
                    tempArray.push(allCounter[i]);
                }
                counter1 = Math.max.apply(Math, tempArray);
            }
            var counter2 = parseInt(counter1);
            counter = ++counter2;
            addDocumentValue('imageCounter', counter.toString());
        }

        fileArray.push(imageFile);
        viewDocumentImage(counter, imageSource);
    };



    /*
     * @Function            : viewDocumentImage 
     * @Used IN             : @function-'viewSingleImage'    this@JS   
     * @Description         : view image in html document
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 30-06-2016 09:37 AM 
     * @Parameter           : counter[INTEGER], imageSource[STRING]
     * @Return              : NULL      
     * @Status              : available      
     */
    var viewDocumentImage = function (counter, imageSource) {
        var output;
        var div = document.createElement('div');
        $(div).attr('id', 'singleImageView' + counter + '');
        $(div).attr('class', 'col-xs-6 col-sm-3');
        output = '<a href="javascript:void(0)" class="thumbnail" style="margin-bottom: 0px;border: none">';
        output += '<img src="' + imageSource + '" alt="Image Title" class="img-rounded box-shadow" style="height: 140px;width: 100%">';
        output += '</a><a href="javascript:void(0)" id="removeImageView" onclick="removeImage(' + counter + ')"><span class="badge" style="position: absolute;z-index: 9999;right: 22px;top: 6px;"><i class="fa fa-times"></i></span></a>';
        $(div).html(output);
        $('#imageView').append(div);
    };




    $('#uploadImage').click(function () {
        var postType = $('#postType').val();
        var removeImageCounter = $('#removeImageCounter').val();

        if (postType === '4') {
            if (removeImageCounter !== '') {
                var removeImageCounterArray = removeImageCounter.split(',');

                for (var i = (removeImageCounterArray.length - 1); i >= 0; i--) {
                    fileArray.splice(((parseInt(removeImageCounterArray[i])) - 1), 1);
                }
            }

            uploadImages();
        }

        if (postType === '5') {
            var videoFile = $('#imageVideo_file').prop('files');
            var uploadImageVideoUrl = $('#uploadImageVideoUrl').val();

            var formdata = new FormData();
            formdata.append('upload_type', 5);
            formdata.append('video_file', videoFile[0]);

            $.ajax({
                url: uploadImageVideoUrl,
                type: "POST",
                data: formdata,
                contentType: false,
                cache: false,
                processData: false,
                success: function (data)
                {
                    alert(data);
//                $('#loading').hide();
//                $("#message").html(data);
                }
            });
        }
    });



    /*
     * @Function            : uploadImages 
     * @Used IN             : @function-'view/user/post_ajax/add_video_from.php
     * @Description         : upload Image video file
     * @Developed By        : MD Jaherul Islam
     * @Start DateTime      : 30-06-2016 03:45 PM 
     * @Parameter           : Null
     * @Return              : NULL      
     * @Status              : available      
     */
    var uploadImages = function () {
        var imageCounter = $('#imageCounter').val();
        var uploadImageVideoUrl = $('#uploadImageVideoUrl').val();

        var formdata = new FormData();
        formdata.append('upload_type', 4);
        formdata.append('total_image', imageCounter);
        for (var i = 0; i < fileArray.length; i++) {
            formdata.append('image_file' + i + '', fileArray[i]);
        }

        $.ajax({
            url: uploadImageVideoUrl,
            type: "POST",
            data: formdata,
            contentType: false,
            cache: false,
            processData: false,
            success: function (data)
            {
                alert(data);
//                $('#loading').hide();
//                $("#message").html(data);
            }
        });
    };



    $('#addTitle').click(function () {
        $('#imageVideoTitle').show();
        $('#imageVideoView').css({'border':'1px solid #80c12c'});
        $('#imageVideoTextArea').hide();
        $('#imageVideoTag').hide();
    });
    
    
    $('#addDescription').click(function () {
        $('#imageVideoTextArea').show();
        $('#imageVideoView').css({'border':'1px solid #80c12c'});
        $('#imageVideoTitle').hide();
        $('#imageVideoTag').hide();
    });
    
    
    
    $('#addTags').click(function () {
        $('#imageVideoTag').show();
        $('#imageVideoTextArea').hide();
        $('#imageVideoView').css({'border':''});
        $('#imageVideoTitle').hide();
    });
    
    
    
    $('#addLocation').click(function () {
//        $('#imageVideoTextArea').show();
//        $('#imageVideoView').css({'border':'1px solid #80c12c'});
//        $('#imageVideoTitle').hide();
//        $('#imageVideoTag').hide();
    });

});


/*
 * @Function            : removeImage 
 * @Used IN             : @function-'view/user/post_ajax/add_video_from.php
 * @Description         : upload Image video file
 * @Developed By        : MD Jaherul Islam
 * @Start DateTime      : 28-06-2016 09:04 AM 
 * @Parameter           : counter[INTEGER]
 * @Return              : NULL      
 * @Status              : available      
 */
var removeImage = function (counter) {
    addDocumentValue('removeImageCounter', counter);
    removeDocumentValue('imageCounter', counter.toString());
    $('#singleImageView' + counter + '').remove();

    var imageCounter = $('#imageCounter').val();
    if (imageCounter === '') {
        $('#imageView').hide();
        $('#postType').val('');
    }
};


/*
 * @Function            : removeVideoView 
 * @Used IN             : @function-'view/user/post_ajax/add_video_from.php
 * @Description         : upload Image video file
 * @Developed By        : MD Jaherul Islam
 * @Start DateTime      : 01-07-2016 12:25 PM 
 * @Parameter           : NULL
 * @Return              : NULL      
 * @Status              : available      
 */
var removeVideoView = function () {
    $('#singleVideoView').remove();
    $('#imageView').hide();
    $('#postType').val('');
    $("#imageVideo_file").removeAttr('disabled');
};




/*
 * @Function            : addDocumentValue 
 * @Used IN             : @function-'viewSingleImage'    this@JS   
 * @Description         : add ID into document 
 * @Developed By        : MD Jaherul Islam
 * @Start DateTime      : 30-06-2016 09:33 AM 
 * @Parameter           : fieldID[STRING], addID[INTEGER]
 * @Return              : NULL      
 * @Status              : available      
 */
var addDocumentValue = function (fieldID, addID) {
    var allUploadVideoOKcounter = new Array();
    var allUploadVideoOKcounter1 = $('#' + fieldID + '').val();
    if (allUploadVideoOKcounter1 !== '') {
        allUploadVideoOKcounter = allUploadVideoOKcounter1.split(',');
    }

    if (allUploadVideoOKcounter.length < 0) {
        allUploadVideoOKcounter.push(addID);
    } else {
        if (allUploadVideoOKcounter.indexOf(addID) < 0) {
            allUploadVideoOKcounter.push(addID);
        }
    }
    $('#' + fieldID + '').val(allUploadVideoOKcounter);
};



/*
 * @Function            : removeDocumentValue 
 * @Used IN             : @function-'viewSingleImage'    this@JS   
 * @Description         : remove ID into document 
 * @Developed By        : MD Jaherul Islam
 * @Start DateTime      : 30-06-2016 10:10 AM 
 * @Parameter           : fieldID[STRING], addID[INTEGER]
 * @Return              : NULL      
 * @Status              : available      
 */
var removeDocumentValue = function (fieldID, removeID) {
    var allUploadVideoCounter = new Array();
    var allUploadVideoCounter1 = $('#' + fieldID + '').val();
    if (allUploadVideoCounter1 !== '') {
        allUploadVideoCounter = allUploadVideoCounter1.split(',');
    }
    if (allUploadVideoCounter.length > 0) {
        if (allUploadVideoCounter.indexOf(removeID) > -1) {
            var index = allUploadVideoCounter.indexOf(removeID);
            allUploadVideoCounter.splice(index, 1);
        }
        $('#' + fieldID + '').val(allUploadVideoCounter);
    }
};




/*
 * @Function            : removeErrorMessage 
 * @Used IN             : @function-'post_ajax/add_video_from.php'
 * @Description         : remove error message
 * @Developed By        : MD Jaherul Islam
 * @Start DateTime      : 02-07-2016 12:10 PM 
 * @Parameter           : Null
 * @Return              : NULL      
 * @Status              : available      
 */
var removeErrorMessage = function () {
    $('#uploadVideoErrorMessage').hide();
};
