if (typeof(jQuery) != 'function') {  $ = function() {return {'ready':function(){}}} }
//if (!window.console) {  console = {'log':function(){},'dir':function(){}};  }
(function(){
var debugok = 0;
;;;  debugok = window.console && window.console.log && typeof(window.console.log.apply) == 'function' ? 1:0;
if (debugok) { window.$log = function(){ console.log.apply( console, arguments ) }; } 
else { window.$log = function(){}; }
})();

createNamespace('WF');

/*
function addObjectEventListener(obj, event, funct) {
    // Assign new anonymous function if we're passed a js string
    // instead of a function reference.
    if (typeof funct == 'string') {
        funct = new Function('evt',funct);
    }

    if (obj.addEventListener) { // Moz
        obj.addEventListener(event, funct, false);
    } 
    else if (obj.attachEvent) { // IE
        obj.attachEvent('on'+event, funct);
    }
    else {
        var old;
        eval('old = obj.on'+event+';');
        if (old !== null) {
            eval('obj.on'+event+' = function(evt) {'+'old(evt); funct(evt);};');
        }
        else {
            eval('obj.on'+event+' = funct;');
        }
    }
}
*/

function addObjectEventListener(o, e, fn) { if (typeof fn == 'string') {fn = new Function('evt',fn)} $(o).bind(e,fn) }

function buildElement(elproto) {
    var el;
    if (elproto.t) {
        el = document.createTextNode(elproto.t);
    }
    else {
        el = document.createElement(elproto.e);
        if (elproto.h) {
            el.innerHTML = elproto.h;
        }
        else {
            for (var attribute in elproto.a) {
                el.setAttribute(attribute,elproto.a[attribute]);
            }
            if (elproto.cl) { el.className = elproto.cl; }
            for (var event in elproto.ev) {
                //addObjectEventListener(el,event,elproto.ev[event]);
                el[event] = elproto.ev[event];
            }
        }
    }
    return el;
}

function buildElementTree(elproto) {
    if (!document.getElementById) {return;}
    var el = buildElement(elproto);
    for (var childproto in elproto.c) {
        el.appendChild(buildElementTree(elproto.c[childproto]));
    }
    return el;
}

function removechildren(el) {  el.innerHTML = ''  }

function createNamespace(s, o) {
    var ns = s.split('.'),
        i,
        len;
    o = o || window;
    for (i=0, len=ns.length; i<len; i++) {
        o = o[ns[i]] = o[ns[i]] || {};
    }
    return o;
}

function parenthref(url) {
    if (opener !== null  &&  typeof(opener.location.href) == "string") {
        opener.location.href = url;
        opener.window.focus();		
    } else {
        window.open(url,"newwefunkwindow");
    }  
}

function handleElementKeepVisible(event) {
    event.stopPropagation();
    var id = event.data.id;
    event.data.fadeInSpeed = event.data.fadeInSpeed || 200;
    window.clearTimeout(timers.hideelement[id]);
    timers.hideelement[id] = -1;
    var el = $('#'+id);
    var eldisplay = el.css('display');
    //if (eldisplay == 'none' || parseFloat(el.css('opacity')) < 1 && eldisplay == 'block') {
    if (eldisplay == 'none' || parseFloat(el.css('opacity')) < 1) {
        if (eldisplay == 'none') { el.css({opacity:0,display:'block'}) }
        console.log('eldisplay='+eldisplay);
        el.stop().animate({opacity:1},event.data.fadeInSpeed);
    }
}

function handleElementSetFade(event) {
    event.data = event.data || {};
    event.data.fadeDelay = event.data.fadeDelay || 800;
    event.data.fadeOutSpeed = event.data.fadeOutSpeed || 1000
    var thisid = event.data.id;
    thisid = thisid || 'learnown';    
    if (timers.hideelement[thisid] < 0) {
        timers.hideelement[thisid] = window.setTimeout(function(){$('#'+thisid).fadeOut(event.data.fadeOutSpeed);},event.data.fadeDelay);
        window.clearTimeout(timers.showelement[thisid]);
    }
}


/* **************************** MISC ************************ */
(function(){
function EXPORT() {$.each({
    'gatherFormData':gatherFormData,
    'contextualShareAdd':contextualShareAdd
},function(n,v){ WF[n]=v; })}

var contextualshare = {
    facebook: {
        context: ['http://www.facebook.com/','http://www.facebook.com/home.php?ref=home','http://www.facebook.com/home.php?ref=logo','http://www.facebook.com/home.php?'],
        destination: 'http://www.facebook.com/share.php?u={URL}&t={TITLE}'
    },
    myspace: {
        context: ['http://www.myspace.com/','http://home.myspace.com/index.cfm?fuseaction=home'],
        destination: 'http://www.myspace.com/Modules/PostTo/Pages/?l=3&u={URL}&t={TITLE}&c={DESCRIPTION}'
    },
    twitter: {
        context: ['http://twitter.com/','http://www.twitter.com/'],
        destination: 'http://twitter.com/home/?status={URL}+{TITLE}'
    }
};

function contextualShareAdd(container) {
    var body = $('body');
    var enc_url = encodeURIComponent(window.location.href.replace('//session.','//www.'));
    var enc_title = encodeURIComponent($('title').text());
    var enc_description = encodeURIComponent($('meta[name=description]').text());
    var el, eld, found;
    var popWin = function () { window.open(this.href); return false };
    for (var cx in contextualshare) {
        var eld = document.createElement('A');
        eld.className = 'cxshare probe';
        el = $(eld);
        found = false;
        for (var i=0, l=contextualshare[cx].context.length; i<l; i++) {
            eld.href = contextualshare[cx].context[i];
            if (el.css('display') == '') { // I'm looking at you, safari
                body.append(el);
            }
            if (el.css('display') != 'none') {
                var url = '/clickout?' + encodeURIComponent(contextualshare[cx].destination.replace('{URL}', enc_url).replace('{TITLE}', enc_title).replace('{DESCRIPTION}', enc_description));
                eld.href = url;
                var text = contextualshare[cx].text || 'Share';
                el.addClass('ok cxshare_'+cx).removeClass('probe').html(text);
                found = true;
                el.bind('click',popWin);
                container.append(el);
                break;
            }
        }
        if (!found) { el.remove() }
    }
}

function gatherFormData(id) {
    var inputs = [];
    $('#'+id+' :input').each(function() {
        inputs.push(this.name + '=' + escape(this.value));
    });
    return inputs.join('&');
}

EXPORT();
})();
/* ***************************** misc ************************** */


/* **************************** Cookies ************************ */
function createCookie(name,value,days,domain) {     // http://www.quirksmode.org/js/cookies.html
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	if (!domain) {domain = '.wefunkradio.com'; }
	document.cookie = name+"="+value+expires+"; path=/; domain="+domain;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name,domain) {
	createCookie(name,"",-1,domain);
}
/* ***************************** Cookies ************************* */


/* **************************** NavSearch ************************ */
(function(){
function EXPORT() {$.each({
    'initNavSearch':initNavSearch
},function(n,v){ WF[n]=v; })}

function navsearch_focus() {
    var el = document.getElementById('navsearch');
    if (el.value == 'search') {
        el.value='';
    }
    el = document.getElementById('navsearchform');
    el.action = "/playlistsearch.plx";
    el.target = '_top'; // default
    $('#navsearchli').addClass('focused');
}

function navsearch_blur_real() {
    $('#navsearchli').removeClass('focused');
    var el = document.getElementById('navsearch');
    if (el.value.length == 0) {
        el.value = 'search';
    }
}

function navsearch_blur() {
    setTimeout(navsearch_blur_real,100);
}

function navsearch_submit_playlists() {
    document.getElementById('navsearchform').submit();
}

function navsearch_submit_learnown() {
    var el = document.getElementById('navsearch');
    var bits = el.value.split(/ - /,2);
    if (bits.length == 2) {
        document.getElementById('artist').value = bits[0];
        document.getElementById('title').value = bits[1];
    } else {
        document.getElementById('artist').value = bits[0];
        document.getElementById('title').value = '';
    }
    el.value = '';
    
    el = document.getElementById('navsearchform');
    el.action = "/learn-own.plx";
    el.submit();
}

function initNavSearch() {
    $('#navsearch').focus(navsearch_focus).blur(navsearch_blur).addClass('dyn').val('search');
    $('#navsearch_playlists').click(navsearch_submit_playlists);
    $('#navsearch_learnown').click(navsearch_submit_learnown);
}

EXPORT();
})();
/* ************************* navsearch ******************* */


/* ************************* FAVORITES ******************* */
(function(){
function EXPORT() {$.each({
    'favoritesCreateStar':favoritesCreateStar,
    'togglefav':togglefav,
    'favoritesUpdateStar':favoritesUpdateStar
},function(n,v){ WF[n]=v; })}

var favorite_types = {
    'show'   : {'s':'show','p':'shows','ts':'Show','tp':'Shows'},
    'showtrack'   : {'s':'song','p':'songs','ts':'Song','tp':'Songs'},
    'extra'  : {'s':'extra','p':'extras','ts':'Extra','tp':'Extras'},
    'search' : {'s':'search','p':'searches','ts':'Search','tp':'Searches'}
};

function prefs_request(str,key) {
  	var d = new Date();
    $('#'+key).trigger('update');
    $.ajax({
        url: '/prefs/gj/' + str + '/key/' + key + '/' + d.getTime(),
        dataType: "json",
        success:prefs_callback,
        error:undefined
    });
}

function prefs_callback(result) {
    if (result.success) {
        favoritesUpdateStar(result.key,parseInt(result.value));
    }
}

function favoritesUpdateStar(key,value) {
    value = parseInt(value)? true:false;
    var type = favtype(key);
    var typestring_s = favorite_types[type].ts;
    var typestring_p = favorite_types[type].tp;
    var el_a = $('#'+key).trigger('update').attr('href','/prefs/?gr/set/favorite/' + (value? '0':'1') + '/key/' + key + '/r/' + escape(document.location.href.substr(document.location.href.indexOf('/',8))));
    var el_img = el_a.children('img').eq(0);
    if (value) {
        el_img.removeClass('staroff staroffpend staronpend').addClass('staron');
        el_a.attr('title','Click to remove from your Favorite '+typestring_p+' list');
    } else {
        el_img.removeClass('staroffpend staronpend staron').addClass('staroff');
        el_a.attr('title','Click to add to your Favorite '+typestring_p+' list');
    }
    el = $('#'+key+'_text');
    if (el) {
        var favtext;
        if (value) {
            favtext = '<b>Favorite ' + typestring_s + '</b>';
            if (el.hasClass('lnk0') || el.hasClass('lnk1')) { 
                var url = '/profile#view_fav_'+type+'s';
                favtext = favtext + ' &nbsp;&nbsp;<a href="'+url+'" class="nu">View All</a>';
            }
        } else {
             favtext = $('<a>').attr({href:'#'}).addClass('nu').bind('click',{'key':key},togglefav_clickevent).text('Add to Favorite ' + typestring_p);
        }
        el.html(favtext);
        el.attr('title','Click to ' + (value? 'remove from':'add to') + ' your WEFUNK Favorites');
  	}
}

function favtype(item) {
    var bits = item.split(/_/);
    return bits[1];
}

function togglefav(key) {
    var el_a = $('#'+key)
    el_a.get(0).blur();
    var el_img = el_a.children('img').eq(0);
    var el = el_img.get(0);
  	var opacity = 1;
    var type = favtype(key);
  	var typestring = favorite_types[type].tp;
    if (el.className.indexOf('off') < 0) {
        WF.loginHook({fn:function(newlogin){
            // it's on; turn off
            el_img.removeClass('staron staronpend').addClass('staroffpend');
            el_a.attr('title','Click to add to your Favorite '+typestring+' list');
            prefs_request('set/favorite/0',key);
            opacity = 0.4;
            $('#'+key+'_label').fadeTo(150, opacity);
        },message:'Removing '+favorite_types[type].s+' from your favorites...'});
    } else {
        WF.loginHook({fn:function(newlogin){
            el_img.removeClass('staroff staroffpend').addClass('staronpend');
            el_a.attr('title','Click to remove from your Favorite '+typestring+' list');
            prefs_request('set/favorite/1',key);
            $('#'+key+'_label').fadeTo(150, opacity);
        },message:'Saving favorite '+favorite_types[type].s+' to your profile...'});
    }
}

function togglefav_clickevent(event) {
    //$log('clicked on #'+this.id);
    togglefav(event.data.key); 
    return false;
}

function favoritesCreateStar(opt) {
    if (opt.returnto) {
        opt.returnto = opt.returnto.replace(/^http:\/\/[^\/]+/,'');
        opt.returnto = opt.returnto.replace(/^\//,'');
    } else {
        opt.returnto = '';
    }
    var url = '/prefs/?gr/set/favorite/'+(opt.isfav?0:1)+'/key/'+opt.key+'/r/'+(opt.returnto?encodeURIComponent(opt.returnto):'');
    var el = $('<a>').attr({'id':opt.key,'href':url}).addClass('nohover starlink');
    var size = (opt.small? 11:22);
    el.append('<img src="http://cache.wefunkradio.com/images-small/pxl-clr.gif" height="'+size+'" width="'+size+'" class="favstar '+(opt.small?'smallstar ':'')+(opt.isfav?'staron':'staroff')+'"></a>');
    
    el.bind('click',{key:opt.key},togglefav_clickevent);
    return el;    
}

function bind_startoggle(id) {
    $('#'+id).bind('click',{key:id},togglefav_clickevent);
}

EXPORT();
})();
/* ***************************** favorites ************************ */


/* **************************** WIDTHCHECK ************************ */
(function(){
function EXPORT() {$.each({
    'checkwidth':checkwidth,
    'windowwidth':windowwidth
},function(n,v){ WF[n]=v; })}

//var detectedas = 0;
function windowwidth() {
  	var myWidth = 0;
  	if( typeof( window.innerWidth ) == 'number' ) {
      	//Non-IE
      	myWidth = window.innerWidth;
      	//detectedas = "Non-IE, because typeof(window.innerWidth)=='number'";
  	} else {
      	if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
          	//IE 6+ in 'standards compliant mode'
          	myWidth = document.documentElement.clientWidth;
          	//detectedas = "IE 6+ (standards), because document.documentElement.clientWidth has useable value";
      	} else {
          	if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
              	//IE 4 compatible
              	myWidth = document.body.clientWidth;
              	//detectedas = "IE 4 compatible or quirks, because document.documentElement.clientWidth doesn't have value, using document.body.clientWidth";
          	}
      	}
  	}
  	return myWidth;
}

function checkwidth() {
    if (!document.getElementsByTagName) { return }
    var el = document.getElementsByTagName('BODY')[0];
    if (!el) { return; }
    var browseWidth = windowwidth();
    var critwidth = 620;
    var classbase = '';
    var thr = el.className.match(/thr(\d+)/);
    if (thr) {
        critwidth = thr[1];
        classbase = thr[0] + ' ';
    }
    if (browseWidth) {
        if (browseWidth < critwidth) {
            el.className = classbase + 'narrowpage';
            createCookie('narrowpage',1,6/24);
        } else {
            el.className = classbase;
            eraseCookie('narrowpage');
        }
    }
}

EXPORT();
})();
/* **************************** widthcheck ************************ */


/* ****************************** LOGIN *************************** */
(function(){
function EXPORT() {$.each({
    'loginHook':loginHook,
    'loginInit':loginInit,
    'getshowdate':getshowdate
},function(n,v){ WF[n]=v; })}

function loginInit() {
    if (document.location.href.indexOf('//store.') > 0) { return; }
    var login = $('#login b').text();
    if (login.length) {
        WF.username = login.substr(0,login.indexOf(' :'));
    }
    $('body').append($('<div>').load('/js/_login.html'));
    if (!WF.username) {
        $('#login A').bind('click',function(){loginView(true,'Logging In...');return false});
    }
    setTimeout(function(){
        $('#logincancel').bind('click',function(){loginView(false);return false});
        $('#logincreate').click(function(){$('#loginchoose').fadeOut(200,function(){$('#loginpre').html('Creating New Account'); $('#loginformcreate').fadeIn(200).find('INPUT').eq(0).focus()});return false});
        $('#logingo').click(function(){$('#loginchoose').fadeOut(200,function(){$('#loginform').fadeIn(200).find('INPUT').eq(0).focus()});return false});
        $('#logingrp .logincancel').bind('click',function(){loginView(false);return false});
        $('#loginform_f').bind('submit',handleLoginFormSubmit);
        $('#loginformcreate_f').bind('submit',handleLoginCreateSubmit);
        $('#logingrp .loginsubmit').bind('click',function(){$(this).parents('FORM').submit()});
    },2000);
}

function handleLoginSubmit(el) {
    $('#logingrp .loginformstatus').show();
    $('#'+el).fadeTo(300,0.2);

    jQuery.ajax({
        data: WF.gatherFormData(el),
        url: '/login?type=json',
        error: function() {
            $log("Failed to submit");
        },
        type: 'POST',
        dataType: 'json',
        success: loginCallback
    }); 
    
    return false;
}

function getshowdate() {
  	var docurl = document.location.toString();
  	var i = docurl.indexOf("show/");
    var showdate = '';
  	if (i >= 0) {
      	showdate = docurl.substr(i+5,10);
    }
    return showdate;
}

function loginCallback(r) {
    //$log('LOGIN SUBMIT RESPONSE', r);
    if (r.success) {
        WF.username = r.username;
        if (r.cookie) {
            document.cookie = r.cookie;
        }
        var el = $('#login');
        el.html('<b>'+WF.username+' : <a class="fglink nohover nu" href="/profile">view profile</a>');
        //el.get(0).onclick = false;

        $('#loginpre,.loginformstatus').fadeOut(100,function(){$('#loginpre').html('Login Complete').fadeIn(200)});
        setTimeout(function(){
            loginView(false);
            var loginfinish = function () {
                if (typeof(WF.onloginsuccess) == 'function') {
                    WF.onloginsuccess();
                    delete WF.onloginsuccess;
                }
            }
            // OKAY, SHALL WE HANDLE THIS PROPERLY WITH AN EVENT/HOOK??
            var showdate = getshowdate();
            if (showdate) {
                jQuery.ajax({
                    url: '/info/showsingle/json?vars=songfav,showfav&show='+showdate,
                    error: loginfinish,
                    dataType: 'json',
                    success: function(r){
                        if (r && r.datafound) {
                            window.trackisfav = r.songfav;
                            var i = 0;
                            $('#playlist .starlink').each(function(){  // this only applies to show pages!!
                                var key = $(this).attr('id');
                                WF.favoritesUpdateStar(key,r.songfav[i]);
                                i++;
                            });  
                            var el = $('#ibx .favstar').parent();
                            if (el.length > 0) {
                                WF.favoritesUpdateStar(el.attr('id'),r.showfav);
                            }
                        }
                        loginfinish();
                    }
                }); 
            } else {
                loginfinish();
            }
        },1000);
    } else {
        if (r.message) { $('#loginpre').html(r.message); }
        $('#logingrp .loginformstatus').fadeOut(200);
        $('#loginform,#loginformcreate').filter(':visible').fadeTo(300,1);
    }        
}

function handleLoginFormSubmit() {
    handleLoginSubmit('loginform');
    return false;
}
function handleLoginCreateSubmit() {
    handleLoginSubmit('loginformcreate');
    return false;
}

function loginView(vis,prologue) {
    prologue = prologue || '';
    if (vis) {
        $('#logingrp,#loginform,#loginformcreate,.loginformstatus').hide();
        $('#loginchoose').show();
        $('#loginpre').html(prologue);
        if ($.browser.msie && $.browser.version < 7) {
            var vptop = $(window).scrollTop();
            $('#logingrp').css({'position':'absolute','top':vptop+'px'});
        } else {
            var vpheight = window.innerHeight || self.innerHeight || (document.documentElement&&document.documentElement.clientHeight) || document.body.clientHeight;
            var vpwidth = window.innerWidth || self.innerWidth || (document.documentElement&&document.documentElement.clientWidth) || document.body.clientWidth;
            $('#loginmask').css({width:2*vpwidth+'px',height:2*vpheight+'px'});
            $('#loginmask').css({opacity:0,display:'block'}).fadeTo(700,0.6); 
        }
        $('#logingrp').fadeIn(500);
    } else {
        $('#loginmask,#logingrp').fadeOut(800);
    }
    return false;
}

function loginHook(opt) {
    if (typeof(WF.username) != 'undefined') {
        opt.fn();
        return true;
    } else {
        window.WF.onloginsuccess = opt.fn;
        loginView(true,opt.message);
        return false;
    }
}

EXPORT();
})();
/* **************************** login ************************ */


/* ******************** unimplemented pref update hooks ******************************* */
/* 
function showprefs_refresh(data) {
    showdate = data.currentshowdate;
    if (showdate != lastshowdate) {
        prefs_request('get/favorite/0','fav_show_'+showdate);    
    }
}
function showprefs_hookupdates() {
    // hook into show updates (radio refresh)
    if (typeof(showupdate_events) == 'object'  &&  typeof(showupdate_events.push) == 'function') {
        showupdate_events.push(showprefs_refresh);
    } else {
        showupdate_events = [showprefs_refresh];
    }
}
*/

/*
 * Tooltip script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
 /*
function tooltip() {	
	xOffset = 6;
	yOffset = -15;		

	$("a.tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip' style='position:absolute'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY + yOffset) + "px")
			.css("left",(e.pageX + xOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	//$("a.tooltip").mousemove(function(e){
	//	$("#tooltip")
	//		.css("top",(e.pageY - xOffset) + "px")
	//		.css("left",(e.pageX + yOffset) + "px");
	//});			
};
	*/
//starting the script on page load
//$(document).ready(function(){
//	tooltip();
//});


/*
(function(){
function EXPORT() {$.each({
    'checkwidth':checkwidth,
    'windowwidth':windowwidth
},function(n,v){ WF[n]=v; })}

EXPORT();
})();
*/

/* **************************** UNIVERSAL ONREADY EVENTS ************************ */
//WF.checkwidth();
window.window_width = WF.windowwidth(); // obsolete?

$(document).ready(function(){ 
    if (document.getElementById('navsearch')) {
        WF.initNavSearch();
    }
    //WF.checkwidth();
    if ($('#divimage').length>0) {  
        WF.checkwidth();
        $(window).resize(WF.checkwidth);
    }
    WF.loginInit();
    
    var elshare = $('.boxsect.sharelinks');
    if (elshare.length > 0) {
        WF.contextualShareAdd(elshare.eq(0));
    }
});
