var production = window.location.hostname.indexOf('indieed.com') != -1;	// not on production

// clixpy tracking
document.write(unescape("%3C")+"script src='"+(document.location.protocol=="https:"?"https://":"http://")+"clixpy.com/clixpy.js?user=2496"+unescape("%26")+"r="+Math.round(Math.random()*10000)+"' type='text/javascript'"+unescape("%3E%3C")+"/script"+unescape("%3E"));

// site url
function site_url(url)
{
	if( !production )	
		return 'http://' + window.location.hostname + '/indieed/index.php/' + url;
	
	return "http://www.indieed.com/index.php/" + url;
}

// amazon s3 url
function s3_url(url)
{
    return "http://indieed.s3.amazonaws.com/" + url;
}

// site url from window.location.pathname
function site_url_pathname(pathname)
{
	var pathparts = pathname.split('/')
	
	// remove first blank and first index.php/ part
	pathname = pathname.substr(1, pathname.length);
	pathparts.shift();
	pathparts.shift();
	
	// remove first 'indieed/'
	if( !production )
		pathparts.shift();
	
	var pathname = pathparts.join('/');
	return site_url(pathname);
}

// nl2br br2nl
function nl2br(str)
{
	var final = str;
	
	final = final.replace(/\n/ig, "<br/>");
	final = final.replace(/\r/ig, "<br/>");

	return final;
}

function br2nl(str)
{
	var final = str;
	
	final = final.replace(/<br\/>/ig, "\n");
	final = final.replace(/<br\/>/ig, "\n");
	final = final.replace(/<br>/ig, "\n");
	final = final.replace(/<br \/>/ig, "\n");
	
	return final;
}

// reload window
window.reload = function() 
{
	window.location.href = window.location.href;
}

// blinkie!
$.blink = function(blink_on_func, blink_off_func, blinktime, numTimes, blinksDone)
{
	if( blinktime == null )
		blinktime = 500;
	
	var blinks = numTimes != null ? numTimes : 4;	// 4 blinks by default
	var blinkOff = true;
	var blinkID = setInterval(__nextBlink, blinktime);
	
	function __nextBlink()
	{
		if( blinks <= 0 ) {
		    
		    if(blinksDone != null)
		        blinksDone();
		        
			clearInterval(blinkID);
			return;
		}
		
		if( blinkOff ) {	// turn on
			blink_on_func();
		}
		else {
			blinks--;
			blink_off_func();
		}
			
		blinkOff = !blinkOff;
	}
}

/*
 	text slide in/out animation ('on' or 'off' as param)
	opts:
		numletters	- number of letters to add/remove at a time
		speed		- number of ms between letter add/remove
		instant		- true/false (skip animation)
*/

// speed is ms per letter to kill/add, numletters is number of letters to kill/create at a time
$.fn.slideText = function(onoff, opts)
{
	this.each(function()
	{
		var _self = this;
		
		// defaults
		opts = (opts == null) ? {} : opts;
		var _numletters = (opts.numletters == null) ? 2 : opts.numletters;
		var _speed = (opts.speed == null) ? 1 : opts.speed;
		var _curri;														// current index
	
		// save our fulltext
		if( _self._fullText == null )
		 	_self._fullText = $(_self).text();
		
		// instant initial collapse?
		if( opts.instant == true ) {
			$(_self).text('');
		}
		
		var _curri = $(_self).text().length;
	
		if( _self._intId != null )
			clearInterval(_self._intId);
			
		var func = (onoff == 'off') ? __killLetter : __addLetter;	// are we adding or killing?
		_self._intId = setInterval( func, _speed );
	
		function __killLetter()
		{
			if( _curri <= 0 )	// we're done
				clearInterval(_self._intId);
		
			_curri -= _numletters;
			var currText = _self._fullText.substring(0, _curri);
			
			// @safari hack to make sure icon shows
			if( currText == '' )
				currText = '&raquo;'
			
			$(_self).html(currText);
		}
	
		function __addLetter()
		{
			if( _curri > _self._fullText.length )	// we're done
				clearInterval(_self._intId);
		
			_curri += _numletters;	
			var currText = _self._fullText.substring(0, _curri) + ' &raquo;';
			$(_self).html(currText);
		}
	});
}

// function that enables us to preload our images
$.preloadImages = function(images)
{
	var hiddenDiv = $('#preloaded_images');
	
	// create hidden div element
	if( hiddenDiv.length == 0 ) {
			
		hiddenDiv = $("<div id='preloaded_images'></div>");
		$("body").prepend(hiddenDiv);	// attach it to our body
	}
	
	// load it up
	for(var i = 0; i<images.length; i++)
		hiddenDiv.append( $("<img>").attr("src", images[i]) );
		
	hiddenDiv.hide();
};

$.fn.fadeAndToggleClass = function(theClass, elems)
{
	var selves = this;	// so we don't loose 'this' in callback function
	var done = false;
	
	if( elems == null )
		elems = selves;
	
	// fade out, switch classes, fade in
	selves.fadeOut(150, function()
	{
		if( !done )	// only do it once
		{
			done = true;
			elems.toggleClass(theClass);
			selves.fadeIn(150);
		}
	});
};

// change an input's TYPE attribute (illusion)
$.fn.changeType = function(toType)
{	
	// do nothing for now... too many bugs
	return;
	
	var fromType = $(this).attr('type');
	var newInput = $('<input type="' + toType + '" />');
	
	if( this.value != null )
		newInput.val(this.value)
	
	if( $(this).attr('name') != null )
		newInput.attr('name', $(this).attr('name') );
		
	if( $(this).attr('class') != null )
		newInput.attr('class', $(this).attr('class') );
		
	if( $(this).attr('alt') != null )
		newInput.attr('alt', $(this).attr('alt') );
	
	if( fromType == null )	// default type of text
		fromType = 'text';
		
	newInput.insertBefore( $(this) );
	$(this).remove();
	
	return newInput;
}

// initial input look/feel
$.initial = function()
{	
	$('.initial').each( function() {
	    
		var input = $(this);

		input.val( input.attr('alt') );
		var isPass = (input.attr('type') == 'password');
		
		input.changeType('text');
		
		input.bind('focus', function() 
		{	
			if( input.is('.initial') ) {
				
				// remove initial value
				input.val('');
				input.removeClass('initial');

				if( isPass )	// change attribute to type password
					input.changeType('password');
			}

		});
		
		input.bind('blur', function() 
		{
			if( input.val() == '' ) {
				
				// show initial input if blank
				input.addClass('initial');
				input.val( input.attr('alt') );
				
				if( !$.browser.msie )
					input.changeType('text');	// change to type input (if we are passwrd) so user can see initial text
			}
		});
	});
	
	// revert to initial state if no input is provided
	$('#user_nav .username, #user_nav .password').bind('blur', function() 
	{	
		if( $(this).val() == '' ) {
			
			$(this).addClass('initial');
			
			if( $(this).is('.password') )
				$(this).changeType('text');	// change to type input so we can see 'password' text
				
			$(this).val( $(this).attr('alt') );
		}
			
	});
}

// show indieed player (play optional song_id)
var playerwin;

function playSong(song_id)
{
	if( playerwin == null || playerwin.closed ) {
		
		playerwin = window.open( site_url('radio/startwithsong/' + song_id), 'playerwin', 'resizable=1,directories=0,status=0,toolbar=0,location=0,menubar=0,width=430,height=430')
		
		if( !playerwin.opener )
			playerwin.opener = self;
	}
	else {
		playerwin.nowPlayThis(song_id);
	}
		
	playerwin.focus();
}

// requires: thickbox.js
function showMsg(msg)
{
	var closebtn = $('<span><br/><br/><div id="msgclosebtn"><p>ok</p></div></span>');
	
	$("#tbMsg p").html(msg + closebtn.html());
	$("#tbMsg").show();
	tb_show("", "#TB_inline?height=140&width=280&inlineId=tbMsg_tbshell&modal=false", false)
	$('#TB_ajaxContent').css({backgroundColor: '#403F01'});
	
	// style close button
	$('#msgclosebtn').css({
		padding: '3px',
		border: '2px solid black',
		backgroundColor: 'beige',
		color: '#333',
		width: '110px',
		margin: 'auto'
		
	});
	
	// style and show close button
	$('#msgclosebtn').click(function()
	{
		hideMsg()
	});
	
	$('#msgclosebtn').hover(function()
	{
		$('#msgclosebtn').css({
			backgroundColor: 'pink',
			cursor: 'hand'
		});
	}, 
	function()
	{
		$('#msgclosebtn').css({
			backgroundColor: 'beige'
		});
	});
	
	$('#msgclosebtn')[0].onmouseover = function(){};
	
	// overwrite overlay/close button tb_remove to hideMsg
	$('#TB_overlay').unbind('click', tb_remove);
	$('#TB_overlay').bind('click', hideMsg);
	
	$("#TB_closeWindowButton").unbind('click', tb_remove);
	$("#TB_closeWindowButton").bind('click', function()
	{
		hideMsg();
		return false;
	});
	
	setTimeout(hideMsg, 2500);
}

function hideMsg()
{
	$("#tbMsg").hide();
	tb_remove();
}

var _delayedExclusiveFuncs = [];	// functions that are delayed and exclusive
Function.delayedExclusiveCall = Function.delExCall = function(func, params, delay) 
{		
	// see if func being passed in is exclusive
	var exclusive = true;
	
	var funci;
	for(funci= 0; funci < _delayedExclusiveFuncs.length; funci++)
		if ( _delayedExclusiveFuncs[funci] != null && _delayedExclusiveFuncs[funci].func === func ) {
			exclusive = false;
			break;
		}
		
	// console.log('exclusive: ' + exclusive)
	
	// we only want to call our function once, so use this wrapper function to clear interval before calling 'real' function
	var intID = setInterval(function() {
		
		clearInterval(intID);
		_delayedExclusiveFuncs[funci] = null;
		func.apply(this, params);	// NOW we can call
		
	}, delay, params);
	
	if( exclusive ) {	// add new function
		_delayedExclusiveFuncs.push( {func:func, params:params, intID:intID} );
	}
	else {	
		
		// pass over new intervalID and parameters
		clearInterval( _delayedExclusiveFuncs[funci].intID );
		_delayedExclusiveFuncs[funci].intID = intID;
		_delayedExclusiveFuncs[funci].params = params;
	}
};

// requires clipboard.jquery.js
function copyToClipboard(txt)
{
	$.clipboard( txt );
	
	if( navigator.appVersion.indexOf("Mac") != -1 )	// mac os
		showMsg('Link copied. Press apple-v to paste.');
	else
		showMsg('Link copied. Press ctrl-v to paste.');
}

// initialization
var body;

$(function()
{
	body = $("body");
	
	// analytics
	require('lib/j/jquery.gatracker.js', function() {
		$.gaTracker('UA-494057-2');
	});
	
	if( $.clipboardReady )	// make sure clipboard is loaded on this page
		$.clipboardReady(function(){},{swfpath: "lib/j/jquery.clipboard.swf"});	// clipboard ready...
	
	$("img[src$=png]").pngfix();	// ie png fix
	
	preloadImages();
	function preloadImages()
	{
		var imgpath = "lib/i/";
		var images = [	'panel_song_listen_hover.jpg', 'panel_song_download_hover.jpg', 'panel_search_active.jpg',
						'panel_search_button_active.jpg'];

		// prepend image path
		for( var i = 0; i < images.length; i++ )
			images[i] = imgpath + images[i];

		$.preloadImages( images );
	}
	
	// for showMsg()
	var tbMsg = $('<div id="tbMsg_tbshell"><div id="tbMsg"><p>Hi.</p></div></div>');
	body.prepend(tbMsg);
	
	$('#tbMsg').css({
		color: 'white',
		fontSize: '15px',
		margin: '20px 0px',
		textAlign: 'center',
		fontFamily: 'Lucida Grande',
		display: 'none'
	});
	
	// usernav login/logout
	// logout
	$("a.logout").bind("click", function() {
		
		$.post( site_url("user/logout/JSON"), null, function(){
			window.location = site_url_pathname(window.location.pathname);
		});
		
		return false;
	});
	
	// login
	// initial input look/feel
	$.initial();
	
	// submit login
	$('#user_nav .username, #user_nav .password').keypress(function(eo) 
	{	
		if(eo.keyCode == 9 ) {	// tab
			
			$(this).blur();
			
			if( $(this).is('.username') )
				$('#user_nav .password').focus();
			else
				$('#user_nav .username').focus();
				
			return false;	// stop key event here
		}
		
		if( eo.keyCode == 13 || eo.keyCode == 77 )	// return, enter
			nav_login();
	});	
	
	$('#user_nav a.login').bind('click', nav_login);
	
	var saved_border = $('input.username, input.password').css('border'); // save border color for nav_login().failed
	function nav_login() 
	{
		var username = $('#user_nav .username').val();
		var password = $('#user_nav .password').val();
		var login = $('#user_nav a.login');
		
		login.text('signing in...');
		
		$.post( site_url("user/login/JSON"), {username:username, password:password}, function(data) {

			var res = eval('(' + data + ')');
			
			if( res.success ) {	// login successful?
				login.text('success!');
				window.location = site_url_pathname(window.location.pathname);
			}
			else {	// show error
				login.text('failed, try again');
				
				$.blink(function()
				{
				    $('input.username, input.password').css('border', '1px solid red');
				},     
				function()
    			{
				    $('input.username, input.password').css('border', saved_border);
				}, 250, 3, function()
				{
				    $('input.username, input.password').css('border', '1px solid red');
				})
			}
		});
		
		return false;
	}
	
	// search on <enter>
	$('#panel input[name=term]').keypress(function(eo) {
		
		if( eo.keyCode == 13 || eo.keyCode == 77 )	// return, enter
			$(this).parents('form:first')[0].submit();
	});
	
	// nobody likes you oh dotted lines... go away!
	body.find("a").focus(function() {
		this.blur();
	});

	body.find("select").change(function() {
		this.blur();
	});
	
	body.find("input[type=button]").bind('click', function(){
		this.blur();
	});
	
	body.find('button').bind('click', function() {
		this.blur();
	})
	
	// Turns grunge On/Off
	$("#controls .grunge_on").click (function()
	{
		body.addClass("grunge");
		return false;
	});

	$("#controls .grunge_off").click (function()
	{
		body.removeClass("grunge");
		return false;
	});
	
	// musicitembox system -- clean it up!!
	// clicking a musicitembox is the same as clicking the link contained within (unless we're clicking the options box)
	$('.resultrow:not(.separator)').click(function(eo) {
		
		var tgt = $(eo.target);
		if( tgt.is('.link') )
			return false;	// false cause we don't want to follow url
			
		if( tgt.is('.listen') || tgt.is('.download') )	// we do want to follow url
			return true;
		
		// window.location = $(this).find('a').attr('href');	// follow url inside our button
	});
	
	// slidey system -- @TODO: rebuild as a clean class?
	var COLLAPSE_DELAY = 500;	// in ms
	
	// make music chains out of each of the elements; should we collapse instantly on initial draw?
	$.fn.MusicChain = function(instantCollapse)
	{	
		$(this).each(function()
		{
			var chain = this;								// outter chain div
			var _boxes = $(chain).find('.mbox')				// boxes in chain
			
			var _timeoutID = null;
			var _optsTimeoutID = null;	
			var _collapseDelay = 500;						// in ms
			var _optsDelay = 0;
			
			// mbox_opts
			$(this).find('.mbox_opts .link').click(function() 
			{
				var link = $(this).parents('.resultrow:first').find('a:first').attr('href');	// get link of our item (.resultrow only)
				copyToClipboard(link);
				return false;
			});
			
			// hide links for now
			$(this).find('.mbox_opts .link').parent('li').css('display', 'none')
			
			__collapse(instantCollapse);	// initial collapse

			// collapse and hide chain links on mouseout of chain (after delay)
			$(chain).hover(function() {
				clearTimeout(_timeoutID)
			},
			function()
			{
				_timeoutID = setTimeout(function() 
				{
					__collapse();
				}, _collapseDelay);	// slight delay
			});
			
			// show/hide links from this box forward
			_boxes.each(function(i)
			{
				var box = $(this);
				var _opts = $(box).find('.mbox_opts');		// options
				
				_opts.hide();	// hide opts initially
				
				box.hover(function()
				{	
					// show boxes (except last)
					for( var b= i; b < _boxes.length-1; b++ )
						__expandBox(_boxes[b]);
						
					_optsTimeoutID = setTimeout(function() 
					{
						//_opts.animate({width:'show'}, 'fast'); // show extra options
						_opts.show();
					}, _optsDelay);	// after a slight delay that is
				},
				function()
				{
					clearInterval(_optsTimeoutID);
					//_opts.animate({width:'hide'}, 'fast');	// in case we're already animatin
					_opts.hide();
				});
			});
			
			// expand/collapse all except last elements in row
			function __expand(chain) 
			{
				for( var i= 0; i < _boxes.length-1; i++ )
					__expandBox(_boxes[i]);
			}

			function __expandBox(box) {
				$(box).find('a').slideText('on');
			}

			function __collapse(isInstant) 
			{
				for( var i= 0; i < _boxes.length-1; i++ )
					$(_boxes[i]).find('a').slideText('off', {instant:isInstant});
			}
		});
	}
});


// urlscript parser
$(function()
{
	// split hash up
	var hash = window.location.hash;
	var urlscriptchk = hash.substring(0,2) == '#/';
	
	if(!urlscriptchk)
		return false;
		
	var allowed_calls = ['show_album', 'show_song', 'show_photo'];
		
	// break hash into function call / params
	var hashparts = hash.substring(2, hash.length).split('/');
	var func = hashparts[0];
	var args = hashparts.slice(1);
	
	// security point
	var accept = false;
	for( var i = 0; i < allowed_calls.length; i++ )
		if( func == allowed_calls[i] )
			accept = true;
			
	if( !accept ) {
		// console.log(hashparts, 'unaccepted urlscript function call:', func, 'not in', allowed_calls);
		return false;
	}

	// quote params
	for( var i=0; i < args.length; i++ )
		args[i] = '"' + args[i] + '"';
	
	var argsstr = args.join(',');
	// sanatize rogue function calls
	argsstr = argsstr.replace(/\(/gi, '[');
	argsstr = argsstr.replace(/\)/gi, ']');
	
	// call the function
	setTimeout(function() {
		eval( 'javascript:' + func + '(' + argsstr + ')' );	// call it
	}, 0);	// make sure all js is loaded
});

// import a script
function require(script, onload)
{
	var s = document.createElement('script');
	s.setAttribute('src', script);
	document.body.appendChild(s);
	
	s.onload = onload;
	void(s);
}