// On DOM ready
$(function() {

    $('#grid-item-cloned, #content, #jplayer_playlist, #footbar')
    
        // Play icon
        .delegate('[class*=play]:not([class*=add2play])[class*=icon][data-track]', 'click', function(e) {
          
            var
                track_ids = $(this).attr('data-track'),
                li_items = $('#jplayer_playlist ul li');
      
            $.getJSON('/release/get_tracks/?track_ids=' + track_ids, function(r) {
            
                $.each(r, function(index, value) {
                    $('#jplayer_playlist ul').append('\
                        <li \
                            data-track-id="' + index + '"\
                            data-track-waveform="/static/' + value.waveform_path + '"\
                            data-track-path="/static/' + value.path + '"\
                            data-track-img1="/static/' + value.release_image_29x13 + '"\
                            data-track-img2="/static/' + value.release_image_29x29 + '"\
                            data-track-img3="/static/' + value.release_image_42x31 + '"\
                            data-track-price="' + value.price + '"\
                            data-track-label-name="' + value.label_name + '"\
                            data-track-label-url="' + value.label_url + '"\
                            data-track-artists-url="' + encodeURIComponent(value.artists_url) + '"\
                            data-track-release-url="' + value.release_url + '"\
                            data-track-genres="' + value.genres + '"\
                            data-track-artists="' + value.artists + '"\
                            data-track-title="' + value.title + '">\
                                <img class="release_img3" src="/static/' + value.release_image_29x13 + '" />\
                                <span class="track">' + value.artists + ' - ' + value.title + '</span>\
                                <span class="del5_icon" data-track=""></span>\
                                <span class="buy5_icon" data-track="' + index + '"></span>\
                        </li>');
                });
                
                var tracks_count = $('.playlist_tracks_count .count');
                var tracks_count_count = tracks_count.html() * 1;
                
                tracks_count.html(tracks_count_count + _(r).size());
                
                $('#jplayer_playlist ul li:eq(' + tracks_count_count + ')').click();
            }); 
        })
  
      // Click on add2play(list)
      .delegate('[class*=add][class*=icon][data-track]', 'click', function() {
        
        var
            track_ids = $(this).attr('data-track'),
            li_items = $('#jplayer_playlist ul li');
      
        $.getJSON('/release/get_tracks/?track_ids=' + track_ids, function(r) {
            
            $.each(r, function(index, value) {
                $('#jplayer_playlist ul').append('\
                    <li \
                        data-track-id="' + index + '"\
                        data-track-waveform="/static/' + value.waveform_path + '"\
                        data-track-path="/static/' + value.path + '"\
                        data-track-img1="/static/' + value.release_image_29x13 + '"\
                        data-track-img2="/static/' + value.release_image_29x29 + '"\
                        data-track-img3="/static/' + value.release_image_42x31 + '"\
                        data-track-price="' + value.price + '"\
                        data-track-label-name="' + value.label_name + '"\
                        data-track-label-url="' + value.label_url + '"\
                        data-track-artists-url="' + encodeURIComponent(value.artists_url) + '"\
                        data-track-release-url="' + value.release_url + '"\
                        data-track-genres="' + value.genres + '"\
                        data-track-artists="' + value.artists + '"\
                        data-track-title="' + value.title + '">\
                            <img class="release_img3" src="/static/' + value.release_image_29x13 + '" />\
                            <span class="track">' + value.artists + ' - ' + value.title + '</span>\
                            <span class="del5_icon" data-track=""></span>\
                            <span class="buy5_icon" data-track="' + index + '"></span>\
                    </li>');
            });
            
            var tracks_count = $('.playlist_tracks_count .count');
            tracks_count.html((tracks_count.html() * 1) + _(r).size());
        }); 
      })
      
      .delegate('[class*=buy][class*=icon]', 'click', function() {

        if ($(this).hasClass('unsave') || $(this).hasClass('disabled'))
        {
            return;
        }

        if ($(this).hasClass('jp-choices-icon') && ( ! $('#footbar .jp-photo').attr('style')))
        {
            return;
        }

        if ($(this).hasClass('sell-in-full'))
        {
            $.facebox(sell_in_full_text);
            setTimeout(function() { $('#facebox').find('.close').click(); }, 3000); 
            return false;
        }
        
        var
            $this = $(this),
            type = 'track', // Default
            id = null;
            
        if ($this.hasClass('in-cart'))
        {
            $.facebox(duplicate_product_text);
            setTimeout(function() { $('#facebox').find('.close').click(); }, 3000);
            return;
        }

        if ($this.hasClass('release-in-cart'))
        {
            $.facebox('<div class="pop_heading" style="width: 545px; font-size: 22px; margin-top: 0; margin-bottom: 0px; text-align: center;">You have the full release in your shopping cart.</div>\
                <p style="line-height: 1.5; margin-top: 0px; font-size: 13px; margin-bottom: -23px; color: #4D4D4D; text-align: center;">First remove the release from your cart to add only this track.</p>');
            setTimeout(function() { $('#facebox').find('.close').click(); }, 5000);
            return;
        }
  
        if ($this.attr('data-release'))
        {
            type = 'release';
        }
        else if ($this.attr('data-chart'))
        {
            type = 'chart';
        }
  
        id = $this.attr('data-' + type);
        
        //load_content('/cart/add/?' + type + '_id=' + id, false, 'get', {}, false, false);
        ajaxStart();
        $.ajax({
            url: '/cart/add/?' + type + '_id=' + id,
            success: function() {
                $.gritter.add({
                    title: 'Added to cart',
                    text: '&nbsp;',
                });
                window.update_client_info();
            },
            complete: function() {
                ajaxStop();
            }
        });
        
      })

      // Grid icon dropdowns
      .delegate('.star-icon:not(.disabled), .download-icon, .actions-icon:not(.disabled)', 'open close click mouseenter mouseleave', function(e) {
          var $this = $(this);
          if (e.type === 'mouseenter')
          {
              $this.addClass('has-mouse');
              $this.data('timeout', setTimeout(function() {
                  if ($this.hasClass('has-mouse') && ! $this.hasClass('opened'))
                  {
                      $this.trigger('open');
                  }
              }, 150));
          }
          else if (e.type === 'mouseleave')
          {
              if ($this.data('timeout'))
              {
                  clearTimeout($this.data('timeout'));
                  $this.removeData('timeout');
                  $this.trigger('close');
              }
              $this.removeClass('has-mouse');
          }
          else if (e.type === 'open')
          {
              if ($this.hasClass('v2'))
              {
                  $this.closest('.track-icons').css('overflow', 'visible');
                  $this.closest('.track').css('overflow', 'visible');
                  $this.closest('.quick-look-container').css('overflow', 'visible');
                  if ( ! $this.closest('.valign-middle').hasClass('all-tracks-expanded'))
                  {
                      $this.closest('.track').siblings().find('.right-side').hide();
                  }
                  $this.closest('.grid-item').css('overflow', 'hidden');
              }
              if ($this.hasClass('page-release'))
              {
                  $this.closest('.loop-container').css('overflow', 'visible');
                  $this.closest('.loop-container').find('.grid-item:gt(2)').css('visibility', 'hidden');
              }
              $this.addClass('opened').find(' > .dropdown_').slideDown(100);
          }
          else if (e.type === 'close')
          {
              $this.removeClass('opened').find(' > .dropdown_').slideUp(100, function() {
                  if ($this.hasClass('v2'))
                  {
                      $this.closest('.track-icons').css('overflow', 'hidden');
                      $this.closest('.track').css('overflow', 'hidden');
                      $this.closest('.quick-look-container').css('overflow', 'hidden');
                      if ( ! $this.closest('.valign-middle').hasClass('all-tracks-expanded'))
                      {
                          $this.closest('.track').siblings().find('.right-side').show();
                      }
                      $this.closest('.grid-item').css('overflow', 'visible');
                  }
                  if ($this.hasClass('page-release'))
                  {
                      $this.closest('.loop-container').css('overflow', 'hidden');
                      $this.closest('.loop-container').find('.grid-item:gt(2)').css('visibility', 'visible');
                  }
              });
          }
          else if (e.type === 'click')
          {
              $this.trigger('open');
          }
      })
      
      .delegate('[class*=share][class*=_icon]', 'open close mouseenter mouseleave', function(e) {

        var $this = $(this), delay = 400;

        function close()
        {
            try {

            if( ! $this.hasClass('has-mouse') && ! $this.data('dropbox').hasClass('has-mouse'))
            {
                $this.trigger('close');
            }
            else
            {
                if ($this.data('timeout'))
                {
                    clearTimeout($this.data('timeout'));
                } 
                $this.data('timeout', setTimeout(function() { close(); }, delay));
            }

            }catch(e) {}
        }

        if (e.type === 'mouseenter')
        {
            $this.addClass('has-mouse');
            if ($this.data('timeout'))
            {
                clearTimeout($this.data('timeout'));
                $this.removeData('timeout');
            }

            if ($this.data('timeout2'))
            {
                clearTimeout($this.data('timeout2'));
                $this.removeData('timeout2');
            }

            $this.data('timeout2', setTimeout(function() {
                if ($this.hasClass('has-mouse') && ! $this.hasClass('opened')) $this.trigger('open');
            }, 150));
        }

        else if (e.type === 'mouseleave')
        {
            $this.removeClass('has-mouse');
            if ($this.data('timeout'))
            {
                clearTimeout($this.data('timeout'));
            }
            $this.data('timeout', setTimeout(function() { close(); }, delay));
        }

        // Close the dropbox event?
        else if (e.type === 'close')
        {
            $(this).removeClass('opened').parent().find('.star_dropbox').fadeOut(150, function() {
                $(this).remove();
            });

            if ($(this).closest('.table2').size() && ! $(this).closest('tr').hasClass('has-mouse'))
            {
                $(this).closest('tr').removeClass('hover');
            }
        }

        else if (e.type === 'open')
        {
            var
                $this = $(this),
                type = 'track', // Default
                id = null,
                top = $this.position().top + $this.outerHeight() - 3,
                left = Math.round($this.position().left - 41 - $this.outerWidth()/2 - $this.css('marginRight').replace('px', '') * 1);
            
            if ($this.hasClass('share4_icon')) left -= 7;
            if ($this.hasClass('share1_icon')) left -= 6;
            if ($this.hasClass('share2_icon')) left -= 9;
            type = $this.attr('data-release') ? 'release' : type;
            type = $this.attr('data-chart')   ? 'chart' : type;
            id = $this.attr('data-' + type);

            $this.addClass('opened');

            var drop = '<div class="star_dropbox" style="top: ' + top + 'px; left: ' + left  + 'px;">';
            
            drop += (get_url().indexOf('wishlist') != -1)
                ? '<span style="color: #bbb !important; cursor: default;">Add to Wishlist</span>'
                : '<span class="add_to_wishlist" data-type="' + type + '" data-id="' + id +'">Add to Wishlist</span>';

            /*
            drop += type == 'chart'
                ? '<a href="#" onclick="return false;" style="color: #bbb !important; cursor: default;" class="not_ajaxy">Add to Chart</a>'
                : '<a href="#" onclick="return false;" style="color: #bbb !important; cursor: default;" class="not_ajaxy">Add to Chart</a>'
                //: '<a class="not_ajaxy add_to_chart_link" data-' + type + '="' + id + '">Add to Chart</a>';
            */
            //drop += '<a class="not_ajaxy add_to_playlist_link" data-' + type + '="' + id + '">Add to Playlist</a>';
            drop += '<a class="not_ajaxy add_to_playlist_link" data-' + type + '="' + id + '" style="color: #bbb !important; cursor: default;" onclick="return false;">Add to Playlist</a>';
            drop += '</div>';

            $(drop).hover(function() {
                $(this).addClass('has-mouse');
                if ($this.data('timeout'))
                {
                    clearTimeout($this.data('timeout'));
                    $this.removeData('timeout');
                }
            }, function() {
                $(this).removeClass('has-mouse');
                if ($this.data('timeout'))
                {
                    clearTimeout($this.data('timeout'));
                }
                $this.data('timeout', setTimeout(function() { close(); }, delay));
            }).hide().appendTo($this.parent());

            $this.parent().children(':last').slideDown(150);

            $this.data('dropbox', $(drop));
         }  
      })

      .delegate('.add_to_wishlist2', 'click', function(e) {

        var
            $this = $(this),
            dropdown = $this.parent(),
            type = dropdown.attr('data-type'),
            id   = dropdown.attr('data-id');

        if ($this.hasClass('disabled'))
        {
            return;
        }

        if (dropdown.hasClass('in-wishlist'))
        {
            $.facebox(duplicate_wishlist_item_text);
            setTimeout(function() { $('#facebox').find('.close').click(); }, 3000);
            return;
        }

        if (dropdown.hasClass('release-in-wishlist'))
        {
            $.facebox('<div class="pop_heading" style="width: 545px; font-size: 22px; margin-top: 0; margin-bottom: 0px; text-align: center;">You have the full release in your wishlist.</div>\
                <p style="line-height: 1.5; margin-top: 0px; font-size: 13px; margin-bottom: -23px; color: #4D4D4D; text-align: center;">First remove the release from your wishlist to add only this track.</p>');
            setTimeout(function() { $('#facebox').find('.close').click(); }, 5000);
            return;
        }
                
        //load_content('/wishlist/add/?' + type + '_id=' + id, false, 'get', {}, false, false);

        ajaxStart();
        $.ajax({
            url: '/wishlist/add/?' + type + '_id=' + id,
            success: function() {
                $.gritter.add({
                    title: 'Added to wishlist',
                    text: '&nbsp;',
                });
                window.update_client_info();
            },
            complete: function() {
                ajaxStop();
            }
        });

        return;
       })
     
      // Add to wishlist in list items
      .delegate('.add_to_wishlist', 'click', function(e) {

        var
            star = $(this).parent().parent().find('[class*=share][class*=_icon]'),
            type = $(this).attr('data-type'),
            id   = $(this).attr('data-id');

        if (star.attr('data-ids') != undefined)
        {
            if ( ! star.attr('data-ids'))
            {
                $.facebox('<div class="pop_heading" style="width: 545px; font-size: 23px; margin-bottom: -12px; text-align: center;">No products to add to wishlist.</div>');
                setTimeout(function() { $('#facebox').find('.close').click(); }, 3000);
                return;
            }

            load_content('/wishlist/add_from_cart/?cart_item_ids=' + star.attr('data-ids'), false, 'get', {}, false, false);
            return;
        }        

        if (star.hasClass('in-wishlist'))
        {
            $.facebox(duplicate_wishlist_item_text);
            setTimeout(function() { $('#facebox').find('.close').click(); }, 3000);
            return;
        }

        if (star.hasClass('release-in-wishlist'))
        {
            $.facebox('<div class="pop_heading" style="width: 545px; font-size: 22px; margin-top: 0; margin-bottom: 0px; text-align: center;">You have the full release in your wishlist.</div>\
                <p style="line-height: 1.5; margin-top: 0px; font-size: 13px; margin-bottom: -23px; color: #4D4D4D; text-align: center;">First remove the release from your wishlist to add only this track.</p>');
            setTimeout(function() { $('#facebox').find('.close').click(); }, 5000);
            return;
        }
                
        //load_content('/wishlist/add/?' + type + '_id=' + id, false, 'get', {}, false, false);
        ajaxStart();
        $.ajax({
            url: '/wishlist/add/?' + type + '_id=' + id,
            success: function() {
                $.gritter.add({
                    title: 'Added to wishlist',
                    text: '&nbsp;',
                });
                window.update_client_info();
            },
            complete: function() {
                ajaxStop();
            }
        });

        return;
       });

       duplicate_product_text = '<div class="pop_heading" style="width: 545px; font-size: 23px; margin-bottom: -12px; text-align: center;">This product is already in your shopping cart.</div>';
       duplicate_wishlist_item_text = '<div class="pop_heading" style="width: 545px; font-size: 23px; margin-bottom: -12px; text-align: center;">This product is already in your wishlist.</div>';
       sell_in_full_text = '<div class="pop_heading" style="width: 545px; font-size: 23px; margin-bottom: -12px; text-align: center;">Sold in full release only.</div>';
    
       $('body')

            .delegate('a.expand-all-link', 'click', function(e) {
                if ($(this).html().indexOf('xpand') != -1)
                {
                    $('.reveal:not(.showing)').click();
                }
                else
                {
                    $('.reveal.showing').click();
                }
                var text = $(this).html();
                $(this).html($(this).data('text'));
                $(this).data('text', text);
                return false;
            })
        
            // View mode (list/grid) icons
            .delegate('div.grid_icon, div.list_icon', 'click', function() {
                var
                    $this      = $(this),
                    expand_all = $('.expand-all-link'),
                    list_items = $('div.list_items'),
                    grid_items = $('div.grid_items');
            
                if ($this.hasClass('active'))
                {
                    return;
                }
                
                $this.addClass('active');
               
                if (window.to_be_closed_grid_item)
                {
                    window.to_be_closed_grid_item.css('visibility', 'hidden').find('.quick-look-container .quick-look-button').click();
                    window.cloned_grid_item.removeClass('has-been-cloned');
                    window.cloned_grid_item.mouseout();
                }
 

                if ($this.hasClass('grid_icon'))
                {
                    expand_all.hide();
                    list_items.hide();
                    grid_items.show();
                    $this.next().removeClass('active');
                    $.get('/set_view_mode/?value=grid'); 
                }
                else
                {
                    expand_all.show();
                    grid_items.hide();
                    list_items.show();
                    $this.prev().removeClass('active');
                    $.get('/set_view_mode/?value=list'); 
                }                
            })

            // Gift a sound
            .delegate('.gift_a_sound_link', 'click', function() {
            
                var
                    $this = $(this),
                    get   = '';
                
                if ($this.attr('data-release'))
                {
                    get = '?release_id=' + $this.attr('data-release');
                }
                else if ($this.attr('data-track'))
                {
                    get = '?track_id=' + $this.attr('data-track');
                }
                else if ($this.attr('data-chart'))
                {
                    get = '?chart_id=' + $this.attr('data-chart');
                }
                else
                {
                    throw 'Element does not have one of the following attributes: "data-release", "data-track", "data-chart"';
                }
                
                $.facebox({ ajax: '/gift_a_sound/' + get });
            })

            .delegate('.add_to_chart_link', 'click', function() {

                return false;
                
                var
                    $this = $(this),
                    get   = '';

                if ($this.hasClass('disabled'))
                {
                    return;
                }
                
                if ($this.attr('data-release'))
                {
                    get = '?release_id=' + $this.attr('data-release');
                }
                else if ($this.attr('data-track'))
                {
                    get = '?track_id=' + $this.attr('data-track');
                }
                else if ($this.attr('data-chart'))
                {
                    get = '?chart_id=' + $this.attr('data-chart');
                }
                else
                {
                    throw 'Element does not have one of the following attributes: "data-release", "data-track", "data-chart"';
                }
                
                $.facebox({ ajax: '/add_to_chart/' + get });
            })

            .delegate('.add_to_playlist_link', 'click', function() {
                    
                var
                    $this = $(this),
                    get   = '';

                if ($this.hasClass('disabled'))
                {
                    return;
                }
                
                if ($this.attr('data-release'))
                {
                    get = '?release_id=' + $this.attr('data-release');
                }
                else if ($this.attr('data-track'))
                {
                    get = '?track_id=' + $this.attr('data-track');
                }
                else if ($this.attr('data-chart'))
                {
                    get = '?chart_id=' + $this.attr('data-chart');
                }
                else
                {
                    throw 'Element does not have one of the following attributes: "data-release", "data-track", "data-chart"';
                }
                
                $.facebox({ ajax: '/add_to_playlist/' + get });
            })

            .delegate('.tell_a_friend_link', 'click', function() {
            
                var
                    $this = $(this),
                    get   = '';
                
                if ($this.attr('data-release'))
                {
                    get = '?release_id=' + $this.attr('data-release');
                }
                else if ($this.attr('data-track'))
                {
                    get = '?track_id=' + $this.attr('data-track');
                }
                else if ($this.attr('data-chart'))
                {
                    get = '?chart_id=' + $this.attr('data-chart');
                }
                else
                {
                    throw 'Element does not have one of the following attributes: "data-release", "data-track", "data-chart"';
                }
                
                $.facebox({ ajax: '/tell_a_friend/' + get });
            })

            .delegate('div.buy_full_dropbox, div.buy_full_drop', 'close mouseenter mouseleave', function(e) {
                var
                    $this = $(this),
                    list_item = $this.closest('div.list_item'),
                    dropbox = list_item.find('div.buy_full_dropbox'),
                    filler = dropbox.prev(),
                    drop = list_item.find('div.buy_full_drop'),
                    delay = 400;

                function close()
                {
                    if( ! drop.hasClass('has-mouse') && ! dropbox.hasClass('has-mouse'))
                    {
                        $this.trigger('close');
                    }
                    else
                    {
                        if (drop.data('timeout'))
                        {
                            clearTimeout(drop.data('timeout'));
                        } 
                        drop.data('timeout', setTimeout(function() { close(); }, delay));
                    }
                }

                if (e.type === 'mouseenter')
                {
                    $this.addClass('has-mouse');
                    if (drop.data('timeout'))
                    {
                        clearTimeout(drop.data('timeout'));
                        drop.removeData('timeout');
                    }

                    if (e.target === drop[0])
                    {
                        if ($this.data('timeout2'))
                        {
                            clearTimeout($this.data('timeout2'));
                            $this.removeData('timeout2');
                        }
                        $this.data('timeout2', setTimeout(function() {
                            if ($this.hasClass('has-mouse'))
                            {
                                dropbox.slideDown(150);
                                filler.show(); 
                            }
                        }, 150));
                    }
                }

                else if (e.type === 'mouseleave')
                {
                    $this.removeClass('has-mouse');
                    if (drop.data('timeout'))
                    {
                        clearTimeout(drop.data('timeout'));
                    }
                    drop.data('timeout', setTimeout(function() { close(); }, delay));
                }

                else if (e.type == 'close')
                {
                    dropbox.slideUp(150, function() {
                        filler.hide();
                    });
                }

            })
            
            .delegate('div.buy_drop, div.buy_dropbox', 'close mouseenter mouseleave', function(e) {
            
                var
                    $this = $(this),
                    td = $this.closest('td'), 
                    dropbox = td.find('div.buy_dropbox'),
                    drop = td.find('div.buy_drop'),
                    delay = 400;

                function close()
                {
                    if( ! drop.hasClass('has-mouse') && ! dropbox.hasClass('has-mouse'))
                    {
                        $this.trigger('close');
                    }
                    else
                    {
                        if (drop.data('timeout'))
                        {
                            clearTimeout(drop.data('timeout'));
                        } 
                        drop.data('timeout', setTimeout(function() { close(); }, delay));
                    }
                }

                if (e.type === 'mouseenter')
                {
                    $this.addClass('has-mouse');
                    if (drop.data('timeout'))
                    {
                        clearTimeout(drop.data('timeout'));
                        drop.removeData('timeout');
                    }

                    if (e.target === drop[0])
                    {
                        if ($this.data('timeout2'))
                        {
                            clearTimeout($this.data('timeout2'));
                            $this.removeData('timeout2');
                        }
                        $this.data('timeout2', setTimeout(function() {
                            if ($this.hasClass('has-mouse'))
                            {
                                dropbox.slideDown(150);
                                drop.addClass('active');
                            }
                        }, 150));
                    }
                }

                else if (e.type === 'mouseleave')
                {
                    $this.removeClass('has-mouse');
                    if (drop.data('timeout'))
                    {
                        clearTimeout(drop.data('timeout'));
                    }
                    drop.data('timeout', setTimeout(function() { close(); }, delay));
                }

                else if (e.type == 'close')
                {
                    dropbox.slideUp(150, function() {
                        drop.removeClass('active');
                    });
                }
            })
            
            .delegate('div.list_item .reveal', 'click', function() {

                // TODO optimize        
                if ( ! $(this).hasClass('showing'))
                {
                    $(this).addClass('showing');
                    $(this).closest('.list_item').find('.table2 tr:gt(2)').show();
                    $(this).html('Collapse tracks');
                }
                else
                {
                    $(this).removeClass('showing');
                    $(this).closest('.list_item').find('.table2 tr:gt(2)').hide();
                    var count = $(this).closest('.list_item').find('.table2 tr:has(td)').size() - 2;
                    $(this).html('Reveal ' + count + ' more tracks');
                }
            }); // End $('#content').delegate
        
}); // End DOM ready

