// -------------------------------------------------------------------------------------
//                      rolldabeats JavaScript functions
// -------------------------------------------------------------------------------------

// Handle page jump on related select change
function do_page_jump(formobj,formtype)
{
  if (formobj.options[formobj.selectedIndex].value != "")
  {
    window.location = '/' + formtype + '/' + formobj.options[formobj.selectedIndex].value;
  }
}

// Cursor into search box on page load
//addEvent( window, 'load', function() { document.getElementById('search_words').focus() } );

function addEvent( obj, evType, fn )
{
	if( obj.addEventListener )
	{
		obj.addEventListener( evType, fn, true );
    return true;
	}
	else if ( obj.attachEvent )
	{
		var r = obj.attachEvent( 'on' + evType, fn );
		return r;
	}
	else
	{
		return false;
	}
}

// Flash controls

// get our flash movie object
var flashMovie;
    function init() {
        if (document.getElementById) {
        flashMovie = document.getElementById("audioplayer");
    }
}

// wait for the page to fully load before initializing
window.onload = init;

function playTrack(id) {
	flashMovie.playTrack(id);	
	switchCode(id,'load');
}

function stopTrack(id) {
	flashMovie.stopTrack();	
	switchBtn(id);
}

function pauseTrack(id) {
	flashMovie.pauseTrack();
	switchCode(id,'unpause');
}

function unpauseTrack(id) {
	flashMovie.playTrack(id);	
	switchCode(id,'pause');
}

var oldid = '';

// 
function switchCode(id,action) {

switch (action) {

	case "load":
        $(".btn"+id+" img").attr("src","/images/icon_loader.gif");
        $("."+id+"").attr("title","Loading audio clip");
        $("#tooltip").remove();
    break;
	case "stop":	
        $(".btn"+id+" img").attr("src","/images/icon_stop.png");
        $(".btn"+id+"").attr("href","javascript:stopTrack('"+id+"')");
        $("."+id+"").attr("title","Stop audio clip");
    break;
	case "pause":	
        $(".btn"+id+" img").attr("src","/images/icon_pause.png");
        $(".btn"+id+"").attr("href","javascript:pauseTrack('"+id+"')");
        $("."+id+"").attr("title","Pause audio clip");
    break;
	case "unpause":	
        $(".btn"+id+" img").attr("src","/images/icon_play.png");
        $(".btn"+id+"").attr("href","javascript:unpauseTrack('"+id+"')");
        $("."+id+"").attr("title","Play audio clip");
    break;
	case "play":	
        $(".btn"+id+" img").attr("src","/images/icon_play.png");
        $(".btn"+id+"").attr("href","javascript:playTrack('"+id+"')");
		$(".btn"+id+"").attr("title","Play audio clip");
	break;

}
	
}

function switchBtn(id) {

var src = $(".btn"+id+" img").attr("src");

if (src == "/images/icon_play.png") {
    switchCode(id,'load');
}
if (src == "/images/icon_loader.gif") {
    switchCode(id,'play');
}
if (src == "/images/icon_stop.png") {
    switchCode(id,'stop');
}


// set last image back to stop if it's still playing
	if ((oldid != '')&&(oldid != id)) {
 	   switchCode(oldid,'stop');	
	}
		oldid = id;
}

function updatecollection(list,release_id,action){
	if (list == 'c')
	{
		var file = '/alter_collection_ajax.php?release_id=' + release_id + '&action=' + action;
	} else {
        var file = '/alter_wishlist_ajax.php?release_id=' + release_id + '&action=' + action;
	}
	var imgid = '';
    var liid = 'li' + release_id;
    var aid = '';
	$.get(file, function(data){
		var originalBG = '';
		var fadeColor = "#ff0000"; 
		if (list == 'c') 
		{
			imgid = 'imgc' + release_id;
			aid = 'ac' + release_id;
			switch (action)
            {
            	case 'add':
		        	$("."+imgid).attr({src:"/images/icon_remove_small.gif"});
		        	$("."+liid).removeClass("dark");
		        	$("."+liid).removeClass("light");
					$("."+liid).addClass("incollection");
		        	$("."+aid).attr({href:"javascript:updatecollection('c','" + release_id + "','remove')",title:"Remove from collection"});
            	break;
            	case 'remove':
   		         	$("."+imgid).attr({src:"/images/icon_add_small.gif"});
		        	$("."+liid).removeClass("incollection");
					$("."+liid).addClass("light");
		        	$("."+aid).attr({href:"javascript:updatecollection('c','" + release_id + "','add')",title:"Add to collection"});
            	break;
			}
		} else {
            imgid = 'imgw' + release_id;
		    aid = 'aw' + release_id;
		    switch (action)
			{
			    case 'add':
		        	$("."+imgid).attr({src:"/images/icon_remove_small.gif"});
		        	$("."+aid).attr({href:"javascript:updatecollection('w','" + release_id + "','remove')",title:"Remove from wishlist"});
	        	break;
	        	case 'remove':
		        	$("."+imgid).attr({src:"/images/icon_add_small.gif"});
		        	$("."+aid).attr({href:"javascript:updatecollection('w','" + release_id + "','add')",title:"Add to wishlist"});
	        	break;
			}
		}
	});
}

// max length for comment boxes
function limitChars(textid, limit, infodiv)
{
	var text = $('#'+textid).val(); 
	var textlength = text.length;
	if(textlength > limit)
	{
		$('#' + infodiv).html('You cannot write more then '+limit+' characters!');
		$('#'+textid).val(text.substr(0,limit));
		return false;
	}
	else
	{
		$('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
		return true;
	}
}

$(function(){
	$('#addcomment').keyup(function(){
	limitChars('addcomment', 500, 'charlimitinfo');
	})
});

/*
 * 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
 *
 */

this.tooltip = function(){	
	/* CONFIG */		
		xOffset = 12;
		yOffset = 12;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$("a.tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "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();
});

/*
 * Image preview 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
 *
 */
 
this.imagePreview = function(){	
	/* CONFIG */
		
		xOffset = 12;
		yOffset = 10;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("span.preview").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='preview'><img src='"+ this.id +"' alt='Image preview' />"+ c +"</p>");								 
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	$("span.preview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};


// Home page accordion
$(document).ready(function(){
	$("#accordion dd:not(:first)").hide();
	$("dt a").click(function(){
		$("dd:visible").slideUp("slow");
		$(this).parent().next().slideDown("slow");
		if ( $("#home_events_flyer").length > 0 ) {
			if ( $("#home_events_flyer").css("display") == "none" ) {
				$("#home_events_flyer").fadeIn("slow");
			} else {
				$("#home_events_flyer").fadeOut("slow");
			}
		}
		return false;
	});
});

// Home page get latest comments 
function showComments() {
	var file = "/comment.php?t=home";
	$.get(file, function(data){
		$('#latest_comments').html(data);
	});
	if ( $("#latest_comments").css("display") ==  "none" ) {
		$("#updates div").fadeOut("slow");
		setTimeout ( "$('#latest_comments').fadeIn('slow')", 500 );
	}
}

function showUpdates() {
	if ( $("#additions").css("display") ==  "none" ) {
		$("#updates div").fadeOut("slow");
		setTimeout ( "$('#additions').fadeIn('slow')", 500 );
	}
}


// starting the script on page load
$(document).ready(function(){
	imagePreview();
});

// galleries
$(document).ready(function(){

if ($('ul.thumb_gallery').length > 0 )
{

	$('.thumb_gallery_unstyled').addClass('thumb_gallery'); // adds new class name to maintain degradability
		
	$('ul.thumb_gallery').galleria({
		history   : true, // activates the history object for bookmarking, back-button etc.
		clickNext : true, // helper for making the image clickable
		insert    : '#main_image', // the containing selector for our main image
		onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
			
			// fade in the image & caption
			image.css('display','none').fadeIn(1000);
			caption.css('display','none').fadeIn(1000);
			
			// fetch the thumbnail container
			var _li = thumb.parents('li');
			
			// fade out inactive thumbnail
			_li.siblings().children('img.selected').fadeTo(500,0.3);
			
			// fade in active thumbnail
			thumb.fadeTo('fast',1).addClass('selected');
			
			// add a title for the clickable image
			image.attr('title','Next image >>');
		},
		onThumb : function(thumb) { // thumbnail effects goes here
			
			// fetch the thumbnail container
			var _li = thumb.parents('li');
			
			// if thumbnail is active, fade all the way.
			var _fadeTo = _li.is('.active') ? '1' : '0.3';
			
			// fade in the thumbnail when finnished loading
			thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
			
			// hover effects
			thumb.hover(
				function() { thumb.fadeTo('fast',1); },
				function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
			)
		}
	});
}
});

/* Show the drop down menu  */

function showDropDown(ddid) {
	$('#'+ddid).fadeIn("fast");
	if ((ddid == "genres")||(ddid == "favourites")||(ddid == "downloads")||(ddid == "youtube")||(ddid == "clip")||(ddid == "sample_admin") )
	{
		$('#'+ddid).bind("mouseenter",function() {
			$('#'+ddid).bind("mouseleave", function() {
				$('#'+ddid).fadeOut("slow");
		  	});
	   });		
	}
	else
	{
		$('.drop_down').bind("mouseenter",function() {
			$('.drop_down').bind("mouseleave", function() {
				$('.drop_down').slideUp("fast");
		  	});
	   });
	}
}

function showGenres(type,id) {
	showDropDown('genres');
	$('#genre_type').attr("value",type);
	$('#genre_id').attr("value",id);
}

function showClip(action,id) {
	showDropDown('clip');
	$('#clip_action').attr("value",action);
	$('#clip_id').attr("value",id);
}

function showVideo(action,id) {
	showDropDown('youtube');
	$('#video_action').attr("value",action);
	$('#video_id').attr("value",id);
}

function showSample(action,id) {
	showDropDown('sample_admin');
	$('#sample_action').attr("value",action);
	$('#sample_track_id').attr("value",id);
}

function showEtching() {
	showDropDown('add_etching');
}

function hideDropDown(ddid) {
	$('#'+ddid).hide("fast");
}

function fadeElement(id) {
	$('#'+id).fadeOut();
}

/* 
Star rater AJAX going in here
*/

function rateRelease(release_id,rating) {
	file = "/rate.php?id=" + release_id + "&rating=" + rating;
	$.get(file, function(data){
		i = data.split("#")
		if (i[1] > 1)
		{
			rateinfo = "Rated " + i[0] + "/5 (<a href=\"javascript:showDropDown('voters')\">" + i[1] + " votes</a>) | Your rating: " + rating + "/5";
		}
		else 
		{
			rateinfo = "Rated " + i[0] + "/5 (<a href=\"javascript:showDropDown('voters')\">1 vote</a>)| Your rating: " + rating + "/5";
		}
		$('#rateinfo').html(rateinfo);
		percentage = ((i[0] * 2) * 10);
		$('.current-rating').css({width:percentage + "%"});
	});
}

/*  AJAX for getting sub-genres in genres pop-up */

$(document).ready(function(){

	$(".parent_genres").click( function() {

	  var tag_id = this.value;
	  var file = "/tag.php?tag=" + tag_id + "&a=getsubs";
	
		$.get(file, function(data){
			$('#sub_genres').html(data);
		});
	});
});

// Generate links for bookmark icons

$(document).ready(function(){

	var docurl = document.location.href;
	var doctitle = document.title;
	
	$("#bookmark_digg").attr("href","http://digg.com/submit?url=" + docurl + "&amp;title=" + doctitle);
	$("#bookmark_delicious").attr("href","http://del.icio.us/post?url=" + docurl + "&amp;title=" + doctitle);
	$("#bookmark_facebook").attr("href","http://www.facebook.com/sharer.php?u=" + docurl);
	$("#bookmark_myspace").attr("href","http://www.myspace.com/Modules/PostTo/Pages/?c=" + docurl + "&amp;t=" + doctitle);
	$("#bookmark_stumble").attr("href","http://www.stumbleupon.com/submit?url=" + docurl + "&amp;title=" + doctitle);
	if ( $("#permalink").length > 0 ) {
		$("#permalink").attr("title",doctitle);
	}

});

// AJAX gallery 

var i = 0;
var loop = 1;
var src = '';
var title = '';
var url = '';
var count = '';
var new_id = '';
var old_id = '';

$(document).ready(function () {

if ( $("#campaign1").length > 0 ) {
		getXMLVars(i);
	}
});

function getXMLVars(i) {
	$.ajax({
		type: "GET",
		url: "/data.xml",
		dataType: "xml",
		success: function(xml) {
			count = $("images>image",xml).length
			src = $("images>image>url:eq("+i+")",xml).text();
			title = $("images>image>title:eq("+i+")",xml).text();
			url = $("images>image>link:eq("+i+")",xml).text();
			setAttributes(src,title,url,i,count);
		}
	});
}

function setAttributes(src,title,url,i,count) {			
//	alert(old_id);
	if ( (loop == 1) && (i == 0) ) 
	{
		$("#campaign1 img")
			.attr("src",src)
			.attr("id","img1")
			.fadeIn("slow");
		$("#caption p").html('<a href="'+url+'">'+title+'</a>');
	}
	else
	{
		new_id = parseInt(i)+1;
		if ( i == count)
		{
			new_id = i;
		}
		$("#img"+old_id).after("<img id=\"img"+new_id+"\" style=\"display:none\"/>");
		$("#img"+old_id).fadeOut("slow");
		setTimeout("removeImage('img"+old_id+"')",4000);
		$("#img"+new_id)
			.attr("src",src)
			.fadeIn("slow");
		$("#caption p").html('<a href="'+url+'">'+title+'</a>');
	}
	i++;
	old_id = i;
	if ( i == count)
	{
		loop++;	
		i = 0;
	}
	setTimeout("getXMLVars('"+i+"')",7000);

}

function removeImage(id) {
		$("#"+id).remove();
}

function getVideos(id) {
	var file = '/youtube.php?t=get&id=' + id;
	alert(file);
	$.get(file, function(data) {
		alert(data);
		$("#videos").html(data);
	});
 }
 
function showYoutube(id) {
	 var embed = '<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/' + id + '&amp;autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + id + '&amp;autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>';
	 $("#videos div").html(embed);
	file = "/youtube.php?vid=" + id + "&t=view";
	$.get(file);
 }
 
 var admin_vars = new Array();
 
 function showAdmin(type) {
	switch(type)
	{
		case "video":
			$('#admin h2').text = 'Add YouTube video';
			$('#admin #admin_content').html('<p><form name="" action="/youtube.php" method="get">YouTube ID or URL: <input type="text" name="vid" value="" /><input type="hidden" id="video_id" name="id" value="" /><input type="hidden" name="t" id="video_action" value="add" /><input type="submit" value="Submit" class="genre_submit" /></form></p>');
		break;
		case "clip":
			$('#admin h2').text = 'Add sound clip';
			$('#admin #admin_content').html('<p><form name="" action="/clip.php" method="get"><input type="text" name="f" value="" /><input type="hidden" id="clip_id" name="t" value="" /><input type="hidden" name="a" id="clip_action" value="add" /><input type="submit" value="Submit" class="genre_submit" /></form></p>');
		break;
		case "image":
			$('#admin h2').text = 'Add image';
			$('#admin #admin_content').html('<form name="" action="/image_add.php" method="post"><p>Enter an image URL: </p><p><input type="text" id="image_url" name="image_url" value="" /></p><p>Upload an image</p><p><input type="file" id="image_upload" name="image_upload" value="" /></p><input type="hidden" id="image_type" name="image_type" value="add" /><input type="hidden" id="image_id" name="image_id" value="" /><input type="hidden" id="image_log_id" name="image_log_id" value="" /><input type="hidden" id="image" name="image" value="1" /><input type="hidden" id="image_type" name="image_type" value="artist" /><p>Click this to confirm you own the copyrght to this image or the image is in the public domain</p><p><input type="submit" id="submit" name="submit" value="Submit" /></p></form>');
		break;
		case "genre":
		break;
		case "favourites":
		break;
		case "sample":
		break;
	}
 
 }
 
function showError(id) {
	var errors = new Array();
	errors[0] = "";
	errors[1] = "Error: This track has no soundclip associated with it. This has been reported to site admin.";
	errors[2] = "Error: This sound clip cannot been loaded. The error has been reported to site admin.";
	$('#error-message span').html(errors[id]);
	$('#error-message').slideDown("fast");
}
