$(document).ready(function(){
	
	$("#content").load('news.tpl.php','',function(){
		$('#left_bar_content').jScrollPane({scrollbarWidth: 12});
	});

	var title = "";
	$("ul#menu > li > a").hover(
		function(){
			var position = $(this).position();
			title = $(this).attr("title");
			$("#menu_description span").text(title);
			$("#menu_description span").css({"left": (position.left-($("#menu_description span").width()/2))+"px"});
			$(this).attr("title", "");
		},
		function(){
			$("#menu_description span").text("");
			$(this).attr("title", title);
		}
	);

	$("ul#menu > li > a").live("click", function(event){
		var nav = $(this).attr('class');
		var href = $(this).attr('rel');
		$('#content').fadeTo('normal', 0.01, function(){
			$('body').attr('id', nav);
			//$('#content').html('<div class="loading"></div>');
			$("#content").load(href+'?random='+ Math.random()*99999,'',function(){
				$('#content').fadeTo('normal', 1);
				$('#left_bar_content, #shoutbox').fadeTo(500, 1, function(){
					$(this).jScrollPane({scrollbarWidth: 12});
				});
				$("#guestbook_form").bind("submit", '', submit_shoutbox_form);
				$('#right_bar_content').fadeTo(500, 1, function(){
															$(this).jScrollPane({scrollbarWidth: 12});
														});
				$("a.img").fancybox();
				$("a.flv").fancybox({'hideOnContentClick': false, 'frameWidth': 435, 'frameHeight': 365});
				$("a.txt").fancybox({'hideOnContentClick': false, 'frameWidth': 535, 'frameHeight': 530});
			});
		});
		
  		event.preventDefault();
	});
	
	$("a.ext").live("click", function(event){
		//$('#content').html('<div class="loading"></div>');
		$("#content").load($(this).attr('href'),'',function(){
			$('#left_bar_content, #shoutbox').jScrollPane({scrollbarWidth: 12});
			$('#right_bar_content').fadeTo(500, 1, function(){
														$(this).jScrollPane({scrollbarWidth: 12});
													});
			$("a.img").fancybox({'hideOnContentClick': false, 'callbackOnShow': imgStart});
			$("a.tillbaka").fancybox({'hideOnContentClick': false, 'callbackOnShow': imgStart});
			$("a.flv").fancybox({'hideOnContentClick': false, 'frameWidth': 435, 'frameHeight': 365});
			$("a.txt").fancybox({'hideOnContentClick': false, 'frameWidth': 530, 'frameHeight': 480});
		});
		
  		event.preventDefault();
	});
	
	function imgStart()
	{
		$("a.tillbaka").fancybox({'hideOnContentClick': false, 'callbackOnShow': imgStart});
		calcPrice();
		$("a.img").fancybox({'hideOnContentClick': false, 'callbackOnShow': imgStart});
	}
	
	$("a.bestall").live("click", function(event){
		var art = $(this).attr('art');
		var price = $(this).attr('price');
		var name = $('h3.name').text();
		var size = $('#sizes').val();
		if(!size)
		{
			size = '';
		}
			
		$.ajax({
			type: "POST", url: "merch_add.tpl.php?random="+ Math.random()*99999, data: "art=" + art + "&size="+size,
			success: function(data){
				alert(name+' är lagd i varukorgen.');
			}
		});
		event.preventDefault();	
	});
	
	$('a.cart_empty').live("click", function(event)
	{
		$.ajax({
			type: "POST", url: "merch_empty.tpl.php?random="+ Math.random()*99999, data: "",
			success: function(data){
				alert('Varukorgen är tom.');
				$('tbody td').each(function(){
					$(this).remove();
				});
			}
		});
		event.preventDefault();
	});
	
	$('a.cart_checkout').live("click", function(event)
	{
		var namn = $('#fornamn').val()+' '+$('#efternamn').val();
		var epost = $('#epost').val();
		var mobil = $('#telefon').val();
		var adress = $('#adress').val();
		var postnr = $('#postnr').val();
		var stad = $('#stad').val();
		var num_items = $('input[name=num_items]').val();
		
		if(check_checkout())
		{
			if(num_items == 0)
			{
				alert(num_items);
				alert('Du har inga varor i varukorgen.');
			}
			else
			{
				$.ajax({
					type: "POST", url: "merch_save.tpl.php?random="+ Math.random()*99999, data: "namn="+namn+"&epost="+epost+"&mobil="+mobil+"&adress="+adress+"&postnr="+postnr+"&stad="+stad,
					success: function(data){
						$.ajax({
							type: "POST", url: "merch_empty.tpl.php?random="+ Math.random()*99999, data: "",
							success: function(data){
								$('tbody td').each(function(){
									$(this).remove();
								});
								$('input').each(function(){
									$(this).val('');
								});
								alert('Tack för din beställning!');
							}
						});
						event.preventDefault();
					}
					
				});
			}
		}
		else
		{
			alert('Fyll i alla fält!');
		}
		event.preventDefault();
	});
	
	function check_checkout()
	{
		var namn = $('#fornamn').val()+' '+$('#efternamn').val();
		var epost = $('#epost').val();
		var mobil = $('#telefon').val();
		var adress = $('#adress').val();
		var postnr = $('#postnr').val();
		var stad = $('#stad').val();
		
		if(namn && epost && adress && postnr && stad)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	$(".quantity input").live("keyup", function(event) {  
	    var orderCode = $(this).attr("name").slice(9, -1);  
	    var quantity = $(this).val();  
		var size = $(".item_size[name*=" + orderCode + "]").text();
		//alert(orderCode+', '+quantity);
	    $.ajax({  
	        type: "GET",  
	        url: "merch_action.tpl.php",  
	        data: "order_code="+orderCode+"&quantity=" + quantity,  
	        success: function() {  
	            var startColor = $(".quantity input[name*=" + orderCode + "]").parent().parent().hasClass("odd") ? "#eee" : "#fff";  
	            $(".quantity input[name*=" + orderCode + "]").parent().parent().find("td").animate({ backgroundColor: "#ff8" }, 100).animate({ backgroundColor: startColor }, 800);  
	            calcPrice();  
	        },  
	        error: function() {  
	            window.location("merch_action.tpl.php?quantity[" + orderCode + "]=" + quantity);  
	        }  
	    });  
	});
	
	$(".remove input").live("click", function(event) {  
      var orderCode = $(this).val();  
		var size = $(".item_size[name*=" + orderCode + "]").text();
		if(!size){size = '';}
		//alert(orderCode+size);
      $.ajax({  
          type: "GET",  
          url: "merch_action.tpl.php",  
          data: "remove[]=" + orderCode,  
          success: function() {  
              $(".remove input[value=" + orderCode + "]").parent().parent().fadeOut(500, function() {  
                  $(this).remove();  
                  calcPrice();  
              });  
          },  
          error: function() {  
              window.location("merch_action.tpl.php?remove[]="+orderCode);  
          }  
      });  
  });
	
	function calcPrice() {
		var totalPrice = 0;
		$(".quantity").parent().each(function() {
			var quantity = $(".quantity input", this).val();
			var unitPrice = $(".unit_price", this).text().slice(0,-4);
			var extendedPrice = quantity*unitPrice;
			var shipping = $('#shipping').text().slice(0,-4);
			totalPrice += extendedPrice;

			$(".extended_price", this).html(extendedPrice + " SEK");
			$("#total_price").html((parseInt(totalPrice)+parseInt(shipping)) + " SEK");
		});
		if ( totalPrice == 0 ) {
			//$("#cart").replaceWith("<p class='center'>Varukorgen är tom.</p>");
		}
	}
	
	function submit_shoutbox_form(){  
 	    if(checkForm()){  
 	        var nick = $("#nick").val();  
 	        var message = $("#message").val(); 
 	        //we deactivate submit button while sending  
 	        $("#send").attr({ disabled:true, value:"Skickar" });  
 	        $("#send").blur();  
 	        //send the post to shoutbox.php 
			$.ajax({
				type: "POST", url: "guestbook.tpl.php?action=guestbook_insert&random="+ Math.random()*99999, data: "nick=" + nick + "&message=" + message,
				complete: function(data){
					$("#content").load('guestbook.tpl.php?random='+ Math.random()*99999,'',function(){
						$('#shoutbox').jScrollPane({scrollbarWidth: 12});
						$("#send").attr({ disabled:false, value:"Skicka!" });  
						$("#message").val("");
						$("#guestbook_form").bind("submit", '', submit_shoutbox_form);
					});
				}
			});
 	    }  
 	    else{alert("Fyll i alla fält!")};  
 	    //we prevent the refresh of the page after submitting the form  
 	    return false;  
 	}

	function checkForm(){
		if($("#nick").val() && $("#message").val())
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	
	/* MUSIC */
	$('#playlist').toggle(
		function(){
			$("#pl_list").fadeIn('slow');
			$("#playlist a").html('<span>Spellista <img src="_bilder/layout/play_icon_down.gif" alt="play_icon" width="8" height="6"/></span>');
		},
		function(){
			$("#pl_list").fadeOut('slow');
			$("#playlist a").html('<span>Spellista <img src="_bilder/layout/play_icon.gif" alt="play_icon" width="8" height="8"/></span>');
		}
	);
	
	var usePlayList = false;
	var playItem = 0;
	var playListLength = myPlayList.length;

	$("#jplayer").jPlayer({
		ready: function() {
			displayPlayList();
			playListEnable(true);
			$("#jplayer").volume(25);
		}
	});
	
	
	$("#jplayer").jPlayerId("play", "player_play");
	$("#jplayer").jPlayerId("pause", "player_pause");
	$("#jplayer").jPlayerId("stop", "player_stop");

	$("#jplayer").onSoundComplete(endOfSong);

	$("#ctrl_prev").click( function() {
		playListPrev();
		return false;
	});

	$("#ctrl_next").click( function() {
		playListNext();
		return false;
	});

	function endOfSong() {
		if(usePlayList) {
			playListNext();
		}
	}

	function displayPlayList() {
		$("#playlist_list").append("<ul></ul>");
		for (i=0; i < myPlayList.length; i++) {
		
			var album = "";
			if(myPlayList[i].album != "")
			{
				album = " ("+myPlayList[i].album+")";
			}
			
			$("#playlist_list ul").append("<li id='playlist_item_"+i+"'><input type='checkbox' checked='true' class='checkbox' id='playlist_box_"+i+"' /><span>"+ myPlayList[i].name +" "+album+"</span></li>");
			$("#playlist_item_"+i+" span").data( "index", i ).hover(
				function() {
					if (playItem != $(this).data("index")) {
						$(this).addClass("playlist_hover");
					}
				},
				function() {
					$(this).removeClass("playlist_hover");
				}
			).click( function() {
				var index = $(this).data("index");
				if (playItem != index) {
					playListChange( index );
				}
			});
		}
		$("#playlist_list input").bind("click", function(){
		if($(this).attr("checked") == true)
		{
			playListLength += 1;
		}
		else
		{
			playListLength -= 1;
		}
		});
		
		$('#playlist_list').jScrollPane({scrollbarWidth: 12});
		$('#pl_list').hide();
	}

	function playListEnable(e) {
		usePlayList = e;
		if(usePlayList) {
			playListChange( playItem );
			$("#jplayer").stop();
		} else {
			$("#jplayer").stop();
		}
	}

	function playListChange( index, b ) {
	if($("#playlist_item_"+index+" input").attr("checked"))
	{
		$("#playlist_item_"+playItem).removeClass("playlist_current");
		$("#playlist_item_"+index).addClass("playlist_current");
		$("#trackname").html($("#playlist_item_"+index).text());
		$('#trackname').marquee();
		if(myPlayList[index].image != "")
			{
				$("#music_player .img").html("<img src='_bilder/content/disco_thumbs/"+myPlayList[index].image+"' alt='"+$("#playlist_item_"+index).text()+"' width='34' />");
			}
			else
			{
				$("#music_player .img").html("<img src='_bilder/content/album_thumbs/blank.gif' alt='"+$("#playlist_item_"+index).text()+"' width='34'/>");
			}
		playItem = index;
		$("#jplayer").setFile(myPlayList[playItem].filename).play();
	}
	else
	{
		if(playListLength <= 1)
		{
			next = playItem;
		}
		else
		{
			if(b == "n")
			{
				next = index + 1;
			}
			else
			{
				next = index - 1;
			}
		}
		playListChange( next, b )
	}
	}

	function playListNext() {
		if(usePlayList) {
			var index = (playItem+1 < myPlayList.length) ? playItem+1 : 0;
			playListChange( index, 'n' );
		}
	}

	function playListPrev() {
		if(usePlayList) {
			var index = (playItem-1 >= 0) ? playItem-1 : myPlayList.length-1;
			if(index == 0 && $("#playlist_item_"+index+" input").attr("checked") == false)
			{
				index = myPlayList.length-1;
			}
			playListChange( index, 'p' );
		}
	}


});