function ajaxError(data){
    $('#ajaxError').remove();
    $('<div id="ajaxError"><h3>We\'re having technical difficulties!</h3><p>There was an error getting data from the server. You can try again, and if that doesn\'t work then please come back and try again later!</p><h4>Thanks!</h4><div class="close"><a href="#" onclick="$(\'#ajaxError\').remove(); return false;">[x]close</a></div>').prependTo('body');
    window.scrollTo(0,0);
}
function loadAjaxPage(data){
    $('#ajaxError').remove();
    var page = $(data),
        header = $("#header"),
        title_start, title, body_classes;
    title_start = data.indexOf("<title>")
    title = data.substr(title_start + 7, data.indexOf("</title>") - title_start - 7)
    body_classes = data.match(/<body [^>]*?class\s?=\s?[\'"]([\w\s-]*?)[\'"][^<]*?>/)
    if (!body_classes[1].match(/\bhome\b/)) {
        header.animate({height:'150px'}); 
    }
    else {
        header.animate({height:'416px'});
    }
    header.children('img').fadeOut()
            .queue(function(){
                var el = $(this),
                    img;
                img = page.children("#header").children('img').hide();
                el.replaceWith(img).queue(function(){
                    var main = page.children("#content");
                    $('#header img').fadeIn();
                    $('body').attr('class', body_classes[1]);
                    $("#content").replaceWith(main);
                    document.title = title;
                    hijax.onPageLoad();
                    $(this).dequeue();
                });
                el.dequeue();
            });
}

function dynamic_songs(list, right) {
    album = list.children("ul.songs");
    album.find("a").click(function(){
        var el = $(this);
        right.children().fadeOut(200).animate({opacity:1},200).queue(function(){
            hijax.track(album.attr("id") + '/' + el.attr("hash").substr(1));
            $(el.attr("hash")).fadeIn();
            $(this).dequeue();
        });
        return false;
    });
}

function loadAlbum(data){
    $('#ajaxError').remove();
    var page = $(data),
        main = page.children("#content"),
        right = $("#mainright"),
        list = $("#sidebar"),
        album;
    right.html(main.find("#mainright").html());
    right.children().hide();
    list.html(main.find("#sidebar").html());
    dynamic_songs(list, right);
}

hijax = {
    getHistoryPage:function(hash) {
            if(hash && $.browser.msie) {hash = encodeURIComponent(hash);}
            $.ajax({
                url:'/'+hash,
                success:loadAjaxPage,
                error:ajaxError
            });
        },
    onPageLoad:function(){
        $(this.loaders).each(function(){this();});
        },
    getroot:function(){return window.location.protocol+'//'+window.location.host+'/';},
    track:function(hash){
        try{pageTracker._trackPageview(hash);return true;}
        catch(err){return false;}
    },
    loaders:[function(){
        $(".hijax").removeClass('hijax').click(function(){
                var hash = this.href.replace(hijax.getroot(),'');
                hash = hash.replace(/^.*#/, '');
                hijax.track(hash);
                $.historyLoad(hash);
                return false;
            });
        }]
}

$(function(){
    jQuery.validator.addMethod("zip", function(value, element) { 
            return this.optional(element) || /^\d{5}$/.test(value); 
        }, "5-digit US zip code, please");
    
    hijax.loaders.push(
        function(){
            $("#mp3player").click(function(){
                hijax.track('mp3player');
                w=window.open('/mp3player', "name",
                    "height=380,width=470, location=no, resizeable=no, menubar=no, status=no, toolbar=no");
                if (window.focus){w.focus()}
                return false;
            });
        },
        function(){
            $(".album .detailview").click(function(){
                var hash = this.href.replace(hijax.getroot(),'');
                hash = hash.replace(/^.*#/, '');
                hijax.track(hash);
                $.ajax({
                    url:'/'+hash,
                    dataType:'html',
                    success:loadAlbum,
                    error:ajaxError
                });
                return false;
            });
        },
        function(){
            $("#signupform").validate({
                rules:{
                    email:{required: true, email:true},
                    zip:{required:true, zip:true}
                },
                messages:{
                    email:{
                        required: "we need your email to sign you up!",
                        email: "sorry, that email doesn't look quite right..."
                    },
                    zip:{
                        required: "zip code, please!"
                    }
                },
                errorPlacement: function(error, element) {
                    $("#content div.errors").html(error).show();
                }
            });
        },
        function(){
            var ext = $("[rel*='external']");
            ext.each(function(){
                $(this).attr('rel',ext.attr('rel').replace('external', ''));
            });
            ext.click(function(){
                w=window.open(this.href);
                if (window.focus) {w.focus()}
                return false;
            });
        }
    );
    
    $.historyInit(hijax.getHistoryPage, "/jquery_history");
    hijax.onPageLoad();
    
    $("<div class='close'><a href='#'>[x]close</a></div>").appendTo("div.notification").click(function () {
        $(this).closest("div.notification").remove();
        return false;
    });
});
