$(document).ready(function() {
    
    $('#submit-contact').live('click', function(){
        $.ajax({
            url:baseURL+"/wp-admin/admin-ajax.php",
            dataType: 'html',
            data: "action=my_ajax_send_contact&"+$('#contacts').serialize(),
            type: 'POST',
            success: function(data){
                var message = '<h1>Thanks for reaching out.</h1>'+
                '<p id="contact_thank_you">While we do our best to respond as quickly as humanly (or any other animal for that matter) possible, our typical response time is between 24 - 48 hours.</p>';
                $('#pagecontent').html(message);
            }
        });
    });
    
    $('#categories ul li, .cat_button').live('click', function(e) {
        var target = $(this).text().toLowerCase();
        $('.artist').each(function() {
            if ($(this).hasClass(target)) {
                $(this).fadeIn('medium');
            } else {
                $(this).fadeOut('medium');
            }
        });
    });
    
    $('#artists').live('click', function(e) {
        $('.artist').each(function() {
            $(this).fadeIn('medium');
        });
    });
    
    $('.artist img').live('click', function() {
        window.location.hash = $(this).parents('.artist').attr('title');
    });

    $('.ply_lst img').live('click', function() {
        window.location.hash = $(this).parents('.artist').attr('title');
        launchArtist($(this).parents('.artist').attr('title'),'playlist');
    });
    
    if (window.location.href.indexOf('player=true') == -1) {
        $(window).hashchange(function(){
            switch (window.location.hash) {
                case '':
                case '#checkout':
                    break;
                case '#info':
                case '#pricing':
                case '#friends':
                case '#contact':
					var page = window.location.hash.replace('#', '');
                    launchPage(page);
					_gaq.push(['_trackPageview', '/page/' + page]);
                    break;
                default:
                    launchArtist(window.location.hash.replace('#', ''),'artist');
                    break;
            }
        });
        $(window).trigger('hashchange');
    }
});

/**
 * Triggers to play a song, or reload the page with the iframe
 */
function triggerPlaySong(url, title, artist, id, pList) {
    if (typeof window.parent.playSong == 'undefined') {
        var hash = window.location.hash;
        var loc  = window.location.href.replace(hash, '');
        window.location.href = loc.replace('http://', 'https://') + '?player=true&id=' + id + '&t=' + pList.type + '&tid=' + pList.id + hash;
    } else {
        window.parent.playSong(url, title, artist, id, pList);
    }
}

/**
 * Launches a content page from the header
 */
function launchPage(page) {
    
    // If the page div doesn't exist, insert it into the DOM
    if ($('#page').size() == '0') {
        $('#body_wrapper').prepend('\
            <section id="page">\
                <section id="pageloader">\
                    <img src="' + themeURL + '/images/loader.gif" alt="Loading...">\
                </section>\
                <section id="pagecontent">&nbsp;</section>\
            </section>\
        ');
    }
    
    window.location.hash = page;
    
    $('#loader').hide();
    $('#pagecontent').hide();
    $('#page').slideDown('medium');
    $('#profile').slideUp('medium');
    $('#profile').unbind();
    
    $('#artist_images li').remove();
    $('#artist_images').anythingSlider('destroy');
    $('#pageloader').slideDown('fast');
    
    $.ajax({
        url:  '/wp-admin/admin-ajax.php',
        type: 'POST',
        data: 'action=my_get_page&page=' + page,
        success: function(data){
            $('#top_songs').slideUp('medium');
            $('#pagecontent').html(data);
            $('#pageloader').slideUp('medium');
            $('#pagecontent').slideDown('medium');
         }
    });
}

/**
 * Handles closing other page elements that may exist
 * and makes artist profile AJAX request
 */
function launchArtist(artist, post_type, sort_by, direction) {
    $('#page').hide();
    $('#profile').hide();
    $('#profile').unbind();
    
    // Reset the state of the artist profile
    $('#artist_profile h1').html('Popular Songs');
    $('#artist_profile tfoot').show();
    $('#top_songs').slideUp('fast');
    $('#artist_images li').remove();
    $('#artist_images').anythingSlider('destroy');
    
    $('#body').html('');
    $('#list tr').remove();
    $('#overflow tr').remove();
    
    $('#loader').slideDown('medium');

    if ($('#page').hasClass('playlist_page')) {
        post_type = 'playlist';
    } else {
        post_type = 'artist';
    }
    $(window).scrollTo('nav', 800, {
        onAfter: function() {
            $.ajax({
                url: baseURL + '/wp-admin/admin-ajax.php',
                type: 'POST',
                dataType: 'json',
                data: 'action=my_ajax_get_artist&artist=' + artist + '&type=' + post_type,
                success: function(data){
                    populateArtist(data, post_type);
                }
            });
        }
    });
}

/**
 * Populates the artist list from AJAX request
 */
function populateArtist(artist, post_type) {
    
    $('#name').html(artist.artist.name);
    $('#artist_name').val(artist.artist.name);
    
    artist.artist.description += '<div id="artist-categories">';
    artist.artist.description += '<div class="cat_button">' + artist.artist.categories + '</div>';
    artist.artist.description += '</div>';
    
	_gaq.push(['_trackPageview', '/artist/profile/' + artist.artist.name]);
	
    $('#body').html(artist.artist.description);
    
    if (artist.artist.image.length != 0) {
        for (var i = 0; i < artist.artist.image.length; i++) {
            $('#artist_images').append('<li><img src="' + artist.artist.image[i] + '"></li>');
        }
    }
    
    if ($('#artist_images li').size() != 0) {
        $('#artist_images').anythingSlider({
            width          : 540,
            height         : 365,
            toggleControls : true,
            buildArrows    : false,
            enableKeyboard : true,
            hashTags       : false,
            toggleControls : false,
            theme          : 'minimalist-round',
            themeDirectory : '/js/anythingslider/css/theme-minimalist-round.css',
            startPanel     : 0
        });
    }
    // Handle a scenario where no songs have been sent over
    if (artist.artist.songs.length > 0) {
        populateSongs(artist.artist.songs, post_type, artist.artist.id);
        $('#artist_profile .songs').show();
        $('#artist_profile #profile').removeClass('padded');
    } else {
        $('#artist_profile .songs').hide();
        $('#artist_profile #profile').addClass('padded');
    }

    $('#loader').slideUp('fast');
    $('#profile').slideDown('slow');
}

/**
 * Populates the songs list
 */
function populateSongs(songs, post_type, artist_id) {
    
    $('#artist_profile #overflow').hide();
    var classtype = 'even';
    var popular_song_count = 5;
    
    for (var i = 0; i < songs.length; i++) {
        
        var instrumental = "";
        if (songs[i].instrumental == 1) {
            instrumental = "<img style='margin:4px 0 0 25px' src='/wp-content/themes/withetiquette_new/images/inst-dot.png'>";
        }
        
        if (classtype == 'even') {
            classtype = 'odd';
        } else {
            classtype = 'even';
        }
        
        var licenseClasses = 'license_song addtocart ajax';
        if (isSongInCart(songs[i].id)) {
            licenseClasses = licenseClasses + ' incart';
        }
        
        var row = '<tr id="' + songs[i].id + '" class="song_' + classtype + '">' +
                  '      <td style="background:none; padding: 0 0 0 10px;" class="audio">' +
                  '          <div id="' + songs[i].id + '" onclick="javascript: ' +
                  '            triggerPlaySong(\'' + songs[i].url + '\', \'' + $('#artist_profile #name').html().replace("'", '') + '\', \'' + songs[i].name + '\',\'' + songs[i].id + '\', { type: \'artist\', id: \'' + artist_id + '\' });"' +
                  '            class="play-audio"></div>' +
                  '      </td>' +
                  '      <td class="title">' + songs[i].name.replace("\\'", "'") + '</td>' +
                  '      <td>' + songs[i].duration + '</td>' +
                  '      <td>' +
                  '          <span style="display: none">' + songs[i].tempo + '</span>' +
                  '          <div class="tempo_unfilled">' +
                  '              <div style="width: ' + parseInt(songs[i].tempo) + '%" class="tempo_filled"></div>' +
                  '          </div>' +
                  '      </td>' +
                  '      <td class="song-instrumental">' +
                  '          <span style="display: none">' + songs[i].instrumental + '</span>' + instrumental + '</span></td>' +
                  '      <td class="' + licenseClasses + '" id="' + songs[i].id + '"></td>' +
                  '  </tr>';
    
        if (post_type == 'playlist'){
            $('#playlist_name').val(songs[i].playlist_name);
            $('#playlist_id').val(songs[i].playlist_id);
        }
        // If the song overflows past the limit put into overflow thead
        if (i >= popular_song_count
            && songs.length >= popular_song_count) {
            $('#artist_profile #overflow').append(row);
        } else {
            $('#artist_profile #list').append(row);
        }
        
    }
    if (songs.length <= popular_song_count) {
        $('#artist_profile tfoot').hide();
    }
    doSongListSorter();
}

/**
 * Zebra stripe the artist list
 */
function doSongListSorter() {
    $("#artist_profile .songs table").tablesorter({
        widgetZebra: {
                css: ['song_even', 'song_odd']
        },
        widgets: ['zebra'],
        headers: {
            0: { sorter: false },
            6: { sorter: false }
        },
        cssDesc: 'sortDesc',
        cssAsc:  'sortAsc'
    })
    .trigger('update');
}

/**
 * React to the artist expand click
 */
$("#artist_profile #expand, #artist_profile #expand-plus").live('click', function() {
    $('#artist_profile #list').append($('#artist_profile #overflow').html());
    $('#artist_profile h1').html('All Songs');
    $('#artist_profile tfoot').hide();
    doSongListSorter();
});
