/*global redux_change, redux*/

(function( $ ) {
    "use strict";

    redux.field_objects = redux.field_objects || {};
    redux.field_objects.intense_icon = redux.field_objects.intense_icon || {};

    var xhr = [];
    var cachedIconSource = [];
    var finishedCheck;
    var requests = [];

    redux.field_objects.intense_icon.init = function( selector ) {
        if ( !selector ) {
            selector = $( document ).find( '.redux-container-intense_icon:visible' );
        }

        $( selector ).each( function() {
            var el = $( this );
            var parent = el;

            if ( !el.hasClass('initialized') ) {

                el.find( 'select.redux-intense-icon-source-item' ).not('.initialized').each( function() {
                    var $source = $(this);

                    $source.selectize({
                        sortField: 'text'
                    });

                    $source.change(function() {
                        setupSource($source);
                    });                
                });                
                
                el.find( 'select.redux-intense-icon-source-item' ).each( function() {
                    var $source = $(this);
                    var source = $source.val();

                    if ( 'undefined' == typeof( requests[source] ) ) {
                        requests[source] = true;
                        xhr.push($.ajax({
                            type: 'POST',
                            url: ajaxurl + '?action=intense_icon_type_action',
                            dataType: 'json',                            
                            cache: true,
                            data: {
                                security: $source.data("nonce"),
                                source: source,
                                type_id: 'xxxx'
                            },
                            success: function(results) {                                
                                cachedIconSource[source] = results; 
                                cachedIconSource.length++;
                            },
                        }));                        
                    }
                });                
            }
        });
        
        clearInterval(finishedCheck);

        finishedCheck = setInterval(function() {
            if (  cachedIconSource.length == xhr.length ) { 
                $( selector ).each( function() {
                    var el = $( this );
                    var parent = el;

                    el.find( 'select.redux-intense-icon-type-item' ).not('.initialized').each( function() {
                        $(this).selectize({
                            sortField: 'text',
                            render: {
                                option: function(item, escape) {
                                    return '<div class="intense icon" style="float: left; width: 30px; height:30px; margin: 1px; text-align: center;">' + 
                                    item.svg + 
                                    '</div>';
                                },
                                item: function(item, escape) {
                                    return '<div><div class="intense icon" style="float: left; width: 20px; height:20px; margin-right: 5px; text-align: center;">' + 
                                    item.svg + '</div> ' + item.text  +
                                    '</div>';
                                }
                            },
                            load: function(callback) { }
                        });
                    });

                    el.find( 'select.redux-intense-icon-source-item' ).each( function() {
                        var $source = $(this);
                        var source = $source.val();
                        setupSource($source);
                    });

                    el.addClass('initialized');
                });                

                clearInterval(finishedCheck);
            }
        }, 30);
        
    };

    function setupSource($source) {   

        var source = $source.val();

        if ( source != '' ) {       
            var source_key = $source.attr('id');
            var icon_type_id = $source.parents('.intense_icon_wrapper').find('.redux-intense-icon-type-item').attr('id');        
            var icon_type = jQuery('#' + icon_type_id)[0].selectize;
            
            var eventPause = function( event ) {
                event.stopPropagation();
            };

            $('#' + icon_type_id).on('change', eventPause);

            icon_type.disable();
            icon_type.clear();                  
            icon_type.clearOptions();

            $('#' + icon_type_id).off('change', eventPause);  

            icon_type.load(function(callback) {
                if ( 'undefined' != typeof( cachedIconSource[source] ) ) {
                    cachedIconSource[source].type_id = icon_type_id;
                    completeSourceSetup( cachedIconSource[source], callback )
                } else {
                    xhr[icon_type_id] && xhr[icon_type_id].abort();
                    xhr[icon_type_id] = $.ajax({
                        type: 'POST',
                        url: ajaxurl + '?action=intense_icon_type_action',
                        dataType: 'json',                    
                        cache: true,
                        data: {
                            security: $source.data("nonce"),
                            source: source,
                            type_id: icon_type_id
                        },
                        success: function(results) {
                            cachedIconSource[source] = results;
                            completeSourceSetup( results, callback );
                        },
                        error: function() {
                            callback();
                        }
                    });
                }
            });   
        }             
    }

    function completeSourceSetup( results, callback ) {
        if ( results != '' && results != null ) {
            var select = jQuery('#' + results.type_id);
            var icon_type = select[0].selectize;                        
            var classList = select.parents('.intense_icon_wrapper').find('.redux-intense-icon-type-item').attr('class').split(/\s+/);
            var defaultVal = '';

            $.each( classList, function(index, item){                                   
                if (item[0] === '_' && item[1] === '_') {
                   defaultVal = item.replace('__', '', 'gi');
                }
            });

            icon_type.enable();
            icon_type.refreshOptions();
            icon_type.clearOptions();
            icon_type.renderCache = {};                             
            callback(results.icons);

            var eventPause = function( event ) {
                event.stopPropagation();
            };

            select.on('change', eventPause);
            icon_type.setValue(defaultVal);
            select.off('change', eventPause);
        }
    }
})( jQuery );