// Popups
(function(){

    function cleartime()
    {
        if (window.popup_timer)
        {
            clearTimeout(window.popup_timer);
            window.popup_timer = null;
        }
    }

    function close()
    {
        if (window.popup_timer)
        {
            $('#facebox').find('.close').click();
            window.popup_timer = null;
        }
    }

    window.popup1 = function(text, time, width)
    {
        time = time ? time : 3000;
        width = width ? width : 600;
        cleartime();
        $.facebox('<div class="pop_heading" style="width: ' + width  +'px; font-size: 23px; margin-bottom: -12px; text-align: center;">' + text + '</div>');
        window.popup_timer = setTimeout(function() {
            close();
        }, time);
    }

    window.popup_forthcoming = function(date_str)
    {
        cleartime();
        var text2 = '<div style="color: #777; line-height: 1.3; text-align: center;">You are able to purchase the release, but it will be available for download only when the offical release date arrives - that\'s <strong>' + date_str + '</strong>. You will receive a notification by email that day so you won\'t forget to download!</div>';
        $.facebox('<div class="pop_heading" style="width: 500px; font-size: 34px; margin-bottom: 12px; text-align: center;">Forthcoming Release</div>' + text2);
        window.popup_timer = setTimeout(function() {
            close();
        }, 6000);
    }

    window.popup_exclusive = function(date_str)
    {
        cleartime();
        var text2 = '<div style="color: #777; line-height: 1.3; text-align: center;">This release is exclusive - it is available to buy only at Soundium until <strong>' + date_str + '</strong>!</div>';
        $.facebox('<div class="pop_heading" style="width: 500px; font-size: 34px; margin-bottom: 12px; text-align: center;">Exclusive Release</div>' + text2);
        window.popup_timer = setTimeout(function() {
            close();
        }, 5000);
    }

})()

window.update_client_info = function() {
    $.getJSON('/update_client_info/', function(data) {
        if (data.logged_in)
        {
            $('.footbar-logged-in').show();
            $('.footbar-not-logged-in').hide();
            $('.client-first-name').html(data.client_first_name);
        }
        else
        {
            $('.footbar-logged-in').hide();
            $('.footbar-not-logged-in').show();
        }
        
        var $footbar = $('#footbar');
        
        $footbar.find('.cart_items').html(data.cart_items_length);
        $footbar.find('.cart_total').html(data.cart_total);
        $footbar.find('.wishlist_items').html(data.wishlist_items_length);

        if (data.need_merge)
        {
            $.get('/cart/merge/', function(html) {
                $.facebox(html);
            });
        }
    });
}

// On DOM ready
$(function() {

    $('body').delegate('.label-artist-letter', 'click', function(e) {
        var letter = $(this).html().toLowerCase();
        var alphabet = 'abcdefghijklmnopqrstuvwxyz';

        $(this).addClass('active').siblings().removeClass('active');

        if (letter == 'all')
        {
            $('.grid_items .grid-item').removeClass('last-in-row').show();

            $('.grid_items .grid-item:nth-child(5n)').addClass('last-in-row');
        }
        else
        {
            $('.grid_items .grid-item').hide();

            var to_show = $('.grid_items .grid-item-fletter-' + letter)
            
            to_show.show().removeClass('last-in-row');
            $.each(to_show, function(index, value) {
                if ((index + 1) % 5 == 0)
                {
                    $(value).addClass('last-in-row');
                }
            });
        }

        return false;
    });

    // Follow icon
    $('#content').delegate('.follow_icon, .follow, .follow-icon', 'click', function() {
    
        var
            $this = $(this),
            q = $this.attr('data-label-id')
                ? 'label_id='  + $this.attr('data-label-id')
                : 'artist_id=' + $this.attr('data-artist-id');

        if ( ! $this.hasClass('unfollow'))
        {
            load_content('/follow/?' + q, false, 'get', {}, false, false);
        }
        else
        {
            load_content('/unfollow/?' + q, false, 'get', {}, false, false);
        }
    });

    function SelectText(element) {
        var text = element;
        if ($.browser.msie) {
            var range = document.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else if ($.browser.mozilla || $.browser.opera) {
            var selection = window.getSelection();
            var range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
        } else if ($.browser.safari) {
            var selection = window.getSelection();
            selection.setBaseAndExtent(text, 0, text, 1);
        }
    }

    $('body').delegate('.embed-code-body', 'click', function(e) {

        if ($(this).is('input'))
        {
            this.select();
        }
        else
        {
            SelectText(this);
        }
    });

    // Download links 
    $('body').delegate('a.forthcoming', 'click', function(e) {
        popup1('This product will be available from ' + $(this).data('release_date'));  
        e.preventDefault();
        return false;
    });

    // Forthcoming indicators
    $('body').delegate('.forthcoming-indicator', 'click', function(e) {
        popup_forthcoming($(this).data('date'));  
        e.preventDefault();
        return false;
    });

    // Exclusive indicators
    $('body').delegate('.exclusive-indicator', 'click', function(e) {
        popup_exclusive($(this).data('date'));  
        e.preventDefault();
        return false;
    });
    
    // .table2 tr hover styles
    $('body').delegate('.table2 tr', 'mouseenter mouseleave', function(e) {

        var tr = $(this).closest('tr');
        
        if (e.type === 'mouseenter')
        {
            tr.addClass('has-mouse'); 
            tr.addClass('hover');
        }
        else
        {
            tr.removeClass('has-mouse');
            if ( ! tr.find('.star_dropbox').size())
            {
                tr.removeClass('hover');
            }
        }    
    });
    
    // Facebox popups
    $('body').delegate('[rel*=facebox]', 'click', function() {
    
        var $this = $(this);
    
        if ( ! $this.hasClass('faceboxed'))
        {
            $this.facebox({
                closeImage: '/static/css_client/img/popup_close.gif',
                loadingImage: '/static/css_client/img/ajax-loader_popup.gif'
            }).click();
        }
    });
    
    $(document)
    
        // Disable all facebox buttons while one is loading
        .bind('loading.facebox', function() {
            $('[rel=facebox]').attr('disabled', 'disabled');
        })
        
        // Enable the facebox buttons after facebox close
        .bind('reveal.facebox', function() {
            $('[rel=facebox]').removeAttr('disabled');
        });
        
    // Social icons hover effect
	$('.social_icon').hover(function() {
		var pos = $(this).attr('data-position');
		$(this).css('backgroundPosition', pos + 'px -29px');
	}, function() {
		var pos = $(this).attr('data-position');
		$(this).css('backgroundPosition', pos + 'px 0px');
	});
    
    // Top banners
    $("#top_banner").faded({
        speed: 500,
        crossfade: true,
        bigtarget: false,
        loading: true,
        autoplay: 30000,
        autorestart: 30000,
        random: true,
        autopagination: false,
        autoheight: 100
    });

    $('body').delegate('.colorpicker_wrapper', 'mouseenter mouseleave', function(e) {
        $(this).toggleClass('has-mouse');

        if (e.type == 'mouseleave')
        {
            $('#facebox .colorpicker_icon').mouseout();
        }
    });
    
    $('body').delegate('.colorpicker_icon', 'click mouseenter mouseleave', function(e) {

        var $this = $(this),
        wrapper = $('#facebox .colorpicker_wrapper');

        if ($this.data('enter'))
        {
            clearTimeout($this.data('enter'));
            $this.data('enter', null);
        }

        if ($this.data('leave'))
        {
            clearTimeout($this.data('leave'));
            $this.data('leave', null);
        }
    
        if (e.type == 'mouseleave')
        {
            $this.removeClass('has-mouse');
            $this.data('leave', setTimeout(function() {
                if ( ! wrapper.hasClass('has-mouse'))
                {
                    $('#facebox .colorpicker_wrapper').hide();        
                }
            }, 500));
        }

        if (e.type == 'mouseenter')
        {
            $this.addClass('has-mouse');
            $this.data('enter', setTimeout(function() {
                if ($this.hasClass('has-mouse'))
                {
                    $this.click();
                }
            }, 250));
        }

        if (e.type == 'click')
        {
            if (wrapper.hasClass('colorpicker_initiated'))
            {
                wrapper.show();
                return;
            }

            if (window.color === '')
            {
                window.color = window.default_color;
            }

            wrapper.addClass('colorpicker_initiated');
            wrapper.show();        
            $('#facebox .color_input').val(color);
            $('#facebox .colorpicker').farbtastic('#facebox .color_input');
            $('#facebox .color_input').unbind('change_color').bind('change_color', function() {
                window.color = $(this).val();

                var p = $('#flash_player_preview');

                if (navigator.appName.indexOf("Microsoft") != -1) {
                    return window['flash_player_preview'].setColor(window.color.replace('#', ''));
                } else {
                    return document['flash_player_preview'].setColor(window.color.replace('#', ''));
                }

                $('#preview1, #preview2, #preview3').val(window.color);
            });
        }
    });

});

