/** lp33.js ********************************************************************
 *                                                                             *
 *	website: lp33.tv                                                           *
 *	author: matt antone                                                        *
 *	email: mattantone@lp33.tv                                                  *
 *  jQuery file and version: jquery-1.3.2.min.js                               *
 *  jQuery UI file and version: jquery-ui-personalized-1.6rc2.packed.js        *
 *                                                                             *
 *  Other Dependencies:                                                        *
 *  jquery.cookie.js                                                           *
 *  jquery.cycle.all.pack.js                                                   *
 *  jquery.form.js                                                             *
 *  jquery.lightbox-0.5.pack.js                                                *
 *  moderator.js (optional)                                                    *
 *                                                                             *
 *******************************************************************************/
 
 
 //Configuration
 // mode - used to turn off debugging. 'dev' activates logging. Switch to 'live' to remove logging.
 var mode = 'live';
 var domain = 'lp33.tv';
 
/*******************************************************************************
 * Player Functions                                                            *
 *******************************************************************************/

/* LP33 Update Player
 *
 * Usage: $.updatePlayer(memid);
 * @memid - integer
 * stringable: no
 * Loads a new playlist into the flash player then changes the stage displayed. 
 */
jQuery.updatePlayer = function(memid){
	if( (typeof document.awolplayer.changeMemberid) === "function"){
		document.awolplayer.changeMemberid(memid);	
		$('#Player-Large').attr('style','background: url(/assets/Stages/'+memid+'.png) no-repeat;');
		return false;
	}else{
		$.updatePlayer(memid);
	}
};



/* LP33 PlaySong
 * Usage: $.playSong();
 * load the artists playlist(mid) and start playing the song(sid)
 * @sid = song ID (integer)
 * @mid = member ID (integer)
 */
jQuery.playSong = function(mid,sid){
	if(!sid){
		sid=0;
	}
	document.awolplayer.changeMemberid(mid);
	document.awolplayer.vidCue(sid);
	return false;
};


/* LP33 init Play song behavior
 *
 */

jQuery.fn.initPlaySongBehavior = function(){
	//////$.log('start initPlaySongBehavior()');
	return this.each(function(){
		// clear any existing "click" events
		$(this).unbind('click');
		$(this).click(function(){
			$.playSong($(this).siblings('.artist').attr('id'),$(this).attr('id'));
			return false;
		});
	});
};

/*******************************************************************************
 * AJAX Functions                                                              *
 *******************************************************************************/

/**
 * Function: dialogForm()
 * Usage: $(element).dialogForm();
 * Dependencies:	element.message
 *					element.form
 *					element.altText
 *					element.href
 * Description: Function retrieves data from the element and sends an AJAX Request to element.href. If the response
 * returns a form the form is displayed and bound with an AJAX request. On form submit the form is submitted via AJAX.
 * The response error or complete displayed. if the response is a handshakes complete, dialogTimer() is invoked.
 **/
 
jQuery.fn.dialogForm = function(){
	return this.each(function(){
		$(this).unbind().click(function(){
		 		$('#Content .systemMessage').remove();
		 		var curAnchor = this;
		 		var message = $(this).attr('message');
		 		var form = $(this).attr('form');
		 		var altText = $(this).attr('altText');
		 		$.ajax({
					type: "GET",
					url: $(this).attr('href')+"&ajax=true",
					dataType: "html",
					timeout: 20000, 
					success: function(html){
						if(form){
							$('#Dialog').empty().append(html+'<br style="clear"/>').dialog('open');
							if($('#Dialog form')[0]){
								$('#Dialog form').append('<input type="hidden" name="ajax" value="true"/>');
								$('#Dialog form').bind('submit',function(){
									$(this).ajaxSubmit({
									type: 'GET',
									dataType: "html",
									success: function(xml){
										//alert(xml.status);
										if($('.systemMessage span',xml)[0]){
											$('#Dialog .error').remove();
											$('#Dialog').prepend($('.systemMessage',xml).html());
										}else{
											//Total HACK fix later
											$('#Dialog').prepend('<span class="success"><button onclick="$(\'#Dialog\').dialog(\'close\')">Close Dialog</button>'+message+'</span>');
											$('#Dialog .success').dialogTimer();
										}
										return false;
									},
									failure: function(xml){
										if($('.systemMessage',xml).html()[0]){
											$('#Dialog').prepend('<span class="error"><button onclick="$(\'#Dialog\').dialog(\'close\')">Close Dialog</button>AJAX Error</span>');
											return false;
										}
									},
									complete: function( data, status ) { 
		      						}
									});
									return false;
								})
							}
							$('#Dialog .formbutton input').each(function(){
								////////$.log($(this));
								$(this).unbind();
								switch($(this).attr('value')){
									case 'Cancel':
										$(this).unbind().click(function(){$('#Dialog').dialog('close');return false;});
										break;
									case 'Send':
										$('#Dialog .error').remove();
										break;
								}
								return false;
							});
						}else{
							
							if($('.systemMessage span',xml)[0]){
								$('#Content').prepend($('.systemMessage',xml));
								$(curAnchor).empty().append(language[$(curAnchor).attr('name')][newObject]['menutext']);
								$(curAnchor).attr('status',newStatus);
							}else{
								//Total HACK fix later
								curLanguage = language[$(curAnchor).attr('name')];
								if($(curAnchor).attr('status')==1){
									newObject = 'neg';
									newStatus = 0;
								}else{
									newObject = 'pos';
									newStatus = 1;
								}
								$('#Content').prepend('<div class="systemMessage"><span class="success">'+language[$(curAnchor).attr('name')][newObject]['message']+'</span></div>');
								$(curAnchor).empty().append(language[$(curAnchor).attr('name')][newObject]['menutext']);
								$(curAnchor).attr('status',newStatus);
								if($(curAnchor).attr('name') == 'friend' && $(curAnchor).attr('status')==1){
									$(curAnchor).attr('form',true);
								}
							}
							return false;					
						}
					},
					failure: function(){},
					complete: function(){
						//$('.toplists').getLists('/xml_content/lists.xml','lists list');
					}
				});
					return false;
	 		});
	});
};


/**
 *
 **/


/**
 * Function: getContent()
 * Usage: getContent(url,callback);
 * @url - string - url must return valid HTML.
 * @callback - function
 * Description: Gets the repsponse of url and displays it. If callback is supplied and is a function it is eval()'d.
 * NOTE: Element must have the attribute 'id'. The Response html must contain the same id as the element whose content you intend to replace. For example,
 * if your element has an id of "#WholePage" then the returned html must contain "#WholePage". 
 **/
jQuery.fn.getContent = function(url,callback){
	var curElSelector = this.selector;
	return this.each(function(){
		url = makeAJAXURL(url);
		var curElement = $(this);
		curElement.insertLoadingImg();
		var curID =  $(curElement.context.selector);
		$.get(url,function(data){
				var content = $(curElSelector,data).html();
				curElement.empty().append(content);
				applyContentBehaviors();
				//check to see if moderator scripts are loaded and apply behaviors
				if(typeof applyModeratorBehaviors == 'function'){
					applyModeratorBehaviors();
				}
				runCallback(callback);
		});
		return false;
	});
}

/*******************************************************************************
 * Init Behaviors                                                              *
 *******************************************************************************/

/**
 * Function: initAnimateList()
 * Usage: $(ul or ol).intiFeaturedArtists();
 * Description: Takes the every list item of the unordered or ordered list and turns it into a slideshow.
 * Parent Item must be undordered or ordered list.
 **/
 jQuery.fn.initAnimateList = function(){
	return this.each(function(){
		if($('li',this).length > 1){
			var element = this;
			$(element).lp33SlideShow();
		}else{
			$('li:eq(0)',this).show();
		}
	});
};

/**
 * Function: initAccordion();
 * Usage:
 **/
jQuery.fn.initAccordion = function(){
	return this.each(function(){
		if($('ol',this).length > 1){
			$(this).accordion({
				header: 'a.listheader',
				autoHeight: 'true'
			});
		}
	});
};

jQuery.initChannelButtons = function(){
			$('.channelbutton').unbind();
			$('.channelbutton').click(function(e){
				//Clear any messages being displayed
				$.clearmessage();
				var curEl = $(this);
				
				this.channelid = curEl.attr('channel');

				//Assign callback function
				this.callback = function(){
					$.updatePlayer(this.channelid);
				}

				//Deselect all channel buttons
				$('.channelbutton').each(function(){$(this).removeClass('selected')});
				
				//Make this button selected
				$('#Channels a[channel = '+this.channelid+']').addClass('selected');
				
				//write new value to cookie
				$.cookie('curchannel', this.channelid, { path: '/', domain: domain, secure: false })
				//update the id of HTML so we can intantiate new styles for the page.
				newid = jQuery.trim($(this).attr('genre'));
				regex = "[^a-zA-Z0-9]";
				newid = newid.replace(regex,'');
				$('html').attr('id',newid);
				//$('html').attr('id',jQuery.trim($(this).text()));
				
				//strip nonalphanumeric characters out
				link =  $(this).attr('href')
				//Get Content & reload player after loading content
				$('#WholePage').getContent(link,$.context(this).callback('callback'));
				return false;
			});
};

function initDialog(){
	$('#Dialog').dialog({
	    autoOpen: false,
	    modal: true,
	    height: 140,
	    modal: true,
	    overlay: {
	        backgroundColor: '#000',
	        opacity: 0.5
	    },
	    resizable: false,
	    width: 500
	    //position: ['center','center']
	});
}
/*******************************************************************************
 * Utilties                                                                    *
 *******************************************************************************/

/**
 * Function: context();
 * Usage: $.context(this);
 * Description: forces context for a given object using "closure" method.
 **/
jQuery.extend(
{
	context: function (context){
		var co = {
			callback: function (method){
				if (typeof method == 'string') method = context[method];
				var cb = function () { method.apply(context, arguments); }
				return cb;
			}
		};
		return co;
	}
}); 


jQuery.fn.lp33SlideShow = function(){
	return this.each(function(){
		$('ol,ul',this).cycle({fx: 'fade',speed: 50, timeout: 6000});
	});
};


/* LP33 Javascript Log
 *
 * Usage: //////$.log(message);
 * @ message - string
 * stringable: no 
 * Use this to log your javascript. 
 * If you're using Firebug in FF then the log will show up in the console tab. 
 * All other browsers will show an alert. 
 *
 */

jQuery.log = function(message){
	if(mode == 'dev'){
		if(window.console){
			////console.log(message);
		}else{
			$('body').append(message+'<br/>');
		}
	}
	return false;
};

/* LP33 Clear Message
 *
 * Usage: $.clearmessage();
 * stringable: no
 * Use this to clear any messages displayed on the screen. 
 */

jQuery.clearmessage = function(message){
	$('#errorLine *').fadeOut().remove();
	return false;
};


/**
 * Function: insertLoadingImg()
 * Usage: $(element).insertLoadingImg()
 * Description: Replaces innerHTML of element with an AJAX Loading image.
 **/
jQuery.fn.insertLoadingImg = function(){
	return this.each(function(){
		//insert loading image.
		$(this).empty().append('<div class="loading"><img src="/themes/lp33_beta/Assets/Images/ajax-loader.gif" class="loader"/></div>');
	});
}


/**
 * Function: dialogTimer();
 * Usage: $(dialogelement).dialogTimer();
 * Description: Adds a "countdown" to dialogelement. The element must be invoked using $(dialogelement).dialog('open');
 **/

jQuery.fn.dialogTimer = function(){
	return this.each(function(){
		curElement = $(this);
		curStatus = $('span',this).attr('class');
		$(this).addClass(curStatus);
		$('span',this).before('<span class="timer">Closing dialog in <span>5</span> seconds. <a href="">close now</a></span>');
		$('span a',this).click(function(){
			$('#Dialog').dialog('close');
			return false; // Added this to prevent page from refreshing when clicking close link
		});
		var close = setInterval( function(){
			curTime = $('#Dialog .timer span').text();
			if(curTime > 0){
				$('#Dialog .timer span').empty().append(eval(curTime - 1));
			}else{
				window.clearInterval(close);
				//$(curElement).remove();
				$('#Dialog').dialog('close');
			}
		}, 1000 );
		
	});
};

/**
 * Function: displayError()
 * Usage: $(element).displayError();
 * Description: adds 'close' functionality and displays 'element'.
 **/
 
 jQuery.fn.displayError = function(){
	return this.each(function(){
		curElement = $(this);
		curStatus = $('span',this).attr('class');
		$(this).addClass(curStatus);
		$('span',this).before('<span class="timer"><a href="">close</a></span>');
		$('span a',this).click(function(){
			$(curElement).hide().empty();
			return false;
		});
		$(this).show();
	});
};

/**
 * Function: makeAJAXURL()
 * Usage: var x = makeAJAXURL(url);
 * Returns: string
 * Description: Turns SEO friendly URI into a handshakes URI
 **/
 function makeAJAXURL(url){
	if(url.indexOf('index.php') == -1){
		urlArray = url.split('/');
		if(urlArray[3]=='artist' || urlArray[3]=='artists'){
			if(!urlArray[5]){
				var section = 'home';
			}else{
				var section = urlArray[5];
			}
			url = '/artists/index.php?folder='+urlArray[4]+'&section='+section+'&ajax=true';
		}
		if(urlArray[3]=='profile' || urlArray[3]=='profiles'){
			if(!urlArray[5]){
				var section = 'home';
			}else{
				var section = urlArray[5];
			}
			url = '/profiles/index.php?folder='+urlArray[4]+'&section='+section+'&ajax=true';
		}
		if(urlArray[1]=='genre'){
			url = '/index.php?page=artist_home_'+urlArray[2]+'&ajax=true';
		}
		if(urlArray[1]=='artist' || urlArray[1]=='artists'){
			if(!urlArray[3]){
				var section = 'home';
			}else{
				var section = urlArray[3];
			}
			url = '/artists/index.php?folder='+urlArray[2]+'&section='+section+'&ajax=true';
		}
	}else{
		if(url.indexOf('?')){
			url = url+'&ajax=true';
		}else{
			url = url+'?ajax=true';
		}
	}
	return url;
}

function runCallback(callback){
	if(typeof callback == 'function'){
		callback();
	}
}


jQuery.query = function() {
	var r = {};
	var q = location.search;
	q = q.replace(/^\?/,''); // remove the leading ?
	q = q.replace(/\&$/,''); // remove the trailing &
	jQuery.each(q.split('&'), function(){
		var key = this.split('=')[0];
		var val = this.split('=')[1];
		// ingnore empty values
		if(val)
			r[key] = val;
	});
	return r;
};


/********* Legacy Player Functions **********/

function newDims() {
	$("#dim_screen").width( $(window).width() );
	$("#dim_screen").height( $(window).height() );
}


function scaleScreenUp() {
	$("#dim_screen").css({"opacity": 0.8});
	$("#dim_screen").css({"visibility":"visible"});
	$("#dim_screen").css({ top:"0" });
	$("#dim_screen").css({ left:"0" });
	$("#dim_screen").css({ "z-index":"200" });
	$("#awolplayer").css({ "z-index":"1000" });
	newDims();
}
function scaleScreenDown() {
	$("#dim_screen").width( 100 );
	$("#dim_screen").height( 100 );
	$("#dim_screen").css({ "z-index":"-1" });
	$("#dim_screen").css({"opacity": 1});
	$("#dim_screen").css({"visibility":"hidden"});
	$("#awolplayer").css({ "z-index":"1" });
	$("#player_container").css({ "z-index":"101" });
}

function hidePlayer() {
	$("#player").height( 170 );
	$(".top").height( 170 );
	return;
}

function jsShowPlayer(){
	$("#player").width( 1024 );
	$("#player").height( 425 );
	$("#player").css( 'visibility', 'visible' );
}