

(
    function($)
    {
        /* Armazenamento do último hash visualizado */
        menuController.lastHash = null;
        
        /* Sobrescrita do método de interpretação de hashes, para a tela de produtos */
        menuController.parseHash = function(hash, event, noRequest)
        {
            var speedController = 'medium';

            if(hash.indexOf('#') == -1)
            {
                return false;
            }
            
            hash = hash.split('#');
            /* Verificar se o endereço informado não aponta para uma página diferente da atual */
            if(hash.length > 1 && hash[0] != '')
            {
                var url = hash[0], current = self.location.pathname.split('/');
                current = current[current.length - 1];
                
                if(current != url)return false;
            }
            
            hash = hash.length > 1 ? hash[1] : hash[0];
            hash = hash.split('/');
            
            if(event)
            {
                event.stopPropagation();
                event.preventDefault();
            }
            else
            {
                showOnlyController.init();
            }

            /* Detalhes de produto */
            var reference = null;
            for(var counter = 0, size = hash.length;counter < size;counter++)
                if(hash[counter].indexOf('reference:') == 0)
                {
					$('div.infoSendFriend').slideUp();
                    reference       = hash[counter].split(':')[1];
                    hash[counter]   = 'reference';
                    break;
                }
            if(reference != null)
                menuController.lastHash = document.location.hash.replace('#','');
            
            $('#details')[reference != null ? 'slideDown' : 'slideUp'](speedController);
            $('#products')[reference == null ? 'slideDown' : 'slideUp'](speedController);
            
            $('#nav-detail div.heading')[reference != null ? 'slideUp' : 'slideDown'](speedController, function()
            {
                if(reference != null)$('html, body').animate({scrollTop: $('#menu').offset().top},'medium');
                var item = $('#products a.product').removeClass('active').filter('[href$="reference=' + reference + '"]').addClass('active');
                
                if(item.length)
                {
                    if(!('productInfo' in item[0]))
                    {
                       item[0].productInfo = eval('(' + item.attr('data-product-info') + ')');
                       item.removeAttr('data-product-info');
                    }
                    
                    var color = productListManager.getColor(item[0].productInfo.colors);
                    productListManager.setActive(item[0].productInfo, color.reference, true);
                }
                else if(reference != null)
                {
                    var target = null;
                    
                    $('#products a.product').each
                    (
                        function()
                        {
                            var current = $(this), pos = null;
                            
                            if(!('productInfo' in current[0]))
                            {
                                current[0].productInfo = eval('(' + current.attr('data-product-info') + ')');
                                current.removeAttr('data-product-info');
                            }
                            
                            for(var counter = 0, size = current[0].productInfo.colors.length;counter < size;counter++)
                            {
                                if(current[0].productInfo.colors[counter].reference == reference)
                                {
                                    pos     = counter;
                                    break;
                                }
                            }
                            
                            if(pos != null)
                            {
                                current.addClass('active');
                                productListManager.setActive(current[0].productInfo, reference, true);
                                return false;
                            }
                            
                            return true;
                        }
                    )
                    
                    
                    self.location.replace(self.location.pathname + '?reference=' + reference);
                    return false;
                }
                
                return true;
            });
            
            if(reference != null)
            {
                hash = self.location.hash;
                if(hash.indexOf('#') == 0)hash = hash.substring(1);
                hash = hash.split('/');
            }
            
            /* Menu */
            var items = $('#menu a:not([href="#wishlist"])').removeClass('active');
            if(hash.length > 0)
            {
                var target = items.eq(0);
                if(items.filter('[href="#' + hash[0] + '"]').length)
                {
                    target = items.filter('[href="#' + hash[0] + '"]');
                    if(!target.hasClass('active'))
                    {
                        /* Geração do menu de itens de pesquisa */
                        target.addClass('active');
                        $('#nav-detail form.params a.special-search').attr('href', '#special-search/' + hash[0]);
                        $('#nav-detail div.filters div.actions a.close').attr('href', '#' + hash[0]);
                    }
                }
            }
            
            /* Submenu */
            var showMyMenu = function()
            {
                var target = $('#submenu > ul.' + (hash[0] || 'void'));
                
                if(target.is(':visible') && reference == null)return false;
                $('#submenu > ul:not(.' + (hash[0] || 'void') + ')').slideUp(speedController, function()
                {
                    target[reference == null ? 'slideDown' : 'slideUp'](speedController);
                    return true;
                });
                return true;
            };

            showMyMenu.apply([this]);
            
            /* Tópicos de submenu */
            var showMySubmenu = function()
            {
                var specific = (hash[1] || 'all');
                if(hash[0] == 'special-search')specific = 'all';
                if(specific.indexOf('show-only:') == 0 && hash.length == 2)
                {
                	$specific = 'all';
                }
                
                var target = $('#submenu > ul.' + (hash[0] || 'void') + ' > li > a').removeClass('active')
                                .filter('[href="#' + (hash[0] || 'void') + '/' + (hash[1] || 'all') + '"]').addClass('active'),
                    submenu= target.siblings('ul');
                
                $('#submenu ul:not(.' + (hash[0] || 'void') + ') ul.suboptions').slideUp(speedController);
                $('#submenu ul.' + (hash[0] || 'void') + ' ul.suboptions')
                    [submenu.length != 0 || specific != 'all' ? 'slideDown' : 'slideUp'](speedController);
                return true;
            }
            
            showMySubmenu.apply(this);
            
            /* Detalhes do submenu */
            $('#submenu > ul.' + (hash[0] || 'void') + ' ul.suboptions a').removeClass('active')
                .filter('[href="#' + (hash[0] || 'void') + '/' + (hash[1] || 'void') + '/' + (hash[2] || 'void') + '"]').addClass('active');
            
            /* Special search */
            if(hash[0] == 'special-search')$('#nav-detail').addClass('active');
                        
            $('#nav-detail div.filters')[hash[0] == 'special-search' && reference == null ? 'slideDown' : 'slideUp']
            (speedController, function()
            {
                if(hash[0] != 'special-search')$('#nav-detail').removeClass('active');
                /* IE */$(this).css({zoom:1});
                
                specialSearchController.init();
            });
            
            if(hash[0] == 'special-search' && hash.length > 1)
            {
                var target = items.filter('[href="#' + (hash[1] || '') + '"]');
                if(target.length == 0)target = items.eq(0);
                target.addClass('active');
            }
            else if(hash[0] == 'special-search')
            {
                items.eq(0).addClass('active');
                var addHash = items.eq(0).attr('href').substring(items.eq(0).attr('href').indexOf('#') + 1);
                hash.push(addHash);
            }
            
            /* Navegação para mais produtos */
            var more = $('#product-more');
            more.animate({height: reference == null && more.attr('data-last-page') == 'no' ? 'show' : 'hide'}, speedController);
            
            /* Page reloading */
            params = {'command': 'search'};
            $('#nav-detail div.heading p.title').animate({height: hash[0] == 'wishlist' ? 'show' : 'hide'}, speedController);
			
			
            switch(hash[0])
            {
                case 'special-search':
                    /* Busca Especial */
                    self.location.hash = showOnlyController.modifyHash('#' + hash.join('/'));
                    if(reference == null && noRequest == null)specialSearchController.execute('#' + hash.join('/'));
                    specialSearchController.setActiveItems();
                    return false;
                break;
                case 'wishlist':
                    params['command'] = 'wishlist';
                    params['wishlist']= cookieManager.get('wishlist');
                break;
                default:
                    /* Categoria, subcategoria e detalhe */
                    if(hash.length > 0) params.category      = hash[0];
                    if(hash.length > 1 && hash[1] != 'all' && hash[1].substr(0,9) != 'show-only' )params.subcategory   = hash[1];
                    if(hash.length > 2 && hash[2].substr(0,9) != 'show-only') params.detailcategory = hash[2];   
                break;
            }
            
            if( document.location.hash.indexOf('show-only') != '-1' )
            {
				if( hash[ hash.length-1 ].substr(0,9) == 'show-only')
					params.show_only = hash[ hash.length-1 ].substr(10);
				else
					params.show_only = document.location.hash.substr( document.location.hash.indexOf('show-only') ).substr(10);
            }

            if(noRequest == null)
            {
                productListManager.lastQueryParams = params;
                $.post('services/products/index.php',params,productListManager.loader);
            }
            
            /* Hash change */
            if(reference == null)
            {
                menuController.manuallyChanged   = true;
                self.location.hash               = hash[0] != 'wishlist' ? showOnlyController.modifyHash('#' + hash.join('/')) : '#' + hash.join('/');
            }
            else
            {
                
				menuController.manuallyChanged   = true;
                self.location.hash               = '#reference:' + reference;  
				
				/* cria carrosel */
				$.ajax({
					type: "POST",
					url: 'content/scripts/produto.php',
					dataType: "json",
					data: "ref="+reference,
					success: function(dados){
						var itens = [];
						$('div#carouselProdutos').html('<ul id="mycarousel" class="jcarousel-skin-tango"></ul>');
						$.each(dados.ref, function(i, obj){
							itens.push('<li class="inb"><a class="product" href="colecao.php?reference='+obj.id+'"><img alt="" src="content/img/produtos/all/'+obj.id+'_thumb.jpg"></a></li>');
						});
						$('#mycarousel').html(itens.join(''));
						setTimeout(function(){
							$('#mycarousel').jcarousel();
						}, 1000);
					}
				});
				
				
				
				
				
				
				
				
				//console.log('INTERNA DE PRODUTOS, a referencia eh: '+reference);
				
			
				
            }
            
            
            /* Wishlist */
            if(hash[0].indexOf('wishlist') == 0)
            {
                showOnlyController.init();
                wishlistManager.showShareLinks();
            }

            $('#menu li.list-cadeaux a')
                [hash[0] == 'wishlist' ? 'addClass' : 'removeClass']('active');
            
            return true;
        };
        
        /* Controlador da special search */
        specialSearchController =
        {
            controller: null,
            init: function()
            {
                var paramsSource = $('#menu > li a[data-search-params].active');
                
                if(paramsSource.length == 0)return false;
                
                var items = eval('(' + paramsSource.attr('data-search-params') + ')'), output = [];
                for(var counter = 0, size = items.length;counter < size;counter++)
                {
                    var current = items[counter];
                    
                    output.push('<ul class="params">');
                    output.push('<li class="title inb">',current.title,'</li>');
                    
                    for(var counter2 = 0, size2 = 9;counter2 < size2;counter2++)
                    {
                        var item = current.items[counter2] ? current.items[counter2] : {hash: '', title: '&nbsp;', extraClass: 'no-decoration'};
                        if(specialSearchController.findInHash(item.hash, self.location.hash))item.extraClass = 'active';
                        
                        output.push('<li class="inb">','<a href="#', item.hash, '" class="', (item.extraClass || ''), '">', item.title, '</a></li>');
                    }
                    
                    output.push('</ul>');
                }
                
                $('#nav-detail #items').html(output.join(''));
                $('#nav-detail #items a').unbind('click.specialsearch').bind
                (
                    'click.specialsearch',
                    function(e)
                    {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        var target  = $(this), hash = target.attr('href').split('#');
                        hash.splice(0,1);
                        hash        = hash.join('');
                        
                        if(hash == '')return false;
                        $(this).toggleClass('active');
                        
                        var timer = 800;
                        if(specialSearchController.controller != null){window.clearTimeout(specialSearchController.controller);timer = 1000;}
                        specialSearchController.controller = window.setTimeout(specialSearchController.setCurrentHash, timer);
                        return true;
                    }
                );
                
                return true;
            },
            getHash: function()
            {
                var found = {}, output = [];
                
                $('#nav-detail #items a.active').each
                (
                    function()
                    {
                        var hash = this.href.split('#');hash.splice(0,1);hash = hash.join('').split('/');
                        
                        if(!(hash[0] in found))found[hash[0]] = hash[1];
                        else found[hash[0]] = found[hash[0]] + ',' + hash[1];
                    }
                );
                
                for(var item in found)
                    output.push(item + ':' + found[item]);
                    
                return output.join('/');
            },
            setCurrentHash: function()
            {
                menuController.manuallyChanged = true;
                
                var hash = specialSearchController.getHash(), target = $('#menu a.active');
                
                if(hash != '')hash = '/' + hash;
                if(target.length == 0)target = $('#menu a:eq(0)');
                
                target = target.attr('href').replace('#','');
                
                document.location.hash = showOnlyController.modifyHash('#special-search/' + target + hash);
                specialSearchController.execute(document.location.hash);
                
                return true;   
            },
            findInHash: function(value, hash)
            {
                if(value == '' || hash == '#')return false;
                hash = hash.split('#');hash.splice(0,1);
                
                if((hash[0] || '').indexOf('special-search/') != 0)return false;
                if(value.indexOf('#') == 0)value = value.substring(1);
                
                
                hash        = hash.join('').split('/');
                value       = value.split('/');
                
                var found   = false;
                
                for(var counter = 0;counter < hash.length;counter++)
                    if(hash[counter].indexOf((value[0] || 'value not found') + ':') == 0){found = counter;break;}
                
                if(found === false)return false;
                var items = hash[found].substring(hash[found].indexOf(':') + 1).split(',');
                
                found = false;
                
                for(var counter = 0;counter < items.length;counter++)
                    if(items[counter] == (value[1] || 'value not found')){found = true;break;}
                
                return found;
            },
            execute: function(hash)
            {
                hash        = hash.split('#')[1].split('/');
                var params  = {};
                
                
                for(var counter = 0, size = hash.length;counter < size;counter++)
                {
                    var value = hash[counter].split(':');
                    
                    switch(counter)
                    {
                        case 0:/* Indica special search */
                            params['command'] = 'special-search';
                        	break;
                        case 1:/* Indica categoria */
                            params['category'] = value[0];
                        	break;
                        default:
                        	params[value[0]] = value[1];
                        	break;
                    }
                }
                if( hash[ hash.length-1 ].substr(0,9) == 'show-only') params.show_only = hash[ hash.length-1 ].substr(10);

                /* Caso não haja parâmetros de busca, executar busca normal */
                if(hash.length == 2)
                    params['command'] = 'search';
                    
                productListManager.lastQueryParams = params;
                $.post('services/products/index.php',params,productListManager.loader);
            },
            setActiveItems: function()
            {
                $('#items a').each
                (
                    function(e)
                    {
                        var target = $(this);
                        target[specialSearchController.findInHash(target.attr('href'), self.location.hash) ? 'addClass' : 'removeClass']('active');
                        return true;
                    }
                );
                
                return true;
            }
        };
        
        /* Controlador do "mostrar somente" */
        showOnlyController =
        {
            init: function()
            {
                var hash = self.location.hash.split('#');hash.splice(0,1), indexes = [];
                hash     = hash.join('').split('/');
                
                for(var counter = 0;counter < hash.length;counter++)
                    if(hash[counter].indexOf('show-only:') == 0)
                    {
                        indexes = hash[counter].substring(hash[counter].indexOf(':') + 1).split(',');
                        break;
                    }
                
                var items = $('#nav-detail form.params input.checkbox').each
                (
                    function()
                    {
                        this.checked = false;
                        
                        for(var counter = 0;counter < indexes.length;counter++)
                            if(indexes[counter] == this.value){this.checked = true;break;}
                            
                        return true;
                    }
                );
                
                return true;
                
            },
            modifyHash: function(input)
            {
                input = input.split('#');input.splice(0,1);
                input = input.join('').split('/');
                
                for(var counter = 0;counter < input.length;counter++)
                {
                    if(input[counter].indexOf('show-only:') == 0)
                    {
                        input.splice(counter, 1);
                        break;
                    }
                }
                
                var append = [];
                $('#nav-detail form.params input.checkbox').each
                (
                    function()
                    {
                        if(this.checked)append.push(this.value);
                        return true;
                    }
                );
                
                if(append.length)
                {
                	input.push('show-only:' + append.join(','));
                }
                return '#' + input.join('/');
            }
        };
		
		
		
		
		
		
		
        
        /* Controlador da listagem de produtos */
        productListManager =
        {
            speedControl    : 'fast',
            lastQueryParams : null,
            init: function()
            {
                /* Item da listagem de produtos */
                $('#products a.product').live
                (
                    'mouseenter mouseleave',
                    function(e)
                    {
                        /* Deixa os dados de produto já cacheados como objeto JSON */
                        if(!('productInfo' in this))
                        {
                            this.productInfo = eval('(' + this.getAttribute('data-product-info') + ')');
                            this.removeAttribute('data-product-info');
                        }
                        
                        switch(e.type)
                        {
                            case 'mouseenter':
                                var target = $(this).find('div.over');

                                if(target.length == 0)
                                {
                                    target = $('<div class="over">' +
                                                    this.productInfo.title +
                                                    '<span>Confira</span>' + 
                                               '</div>');
                                    $(this).append(target);
                                }
                                
                                target.stop().animate({left:0}, productListManager.speedControl);

                            break;
                            case 'mouseleave':
                                var target = $(this).find('div.over');
                                if(target.length)
                                    target.stop().animate({left: -target.outerWidth()}, productListManager.speedControl);
                            break;
                        }
                    }
                ).live
                (
                    'click',
                    function(e)
                    {
                        var item = $(this).addClass('active'), reference = (item.attr('href').split('?')[1]).split('=')[1];
                        menuController.parseHash('#reference:' + reference, e, true);
                    }
                );
                
                /* Ações do detalhe de produtos */
                
                /* Pesquisas adicionais */
                $('#details ul.about a.more').bind
                (
                    'click',
                    function(e)
                    {
                        menuController.parseHash(this.getAttribute('href'), e);
                    }
                );
                
                /* Navegação entre cores */
                $('#details li.other-colors a').live
                (
                    'click',
                    function(e)
                    {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        var target = $('#products a.product.active');
                        if(target.length == 0)return false;
                        
                        if(!('productInfo' in target[0]))
                        {
                            target[0].productInfo = eval('(' + target[0].getAttribute('data-product-info') + ')');
                            target[0].removeAttribute('data-product-info');
                        }
                        
                        productListManager.setActive(target[0].productInfo, this.getAttribute('data-reference'));
                        menuController.manuallyChanged = true;
                        self.location.hash = '#reference:' + this.getAttribute('data-reference');
                        return true;
                    }
                );
                
                /* Navegação entre imagens */
                $('#details li.details a.other').live
                (
                    'click',
                    function(e)
                    {
                        e.stopPropagation();
                        e.preventDefault();
                        
                        var current = this,
                            items   = $('#details li.details a.other').each
                            (function(){$(this)[this == current ? 'addClass' : 'removeClass']('active');}),
                            position= items.index(current);
                        
                        $('#details div.pics ul').animate
                        ({'margin-left': -($('#details div.pics li:eq(' + position + ')').position()).left},'fast');

                    }
                );
                
                /* Zoom */
                var zoomIndicator = null, pos, win, max = {x: 0, y: 0}, zoomSize = {width:138, height: 128}, currentImage ,zoomed;
                
                $('#details div.pics div.mask').bind
                (
                    'mouseenter',
                    function(e)
                    {
                        if(this.getAttribute('data-zoom') != '')
                        {
                            /* Máscara de zoom que fica sobre a imagem */
                            if(zoomIndicator == null)
                            {
                                zoomIndicator = $('<div class="zoom-indicator"></div>').bind
                                (
                                    'mouseleave',
                                    function(e)
                                    {
                                        var me     = $(this), pos = me.offset(), size = {width: zoomSize.width, height: zoomSize.height},
                                            limits = {top: pos.top, left: pos.left};
                                            
                                        if(parseInt(me.css('top')) != 0)limits.top   += size.height;
                                        if(parseInt(me.css('left')) != 0)limits.left += size.width;
                                        
                                        /* Previne o bubbling do evento enquanto se está com o cursor na área de zoom para que a visualização continue disponível */
                                        if((e.clientX - limits.left) > 0 && (e.clientY - limits.top) > 0)
                                        {
                                            e.stopPropagation();
                                            e.preventDefault();                                            
                                        }
                                        
                                        return true;
                                    }
                                );
                            }
                        
                            if(e.target.tagName.toLowerCase() == 'img')
                            {
                                pos      = $(e.target).offset();
                                win      = $(window);
                                var here = $(this);
                                
                                max.x = parseInt(here.css('width')) - zoomSize.width - 2;
                                max.y = parseInt(here.css('height')) - zoomSize.height - 2;
                                
                                $('#details #zoom-mask')
                                    .html('<img src="' + e.target.getAttribute('data-zoom') + '" alt="" />')
                                    .css({top: $('#details ul.about li.color').position().top});
                                
                                zoomed      = $('#details #zoom-mask img');
                                currentImage= $(e.target);
                            }
                                
                            $('#details div.mask').append(zoomIndicator.css({display:'none'}));
                            
                            $('#details #zoom-mask').fadeIn('medium');
                            zoomIndicator.fadeIn('medium');
                        }
                    }
                ).bind
                (
                    'mousemove',
                    function(e)
                    {
                        if(zoomIndicator && pos)
                        {
                            var positions = {top : e.clientY - pos.top  - Math.round(zoomSize.height / 2) + win.scrollTop(),
                                             left: e.clientX - pos.left - Math.round(zoomSize.width / 2)  + win.scrollLeft()};


                            if(positions.top  < 0)positions.top = 0;
                            if(positions.top > max.y)positions.top = max.y;
                            
                            if(positions.left < 0)positions.left= 0;
                            if(positions.left > max.x)positions.left = max.x;
                            
                            /* Deslocamento proporcional da imagem */
                            if(currentImage)
                            {
                                var scales =
                                {
                                    x: parseInt(zoomIndicator.css('left')) / currentImage.outerWidth(),
                                    y: parseInt(zoomIndicator.css('top')) / currentImage.outerHeight()
                                };
                                
                                zoomed.css({top: -Math.round(zoomed.outerHeight() * scales.y), left: -Math.round(zoomed.outerWidth() * scales.x)});
                            }
                            
                            zoomIndicator.css(positions);
                        }
                    }
                ).bind
                (
                    'mouseleave',
                    function(e)
                    {
                        if(zoomIndicator)
                        {
                            $('#details #zoom-mask').fadeOut('medium');
                            zoomIndicator.fadeOut('medium');
                        }
                        
                        return false;
                    }
                );
                
                /* Voltar para a lista de produtos */
                $('#details div.share a.close').bind
                (
                    'click',
                    function(e)
                    {
                        menuController.parseHash(this.getAttribute('href'), e, self.location.hash.indexOf('wishlist') == -1 && menuController.lastHash != null ? true : null);
                    }
                );
                
                /* Special search */
                $('#details div.actions a.special-search').bind
                (
                    'click',
                    function(e)
                    {
                        menuController.parseHash(this.getAttribute('href'), e, true);
                        return true;
                    }
                );
                
                /* Botão "voltar" da lista de produtos */
                $('#products a.to-search').live
                (
                    'click',
                    function(e)
                    {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        $('html, body').animate({scrollTop: $('#menu').offset().top},'medium');
                    }
                );
                
                /* Adicionar à wishlist */
                $('#details div.actions a.wishlist-add').bind
                (
                    'click',
                    function(e)
                    {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        var reference   = this.getAttribute('href').split('#')[1],
                            wishlist    = cookieManager.get('wishlist'),
                            action      = '';
                        
                        if(!productListManager.isInWishlist(reference))
                        {                            
                            if(wishlist == '' || wishlist == null)wishlist = [];
                            else wishlist = wishlist.split(',');
                            
                            if(wishlist.length >= 60)
                            {
                                alert('A sua wishlist comporta no máximo 60 itens.');
                                return false;
                            }
                            
                            wishlist.push(reference);
                            action = 'add';
                        }
                        else
                        {
                            wishlist = wishlist.split(',');
                            for(var counter = 0, size = wishlist.length;counter < size;counter++)
                                if(wishlist[counter] == reference)
                                {
                                    wishlist.splice(counter, 1);
                                    break;
                                }
                                
                            action = 'remove';
                        }
                        
                        cookieManager.set('wishlist', wishlist.join(','));
                            
                        $('#menu li.list-cadeaux span').html(wishlist.length == 1 ? '1 item' : wishlist.length + ' itens');
                        $(this)[action == 'add' ? 'addClass' : 'removeClass']('already-in-list').find('span').html(action == 'add' ? 'Remover' : 'Adicionar');
                        return true;
                    }
                );
            },
            /* Pega a cor atualmente selecionada */
            getColor: function(colors, index)
            {
                if(index == null)
                {
                    for(var counter = 0;counter < colors.length;counter++)
                        if(colors[counter].defaultColor){index = counter;break;}
                        
                    if(index == null || colors.length < index)return false;
                    return colors[index];
                }
                
                return colors[index];
            },
            /* Pega as outras cores */
            getOtherColors: function(colors, index)
            {
                var returnData = [];
                if(index == null)
                    for(var counter = 0, size = colors.length;counter < size;counter++)
                        if(colors[counter].defaultColor){index = counter;break;}
                
                for(var counter = 0, size= colors.length;counter < size;counter++)
                {
                        returnData.push
                        ('<a href="#" class="color',
                            (counter == index ? ' hide' : ''),
                            '"',
                            'data-color-title="',      colors[counter].title, '"', " ",
                            'data-reference="',        colors[counter].reference, '" ',
                            'data-value="',            colors[counter].value, '" ',
                            'data-group-name="',       colors[counter].groupName, '" ',
                            'data-group-image="',      colors[counter].groupImage, '" ',
                            'data-group-hash="',       colors[counter].groupHash, '" ',
                            "data-images='",           colors[counter].images, "' ",
                            'title="',           colors[counter].title, '" ',
                            '>',
                            '<img src="', colors[counter].image,'" alt="Cor" />',
                            '</a>');
                }
                
                return returnData.join('').replace('=?','');
            },
            /* Pega as imagens relacionadas ao produto, versão thumbs */
            getDetails: function(colors, index)
            {
                if(index == null)
                    for(var counter = 0, size = colors.length;counter < size;counter++)
                        if(colors[counter].defaultColor){index = counter;break;}
                
                if(index == null)return '';
                
                var returnData = [], images = eval('(' + colors[index].images + ')');
                for(var counter = 0, size = images.length;counter < size;counter++)
                {
                    returnData.push
                    (
                        '<a href="#" class="other', (counter == 0 ? ' active' : ''), '" ',
                        'data-image="', images[counter].normal, '" ',
                        'data-zoom="', images[counter].zoom, '">',
                        '<img src="', images[counter].normal, '" width="39" height="39" />',
                        '</a>'
                    );
                }
                
                return returnData.join('').toString();
            },
            /* Pega as imagens relacionadas ao produto, versão pics */
            getPics: function(colors, index)
            {
                if(index == null)
                    for(var counter = 0, size = colors.length;counter < size;counter++)
                        if(colors[counter].defaultColor){index = counter;break;}
                
                if(index == null)return '';
                
                var returnData = [], images = eval('(' + colors[index].images + ')');
                for(var counter = 0, size = images.length;counter < size;counter++)
                {
                    returnData.push
                    (
                        '<li class="inb">',
                            '<img src="',images[counter].normal,'" data-zoom="', images[counter].zoom, '" width="485" height="485" />',
                        '</li>'
                    );
                }
                
                return returnData.join('');
            },
            /* Pega os posts ao produto */
            getRelated: function(colors, index)
            {
                if(index == null)
                    for(var counter = 0, size = colors.length;counter < size;counter++)
                        if(colors[counter].defaultColor){index = counter;break;}
                
                if(index == null)return '';
                
                var returnData = [];
                for(var counter = 0, size = colors[index].relatedPosts.length;counter < size;counter++)
                {
                    returnData.push
                    (
                        '<li class="item">',
                            '<a href="', colors[index].relatedPosts[counter].url, '" target="_blank">',
                            colors[index].relatedPosts[counter].title,
                            '</a>',
                        '</li>'
                    );
                }
                
                return returnData.join('');
            },
            /* Verifica se um produto já consta na wishlist */
            isInWishlist: function(reference)
            {
                var wishlist = cookieManager.get('wishlist');
                if(wishlist == null)wishlist = '';
                wishlist = wishlist.split(',');
                
                for(var counter = 0, size = wishlist.length;counter < size;counter++)
                    if(wishlist[counter] == reference){return true;}
                
                return false;
            },
            /* Exibe informações do produto com a referência informada */
            setActive: function(product, reference, skipAnimation)
            {
                var color = null, index = 0;
                
                for(var counter = 0, size = product.colors.length;counter < size;counter++)
                {
                    if(product.colors[counter].reference == reference)
                    {
                        color = product.colors[counter];
                        index = counter;
                        break;
                    }
                }
                
                if(color == null)return false;
                
                $('#content #details').slideDown
                (
                    'medium',
                    function()
                    {
                        /* Share - Twitter */
                        var twitter = $('#details div.twitter a');
                        twitter.attr('href', twitter.attr('data-base-url') + '&url=http://' + self.location.hostname + self.location.pathname + '?reference=' + color.reference + '&text=' + product.title);
                        
                        /* Share - Facebook */
                        var face    = $('#details div.share iframe.facebook');
                        face.attr('src', face.attr('data-base-url') + '&href=http://' + self.location.hostname + self.location.pathname + '?reference=' + color.reference);
                        
                        /* Voltar para a listagem de produtos */
                        var hash    = self.location.hash;
                        if(hash.indexOf('#') == 0)hash = hash.substring(1);
                        if(hash.length == 0)hash = product.category;
                        
                        $('#details div.share a.close').attr('href', '#' + menuController.lastHash);
                        $('div.carrousel a.moreInfo').attr('href', '#' + menuController.lastHash);
                        
                        /* Adicionar à wishlist */
                        $('#details div.actions a.wishlist-add').attr('href', '#' + color.reference)
                            [productListManager.isInWishlist(color.reference) ? 'addClass' : 'removeClass']('already-in-list')
                            .find('span').html(productListManager.isInWishlist(color.reference) ? 'Remover' : 'Adicionar');
                        
                        /* Special search */
                        $('#details div.actions a.special-search').attr('href', '#special-search/' + product.category);
                        
                        
                        /* Título */
                        $('#details div.info h1').html(product.title);
                        $('div.carrousel h2 span').html(product.category);
						
                        /* Descrição */
                        $('#details div.info p.description').html(color.description);
                        /* Referência */
                        $('#details p.reference span').html(color.reference);
                        /* Valor */
                        $('#details p.value span').html(color.value);
                        
                        /* Cor */
                        $('#details li.color span').html(color.title);
                        /* Nome do grupo e hash */
                        $('#details li.color a.more span')
                            .html(color.groupName).parent().attr('href', '#' + color.groupHash);
                        /* Outras cores */
                        var data    = productListManager.getOtherColors(product.colors, index).toString(),
                            colors  = $('#details li.other-colors span').html(data).html(data),
                            count   = $('#details li.other-colors a.color');
                        
                        if(skipAnimation)
                            $('#details li.other-colors').css({'display': count.length > 1 ? 'block' : 'none'});
                        else
                            $('#details li.other-colors')[count.length > 1 ? 'slideDown' : 'slideUp']('fast');
                        
                        /* Construção */
                        $('#details li.construction span').html(product.construction.title);
                        $('#details li.construction a.more').attr('href', '#' + product.construction.hash);
                        
                        /* Material */
                        $('#details li.material > span').html(product.material.title);
                        $('#details li.material a.more').attr('href', '#' + product.material.hash).find('span').html(product.material.type);
                        
                        /* Detalhes: fotos */
                        $('#details li.details span').html(productListManager.getDetails(product.colors, index));
                        var count = $('#details li.details span a.other').length;
                        
                        $('#details li.details')[count > 1 ? 'slideDown' : 'slideUp']('fast');
                        
                        /* Posts do blog relacionados */
                        $('#details ul.related li.item').remove();
                        $('#details ul.related').append(productListManager.getRelated(product.colors, index));
                        var count = $('#details ul.related li.item').length;
                        
                        if(skipAnimation)
                            $('#details ul.related').css({'display': count > 1 ? 'block' : 'none'});
                        else
                            $('#details ul.related')[count != 0 ? 'slideDown' : 'slideUp']('fast');
                        
                        /* Imagens para visualização */
                        $('#details div.pics div.mask ul').html(productListManager.getPics(product.colors, index)).animate({'margin-left':0},'fast');
                    
                        return true;
                    }
                );
                
                return true;
            },
            /* Carregador via AJAX de produtos */
            loader: function(data)
            {
                transitionManager.remove
                (
                    $('#products div.content'),
                    function()
                    {
                    	if( jQuery.trim(data) != "<ul></ul>" )
                    	{
							$('div.infoSendFriend').slideUp();
	                        $('#products div.content').html(data).animate({height:'show'},'slow', function()
	                        {
	                            $('body').animate({scrollTop: $('#menu').offset().top},'medium', function()
	                            {
	                                $('#product-more').animate({height:hasNextPage.attr('data-last-page') == 'yes' || data == '' ? 'hide' : 'show'},'fast').attr('data-last-page',hasNextPage.attr('data-last-page'));
	                                hasNextPage.removeAttr('data-last-page');
	                            });
	                            
	                            $('#product-more a').attr('data-current-page',1);
	                                
	                            var hasNextPage = $('#products li[data-last-page]');
	                            
	                            return true;
	                        });
                       }
                       else
                       {
							$('div.infoSendFriend').slideUp();
	                        $('#products div.content').html("<h3>Nenhum produto encontrado.</h3>").animate({height:'show'},'slow', function()
	                        {
	                            $('body').animate({scrollTop: $('#menu').offset().top},'medium', function()
	                            {
	                                $('#product-more').animate({height:'hide'},'fast').attr('data-last-page',hasNextPage.attr('data-last-page'));
	                                hasNextPage.removeAttr('data-last-page');
	                            });
	                            
	                            $('#product-more a').attr('data-current-page',1);
	                                
	                            var hasNextPage = $('#products li[data-last-page]');
	                            return true;
	                        });
                       }
                        return true;
                    }
                );
            },
            /* Inicialização do botão "mais" */
            initMore: function()
            {
                $('#product-more a').bind
                (
                    'click',
                    function(e)
                    {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        var target  = $(this);
                        if(target.attr('data-current-page') == null)target.attr('data-current-page','1');
                        var nextPage=parseInt(target.attr('data-current-page')) + 1;
                        
                        if(!('running' in target[0]))
                            target[0].running = false;
                        
                        var params = productListManager.lastQueryParams, image = target.find('img').attr('src');
                        params['p'] = nextPage;

                        if(!target[0].running)
                        {
                            target[0].running = true;
                            target.find('img').attr('src', 'content/img/ajax-loader.gif');
                            
                            $.post('services/products/index.php',params,function(data)
                            {
                                target.find('img').attr('src', image);
                                
                                $('#products div.content').append(data);
                                $('html, body').animate({scrollTop: target.offset().top + 28},'medium');
                                target.attr('data-current-page',nextPage);
                                
                                var hasNextPage = $('#products li[data-last-page]');
                                if(hasNextPage.attr('data-last-page') == 'yes')
                                    $('#product-more').animate({height:'hide'},'fast').attr('data-last-page','yes');
                                hasNextPage.removeAttr('data-last-page');
                                
                                target[0].running = false;
                            });                             
                        }                       
                        
                        return true;
                    }
                );
            }
        };
        
        /* Gerenciador das transições */
        transitionManager =
        {
            /* Remove todos os itens */
            remove: function(collection, doAfter)
            {
                if(collection.is(':visible'))
                    collection.animate({height:'hide'},'medium', doAfter);
                else
                    doAfter.apply([this]);
            },
            /* Exibe ordenadamente todos os itens informados */
            show: function(collection)
            {
                var position = 0, action = function()
                {
                    if(position < collection.length)
                    {
                        collection.eq(position).animate({width:'hide'}, 'medium', action);
                        position++;
                    }
                    return true;                    
                }
            }
        };
        
        /* Gerenciador da wishlist */
        wishlistManager =
        {
            showShareLinks: function()
            {
                var wishlist = cookieManager.get('wishlist');
                
                if(wishlist == '')wishlist = [];
                else wishlist = wishlist.split(',');
                
                if(wishlist.length != 0)
                {
                    $('#nav-detail div.heading p.title')
                        .html
                        ('Compartilhe sua wishlist&nbsp;&nbsp;' +
                            '<div class="twitter inb">' +
                                '<a href="http://twitter.com/share?via=santa_lolla&amp;url=http://' + self.location.hostname + self.location.pathname + '%3Fwishlist=' + wishlist.join(',') + '&amp;text=Minha wishlist" target="_blank">' +
                                    '<img alt="" src="content/img/blog/ico-twitterPost.gif">' +
                                '</a>' +
                            '</div>' +
                            '<iframe frameborder="0" class="facebook inb" allowtransparency="true" style="border: medium none; overflow: hidden;" src="http://www.facebook.com/plugins/like.php?layout=button_count&amp;show_faces=true&amp;action=recommend&amp;colorscheme=light&amp;height=21&amp;width=100&amp;href=http://' + self.location.hostname + self.location.pathname + '%3Fwishlist=' + wishlist.join(',') + '"><!--Facebook--></iframe>' + 
							'<div class="sendEmailWishlist">' +
								'<a href="#" title="Envie para um amigo">Envie para um amigo</a>' +
							'</div>'
                        );
						
						$('#content').append('<div class="infoSendFriend ajusteFriend friendBox2">'+						
							'<h2>Envie por email <span class="closeFriend">Fechar</span></h2>' +
							'<form action="content/includes/email.php" method="post" id="formSendFriend">' +									
								'<label for="seuNome">Seu Nome</label>' +
								'<input type="text" name="seuNome" id="seuNome" />' +
								'<label for="seuEmail">Seu e-mail</label>' +
								'<input type="text" name="seuEmail" id="seuEmail" />'+
								'<label for="nomeFriend">Nome do destinatário</label>'+
								'<input type="text" name="nomeFriend" id="nomeFriend" />'+
								'<label for="emailFriend">Email do destinatário</label>'+
								'<input type="text" name="emailFriend" id="emailFriend" />'+
								'<label for="mensagem">Mensagem</label>'+
								'<textarea name="mensagem" id="mensagem"></textarea>'+
								'<input type="hidden" name="url" value="http://' + self.location.hostname + self.location.pathname + '%3Fwishlist=' + wishlist.join(',') + '" />'+
								'<input type="submit" name="enviar" id="enviar" value="Enviar" />'+
								'<div class="clear"></div>'+
							'</form>'+
						'</div>'
					);
						
						
                }
                else
                {
                    $('#nav-detail div.heading p.title').html('');
                }
            }
        };
        
        $(document).ready
        (
            function()
            {
                /* Limpar seleção */
                $('#nav-detail div.actions a.clear').bind
                (
                    'click',
                    function(e)
                    {
                        e.preventDefault();
                        e.stopPropagation();
                        
                        $('#nav-detail #items a.active').removeClass('active');
                        specialSearchController.setCurrentHash();
                    }
                );
                
                
                /* Parâmetros de pesquisa */
                $('#nav-detail form.params input.checkbox').bind
                (
                    'click',
                    function(e)
                    {
                        menuController.manuallyChanged = true;
                        self.location.hash = showOnlyController.modifyHash(self.location.hash);
                        menuController.parseHash( self.location.hash );
                        return true;
                    }
                );
                
                /* Inicializa os checkboxes de pesquisa */
                showOnlyController.init();
                
                /* Inicializa o mecanismo de exibição de detalhes de produto */
                productListManager.init();
                
                /* Inicializa o botão "mais" */
                productListManager.initMore();
                
                /* Mudança de hash */
                $(window).bind
                (
                    'hashchange',
                    function(e)
                    {
                        if(!menuController.manuallyChanged)
                            menuController.parseHash(self.location.hash);
                        //alert( menuController.manuallyChanged );
                        menuController.manuallyChanged = false;
                    }
                );
				
				
				$('div.sendEmail a').live('click', function(e){
					e.preventDefault();
					$('div.friendBox1').slideToggle();
				});
				
				$('div.sendEmailWishlist a').live('click', function(e){
					e.preventDefault();
					$('div.friendBox2').slideToggle();
				});
				
				$('span.closeFriend').live('click', function(e){
					e.preventDefault();
					$('div.infoSendFriend').slideUp();
				});
				
				
				

				
            }
        );
    }
)(jQuery);

function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}



