var callEqualizer = function()
{
    var attachEqualizer = function(containerId, callbacks)
    {
        if(!callbacks)
        {
            callbacks = {};
        }
        var innerTimeoutCallback = callbacks.timeout;
        var timeoutCallback = (typeof innerTimeoutCallback  == "function")
            ? function(){ innerTimeoutCallback(tastes); }
            : false;
        var ondropCallback = callbacks.ondrop;
        // id do timer de delay para busca da página contextualizada ao gosto
        var customPageTimer;

        // Array para facilitar o envio pro server (só dar um join)
        var tastes = API.getCookie('tastes-settings', false);
        if(!tastes)
        {
            tastes = [1,1,1,1];
        }
        else
        {
            tastes = tastes.split('-');
        }

        // Objeto que mapeia a posição de cada gosto dentro do array
        var tastesKeys = {
            flavor: 0,
            football: 1,
            samba: 2,
            rodeo: 3
        };

        // Objeto que mapeia o nível de gosto pelo top do botão de controle
        var positionVersusTaste = {
            "90": 0,
            "45": 1,
            "0": 2
        };

        var getNextSibling = function(el)
        {
            while(el.nextSibling && el.nextSibling.nodeType !== 1)
            {
                el = el.nextSibling;
            }
            return el.nextSibling;
        };

        /*
         * Isola variáveis de controle em uma closure e retorna objeto
         * com os métodos de callback pro drag
         */
        var dragCallbacksFactory = function()
        {
            var bgParentHeight, bgParent, coloredBg;
            var positionArray;

            var snapControl = function()
            {
                var top = global.parseInt(this.style.top, 10);
                var newTop;
                if(top < 23)
                {
                    newTop = 0;
                }
                else if(top > 66)
                {
                    newTop = 90;
                }
                else
                {
                    newTop = 45
                }
                this.style.top = newTop + "px";
                API.sizeElement(coloredBg, bgParentHeight - newTop);

                var tasteKey = this.parentNode.id.split("_")[1];
                
                tastes[tastesKeys[tasteKey]] = positionVersusTaste[newTop];

                if(typeof timeoutCallback == "function")
                {
                    if(customPageTimer)
                    {
                        global.clearTimeout(customPageTimer);
                    }
                    customPageTimer = global.setTimeout(function()
		    	{
				// wait
				var waitEl = API.getEBI("wait");
				if(waitEl)
				{
					API.getEBI("wait").style.display = "block";
				}
				timeoutCallback();
			}, 4000);
                }

                API.setCookie('tastes-settings', tastes.join('-'));

                if(typeof ondropCallback == "function")
                {
                    ondropCallback.call(this, tastes, tastesKeys[tasteKey]);
                }
                //analytics
                if(tasteKey)
                {
                  var  tastesNames  = ['sabor','futebol','carnaval','rodeio'];
                  sendAnalytcsEvents("/brahma/home/adaptar/"+tastesNames[tastesKeys[tasteKey]],'drag',tastesNames[tastesKeys[tasteKey]],tastes[tastesKeys[tasteKey]]);
                }
                //fim analitcs
            };

            var dragControl = function(position)
            {
                if(!positionArray)
                {
                    positionArray = position;
                }

                var top = position[0];
                if(top < 0 || top > 90)
                {
                    return true;
                }
                if(typeof bgParent == "undefined")
                {
                    bgParent = this.parentNode;
                }

                if(typeof coloredBg == "undefined")
                {
                    coloredBg = getNextSibling(this);
                }

                if(typeof bgParentHeight == "undefined")
                {
                    bgParentHeight = API.getElementSizeStyle(bgParent)[0] - 20;
                }
                API.sizeElement(coloredBg, bgParentHeight - top);
            };

            return {
                ondrag: dragControl,
                ondrop: snapControl
            };
        };

        var equalizerContainer = document.getElementById(containerId);
        if(equalizerContainer)
        {
            var eqControls = API.getEBCN('box_slider_control', equalizerContainer);
            var dragCbs;
            for(var i = eqControls.length, eqControl; --i >= 0;)
            {
                eqControl = eqControls[i];
                dragCbs = dragCallbacksFactory();
                API.attachDrag(
                    eqControl,
                    null,
                    {
                        ondrag: dragCbs.ondrag,
                        ondrop: dragCbs.ondrop,
                        axes: 'vertical',
                        ghost: false
                    }
                );
            }
        };

    };

    API.attachEqualizer = attachEqualizer;

    //API.attachDocumentReadyListener(function()
    //{
    //    var requestCustomPage = (function()
    //    {
    //        var pageRequester = new API.Requester();
    //        pageRequester.onsuccess = function(xhr, data)
    //        {
    //            API.addBoxes(data.boxes);
    //        };
    //
    //        return function(tastes)
    //        {
    //            customPageTimer = null;
    //            var tastesParams = [
    //                'sabor=' + tastes[0],
    //                'futebol=' + tastes[1],
    //                'samba=' + tastes[2],
    //                'rodeio=' + tastes[3],
    //            ].join('&');
    //            API.setCookie('tastes-settings', tastes.join('-'));
    //
    //            pageRequester.get('/svc/Pagina.php?' + tastesParams, true);
    //        }
    //    })();
    //
    //    attachEqualizer('box_config_content', {'timeout': requestCustomPage});
    //});
};

callEqualizer();

API.callEqualizer = callEqualizer;

