var newImageCount = -1;
var newImages = new Array();
function newImage(arg) {
    if (document.images) {
        newImageCount++;
        newImages[newImageCount] = new Image();
        newImages[newImageCount].src = arg;
        return newImages[newImageCount];
    }
}

function email_encoder(account, domain, dotwhat, spanID) {
    spanID = spanID || account;
    $("#em_"+spanID).html('<a href="mailto:' + account + '&#64;' + domain + '&#46;' + dotwhat + '">' + account + '&#64;' + domain + '&#46;' + dotwhat + '</a>');
}

$(function(){
    var user_imgs = ['user', 'header', 'background'];
    $.each(user_imgs, function(i, e) {
        if ($('#edit-delete-'+e+'-image')) {
             $('#edit-delete-'+e+'-image').click(function(){
                  if (this.checked)
                       $('#edit-'+e+'-image').attr('value','').attr('disabled','disabled');
                  else
                       $('#edit-'+e+'-image').removeAttr('disabled');
             });
        }
    });

    if ($('#newsletter_email') && $('#newsletter_email')[0]) {
        var enter_msg = 'Enter your e-mail';
        var invalid_msg = 'Please enter a valid e-mail address';
        if ($('#newsletter_email')[0].value == '') {
            $('#newsletter_email').css('color', '#999');
            $('#newsletter_email')[0].value = enter_msg;
        }
        $('#newsletter_email').click(function() {
            $('#newsletter_email').css('color', '#000');
            if ($('#newsletter_email')[0].value == enter_msg) $('#newsletter_email')[0].value = '';
        });
        $('#newsletter_form').submit(function() {
            if ($('#newsletter_email')[0].value && ($('#newsletter_email')[0].value != enter_msg)) {
                var re = /^[^@]+@[^@]+.[a-z]{2,}$/i;
                var e = $('#newsletter_email')[0].value;
                if (e.search(re) == -1)
                    alert(invalid_msg);
                else
                    return true;
            } else {
                alert(enter_msg);
            }
            return false;
        });
    }

	if ($("#rss_treeview").length) {
	    $("#rss_treeview").treeview({
		    collapsed: true,
		    persist: "location",
		    control: '#expand_collapse_all'
	    });
	}
	
    if ($.browser.safari) $("#main .artist_filter a, #main .artist_filter span span").css("padding-left", "1px").css("padding-right", "1px");
    if ($.browser.mozilla && (navigator.userAgent.indexOf("Mac") != -1)) $(".dl, #main .dl").css("padding-top", "6px");
});

var imgBase = "/themes/rcrdlbl/_img/";
function artistNav() {
    var collapserLinks = $("a.arrow_collapse");
    for (var i = 0; i < collapserLinks.length; i++) {
        collapserLinks[i].onclick = function() {
            var blop = this.parentNode.parentNode;
            blop.className = (blop.className == 'collapsed') ? 'expanded' : 'collapsed';
            return false;
        }
    }
}
$(function() {
    artistNav();
    newImage(imgBase+"artist_nav-a-arrow_collapse.gif");
    newImage(imgBase+"artist_nav-a-arrow_expand.gif");
    newImage(imgBase+"icon_collapse_white.gif");
    newImage(imgBase+"icon_expand_white.gif");
    newImage(imgBase+"gl-a-comments_hover-bg.gif");
    newImage(imgBase+"gl-a-permalink_hover-bg.gif");
    newImage(imgBase+"gl-a-send_to_friend_hover-bg.gif");
    newImage(imgBase+"gl-a-delicious_hover-bg.gif");
    newImage(imgBase+"gl-a-digg_hover-bg.gif");
    newImage(imgBase+"gl-a-stumble_upon_hover-bg.gif");
    newImage(imgBase+"artists-a-music_hover-bg.png");
    newImage(imgBase+"artists-a-blog_hover-bg.png");
});

/* AJAX */

var ajaxLock = false;
var rootDir = "";
function ajaxError(XMLHttpRequest, textStatus, errorThrown) {
    //alert(textStatus + " | " + errorThrown);
    ajaxLock = false;
    msg = textStatus + " | " + errorThrown;
    $.post(rootDir+"/report_error.php", msg);
    alert('Something went wrong.  Try again...');
}

var resp = {
    atm_e: "Ajax script returned an error.",
    atm_1: "This sublabel is already one of your favorites.",
    atm_2: "This sublabel has been added to your list of favorites.",
    atm_3: "This artist is already one of your favorites.",
    atm_4: "This artist has been added to your list of favorites."
}

$(function(){
    $("#add_to_my").click(function() {
        if ($("#add_to_my_rblog_id").length) {
            var rblog_id = parseInt($("#add_to_my_rblog_id")[0].value);
            if (!ajaxLock && !isNaN(rblog_id)) {
                ajaxLock = true;
                $.ajax({
                    type: "POST",
                    url: rootDir+"/ajax_add_to_my.php",
                    data: "i="+rblog_id,
                    success: hAddToMy,
                    error: ajaxError
                });
            }
        }

        function hAddToMy(r) {
            ajaxLock = false;
            r = parseInt(r);
            if (!isNaN(r)) {
                switch (r) {
                    case 0:
                        ajaxError(null, resp.atm_e);
                        break;
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                        alert(eval('resp.atm_'+r));
                        break;
                }
            }
        }
    });
    $("#add_to_my_login").click(function() {
        var atml_msg = "Want to add this to your list of RCRD LBL faves? Login if you already have a My RCRD LBL account, otherwise register to create one. It'll only take a minute.";
        alert(atml_msg);
    });
});

/* CUSTOM RSS FEEDS */

$(function() {
    if ($("#custom_rss_feed").length) {
            $(".checkbox").filter(function() {
                var sbStr = "sublabel_blog_";
                var sbi = this.id.indexOf(sbStr);
                return ((sbi != -1) && (this.id.substr(sbStr.length) != "all"));
            }).click(function() {
                setCustomAll("sublabel");
        });
        $(".checkbox").filter(function() {
            var abStr = "artist_blog_";
            var abi = this.id.indexOf(abStr);
            return ((abi != -1) && (this.id.substr(abStr.length) != "all"));
        }).click(function() {
            setCustomAll("artist");
        });
        $("#sublabel_blog_all").click(function() { setCustomItems("sublabel", this.checked); });
        $("#artist_blog_all").click(function() { setCustomItems("artist", this.checked); });
        setCustomAll("sublabel");
        setCustomAll("artist");
    }
});

function setCustomAll(type) {
    var allItems = true;
    $(".checkbox").filter(function() {
        var bStr = type+"_blog_";
        var bi = this.id.indexOf(bStr);
        return ((bi != -1) && (this.id.substr(bStr.length) != "all"));
    }).each(function() {
        if (!this.checked) allItems = false;
    });
    $("#"+type+"_blog_all")[0].checked = allItems;
}

function setCustomItems(type, checked) {
    $(".checkbox").filter(function() {
        var bStr = type+"_blog_";
        var bi = this.id.indexOf(bStr);
        return ((bi != -1) && (this.id.substr(bStr.length) != "all"));
    }).each(function() {
        this.checked = checked;
    });
}

/* STREAMING MUSIC */

function stream(id) {
    if ((typeof(rw_rlid) != "undefined")) {
        if ($("#w_"+rw_rlid).length) {
            var rw = $("#w_"+rw_rlid)[0];
            if (typeof(rw.loadTrack) != 'undefined') rw.loadTrack(id);
        }
    }
}

/* PAGE RENDERERS */

var tp = null;
var tp_old = null;
var tp_lock = false;
function rFeatured() {
    if ($(".featured").length) {
        tp = 1;
        var tp_anim = function() {
            $("#tracks #tracks"+tp_old).fadeOut('fast', function() {
                var cur = $("#tracks .pagination .current").html();
                cur = tp+cur.substr(cur.indexOf('/'));
                $("#tracks .pagination .current").html(cur);
                $("#tracks #tracks"+tp).fadeIn('fast', function() { tp_lock = false; });
            });
        };
        $("#tracks .pagination .prev a").click(function() {
            if (!tp_lock) {
                tp_lock = true;
                tp_old = tp;
                tp--;
                if (tp <= 0) tp = $("#tracks .container").length;
                tp_anim();
            }
        });
        $("#tracks .pagination .next a").click(function() {
            if (!tp_lock) {
                tp_lock = true;
                tp_old = tp;
                tp++;
                if (tp > $("#tracks .container").length) tp = 1;
                tp_anim();
            }
        });
    }
}

function rArtists() {
    $("#select_label").change(function() {
        $(this).attr("disabled", "disabled");
        var lh = location.href.replace(location.search, '');
        var label_index = lh.indexOf("\/label\/", 8);
        var lh_suf = ($(this).val()) ? "label/"+$(this).val() : "";
        location.href = ((label_index != -1) ? lh.substr(0, label_index)+"/" : lh+((lh.substr(lh.length - 1) == "/")?"":"/")) + lh_suf;
    });
    $(".mp a").click(function() {
        $("#past_week, #past_month, #all_time").removeClass("selected");
        $(this).addClass("selected");
        var mp_type = $(this).attr("id");
        $(".mp_artists").each(function() {
            if ($(this).attr("id") == "mp_"+mp_type)
                $(this).show();
            else
                $(this).hide();
        });
    });
}

function rArtist() {
    $("a.more, a.less").each(function() {
        $(this).click(function() {
            $("#bio").attr("class", (($("#bio").attr("class") == 'collapsed') ? 'expanded' : 'collapsed'));
        });
    });
}

function rTracks(iht_arr) {
    $.each(iht_arr, function(i, e) { rTrack(e.i, e.h, e.t, e.d); });
}

var dl_lock = false;
var dl_lock_to = 100;
var dl_to = [];
var dl_rehost_to = 2000;

function rTrack(i, h, t, d) {
    if (d) {
        $("#dl_link_"+i).click(function() {
            if (!dl_lock) {
                dl_lock = true;
                setTimeout(function() { dl_lock = false; }, dl_lock_to);
                $("#dl_h")[0].value = h;
                $("#dl_t")[0].value = t;
                $("#dl_form").submit();
            }
            return false;
        }).mouseover(function() {
            clearTimeout(dl_to["i"+i]);
            $("#dl_rehost_"+i).html("Please do not rehost this download.");
        }).mouseout(function() {
            dl_to["i"+i] = setTimeout(function() {
                $("#dl_rehost_"+i).empty();
            }, dl_rehost_to);
        }).mousedown(function(e) {
            var evt = e;
            $(this).mouseup(function() {
                $(this).unbind('mouseup');
                if (evt.button == 2) {
                    alert("To download this track, click \""+$(this).text()+"\" with your left mouse button.");
                    return false;
                } else {
                    return true;
                }
            });
            $(this)[0].oncontextmenu = function() { return false; };
        });
    }
    $("#trk_"+i+" .trk").click(function() { stream(i); });
}

function rRBlogPosts() {
    $("#rblog_posts_rblog").change(function() {
        var val = this.options[this.selectedIndex].value;
        if (val) {
            $("#rblog_posts_form").attr("action", $("#rblog_posts_action").val()+val);
            $("#rblog_posts_form").submit();
        }
    });
}

/* WIDGETS */

function rlVideo(rlid) {
    if ($("#"+rlid+"_video").length) {
        $("#"+rlid+"_video").html(
            '<object width="425" height="428">\n'+
            '<param name="movie" value="http://'+window.location.hostname+'/widgets/swf/videos.swf?rlid='+rlid+'&wid=4865596fc41a7da0'+'&pid=48f524c0b034aabe"></param>\n'+
            '<param name="wmode" value="transparent"></param>\n'+
            '<param name="menu" value="false"></param>\n'+
            '<param name="bgcolor" value="#FFFFFF"></param>\n'+
            '<embed src="http://'+window.location.hostname+'/widgets/swf/videos.swf?rlid='+rlid+'&wid=4865596fc41a7da0&pid=48f524c0b034aabe" type="application/x-shockwave-flash" wmode="transparent" menu="false" bgcolor="#FFFFFF" width="425" height="428"></embed>'
        );
    }
}

function rlPlaylist(rlid) {
    if ($("#"+rlid+"_playlist").length) {
        $("#"+rlid+"_playlist").html(
            '<object width="300" height="365">\n'+
            '<param name="movie" value="http://'+window.location.hostname+'/widgets/swf/videos.swf?rlid='+rlid+'&wid=48a349c21616a695'+'&pid=48f3840732b0863b"></param>\n'+
            '<param name="wmode" value="transparent"></param>\n'+
            '<param name="menu" value="false"></param>\n'+
            '<param name="bgcolor" value="#FFFFFF"></param>\n'+
            '<embed src="http://'+window.location.hostname+'/widgets/swf/playlist.swf?rlid='+rlid+'&wid=48a349c21616a695&pid=48f3840732b0863b" type="application/x-shockwave-flash" wmode="transparent" menu="false" bgcolor="#FFFFFF" width="300" height="365"></embed>'
        );
    }
}
