/*
http://localhost/jquery.address/samples/api/#/'/section/2/1/?id=2.2&ho=23

value: 			$.address.value()			=	/section/?id=2.2
path: 			$.address.path()			= 	/section/2/1/
pathNames: 		$.address.pathNames()		= 	section, 2, 1
parameterNames: $.address.parameterNames()  =	{id: '2.2', ho: '23'}
queryString: 	$.address.queryString()		=	id=2.2&ho=23'
*/
$(function(){
	$("#cravechartsLogo").address();
	$("#footerContent .blueLink").address();
	$("#playlist_holder .comm_list").address();
	$('input#searchInput').bind('focus',function(){
		$(this).val("")
		search.init($(this));
		$(this).unbind('focus');
		return false;
	})
	$("#volImgLayer").slider({
		orientation: "vertical",
		min: 0,
		max: 100,
		value: crave.vol,
		slide: function(e, ui) {
		
			crave.vol = ui.value;
			if ( typeof( window[ 'mySound' ] ) == "object" )
			{
				mySound.setVolume( ui.value );
			}
			$('#volBg').css('height', ( 100 - ui.value ) + '%');
		}
	});

})

/*
$("input").live("click", function(){
	$(this).focus().select()
})
*/

$(function(){
	$.address.init(function(event) { //this function will run when the page is refresh or 1st time load. run the initialization function
	    var pathNames	=	$.address.pathNames()
	    navigate.init()
	}).change(function(event) { //this function will run whenever the address is change. it will run the route function
		var pathNames	=	$.address.pathNames()
	    navigate.route(pathNames)
	}).internalChange(function(event) {
	    //log('internalChange: ' + event.value);
	}).externalChange(function(event) {
	    //log('externalChange: ' + event.value);
	});
})

// This is the object class to control the navigation after "$.address.init" or "$.address.change"
var userLogined		= false;
var userId			= null;
var user_RoleId		= null;
var artistId		= null;
var listenerId		= null;
var currController 	= null;	//Current view controller

var navigate = {
	init : function()		//Initialize all var
	{	
		type		= "chartsweek"
		genreMain 	= "all";
		genreSub 	= "all";
		genre 		= genreMain+"/"+genreSub;
		charts 		= "/charts/chartsweek";
		page		= 0;
		totalSong	= 0;
		totalPage 	= 0;
	},
	route : function(path) //Route to the correct controller base on the 1st path
	{
		controller 		= path[0];

		if(controller == "charts") //if the 1st path equal to charts
		{
			type		= path[1];
			genreMain 	= path[2];
			genreSub 	= path[3];
			genre 		= genreMain+"/"+genreSub;
			charts 		= "/charts/"+type;
			page		= path[4];
			totalSong	= 0;
			totalPage 	= 0;
			
			if(currController == "charts") //if current controller equal to charts, dont need to load the charts page, skip tp the swap genre function
			{
				navigate.charts.swapGenre()
			}else{	//if current controller not equal to charts or from the other controller/page, load the whole charts page and run the process step by step
				navigate.charts.getPage()
			}
			
		}else if(controller == "searches")
		{
			action = path[1];
			variable = path[2];
			
			navigate.searches.getPage()
			
		}else if(controller == "listeners")
		{
			//action = path[1];
			//variable = path[2];
			listenerid = path[3];
			
			navigate.listener.getPage("id/"+listenerid)
			
		}else if(controller == "info")
		{
			action = path[1];
			//variable = path[2];
			//listenerid = path[3];
			
			navigate.info.getPage(action)
			//alert("sasas")
			
		}else if(controller == null) //if the 1st path equal to null, controller equal to charts
		{
			browserUrl 	= document.location.href;
			browserUrl 	= browserUrl.replace("http://dev.cravecharts.com/", "")
			browserUrl 	= browserUrl.replace("http://pro.cravecharts.com/", "")
			browserUrl 	= browserUrl.replace("http://cravedevs.com/", "")
			browserUrl 	= browserUrl.replace("http://cravecharts.com/", "")
			browserUrl 	= browserUrl.replace("http://www.cravecharts.com/", "")
			userUrls 	= browserUrl.split("/");
			userUrl		= userUrls[0]
			
			if(userUrl == null || userUrl == ""){
				controller 	= "charts";
				type		= "chartsweek";
				genreMain 	= "all";
				genreSub 	= "all";
				genre 		= genreMain+"/"+genreSub;
				charts 		= "/charts/chartsweek";
				page		= 0;
				totalSong	= 0;
				totalPage 	= 0;
				
				if(currController == "charts") //if current controller equal to charts, dont need to load the charts page, skip tp the swap genre function
				{
					navigate.charts.swapGenre()
				}else{	//if current controller not equal to charts or from the other controller/page, load the whole charts page and run the process step by step
					navigate.charts.getPage()
				}
			}else{
				userURL = userUrl;
				
				$.ajax({
				type	: 	'POST',
				url		: 	"/users/getRole/"+userURL,
				success	: 	function(data){
								if(data == "Artist")
								{
									if ( userUrls[1] == "play" )
									{
										userURL = userURL+"/"+userUrls[1]+"/"+userUrls[2]+"/";
									}
									navigate.artist.getPage(userURL)
								}else if(data == "Listener"){
									navigate.listener.getPage(userURL)
								}else{
									
								}
							}
				})
			}
			
		}else{ //route to other controller
			userURL = path[0];
			userSubPage = path[1];
			if(userSubPage == "play"){
				songId = path[2]
			}
			
			$.ajax({
				type	: 	'POST',
				url		: 	"/users/getRole/"+userURL,
				success	: 	function(data){
								if(data == "Artist")
								{
									if(userSubPage == "play"){
										//navigate.artist.getPage(userURL)
										navigate.artist.getPage(userURL+"/"+userSubPage+"/"+songId+"/")
									}else if ( userSubPage == null )
									{
										navigate.artist.getPage(userURL);
									}
									else{
										navigate.artist.getAccPage(userURL,userSubPage)
									}
									
								}else if(data == "Listener"){
									
									if(userSubPage == null){
										navigate.listener.getPage(userURL)
									}else{
										navigate.listener.getAccPage(userURL,userSubPage)
									}
								}else{
									
								}
							}
			})
			
			//navigate.artist.getPage(userURL)
			//alert('userLogined'+userLogined+' | userId'+userId+' | user_RoleId'+user_RoleId+' | artistId'+artistId)
		}
	},
	charts : {
		changeAdd : function(gm) //this is the function to change the address base on the menu that user click, genre or charts type
		{
			if($(gm).attr("href") != "all") //If user click other than All Genres
			{
				if($(gm).attr("class") == "discover genre_menu") //If user Click on Unselected Genre Menu
				{
					if(genreMain != "all") //if genreMain currently != all
					{
						if(genreSub != "all") //if genreSube currently != all, do nothing
						{
							
						}else{	//if genreSube currently == all, change genreSub to the selected genreMenu
							genreSub = $(gm).attr("href");
							
							page = 0;
							$.address.value('charts/'+type+'/'+genreMain+'/'+genreSub+'/'+page) // change the address
							
						}
					}else{ //if genreMain currently == all, change genremain to the selected genreMenu
						
						genreMain = $(gm).attr("href");
						
						page = 0;
						$.address.value('charts/'+type+'/'+genreMain+'/'+genreSub+'/'+page) // change the address
					}
				}else if($(gm).attr("class") == "discover genre_menuActive")  //If user Click on Selected Genre Menu
				{
					if(genreSub != "all"){ //if genreSub currently != all
						if($(gm).attr("href") == genreSub) //if selected genreMenu equal to current genreSub, change genreSub to all
						{
							genreSub 	= "all"
							
							page = 0;
							$.address.value('charts/'+type+'/'+genreMain+'/'+genreSub+'/'+page) //change the address
							
						}else if($(gm).attr("href") == genreMain){ //if selected genreMenu equal to current genreMain,
							genreMain 	= genreSub				   //change genreMain to genreSub and genreSub to all
							genreSub 	= "all"
							
							page = 0;
							$.address.value('charts/'+type+'/'+genreMain+'/'+genreSub+'/'+page) //change the address
						}
					}else{ //if genreSub currently == all
						if($(gm).attr("href") == genreMain) //if selected genreMenu equal to current genreMain, genreMain == all
						{
							genreMain 	= "all"
		
							page = 0;
							$.address.value('charts/'+type+'/'+genreMain+'/'+genreSub+'/'+page) //change the address
						}
					}
				}else if($(gm).attr("class") == "discover tabDefault") //If user Click on Tabs charts type
				{
					if(type != $(gm).attr("href"))
					{
						type = $(gm).attr("href")
						page = 0;
						
						$.address.value('charts/'+type+'/'+genreMain+'/'+genreSub+'/'+page) //change the address
					}
				}else if($(gm).attr("class") == "discover pageinationBttn"){
					page = $(gm).attr("href");
					
					$.address.value('charts/'+type+'/'+genreMain+'/'+genreSub+'/'+page)
				}
			}else{  //If user click All Genres, change both genreMain and genreSub to all
				genreMain 	= "all"
				genreSub 	= "all"
		
				page = 0;
				$.address.value('charts/'+type+'/'+genreMain+'/'+genreSub+'/'+page) //change the address
			}
		},
		getPage : function() // The function to get the charts page
		{
			if(currController == "charts")
			{
				$("#content").fadeOut("slow", function(){
					$(this).empty().load("/charts", function(){
						$(this).fadeIn("fast", function(){navigate.charts.loadGenre()})
					})
				})
			}else{
				$("#content").empty().load("/charts",function(){
					navigate.charts.loadGenre();
				});
				currController = "charts";
			}

			
		},
		loadGenre : function()
		{
			$("div#genre").load("/charts/genre", function(){
				navigate.charts.swapGenre()
			});
		},
		swapGenre : function()  //This function will run when address is change or after the genre has been loaded.
		{						//This function will change the genreMenu style base on selected genreMenu
			$("a#allGenre").removeClass("genre_menuActive").addClass("genre_menu");
			$(".genre_menuActive").removeClass("genre_menuActive").addClass("genre_menu");
			
			if(genreMain != "all"){
				$("a#mainGenre_"+genreMain).removeClass("genre_menu").addClass("genre_menuActive");
				
				if(genreSub != "all"){
					$("a#mainGenre_"+genreSub).removeClass("genre_menu").addClass("genre_menuActive");
				}else{
					$("a#allGenre").removeClass("genre_menuActive").addClass("genre_menu");
				}
			}else{
				$("a#allGenre").removeClass("genre_menu").addClass("genre_menuActive");
			}
			
			$("a.tabActive").removeClass("tabActive").addClass("tabDefault")
			$("a#"+type).removeClass("tabDefault").addClass("tabActive")
			
			navigate.charts.loadCharts() // Once done, load the charts base the address value
		},
		loadCharts : function() // The last step of the charts controller is to load the charts
		{
			
			$("div#loadingIndicator").show("fast", function(){
				$("div#charts").fadeOut("fast", function(){
					$(this).load(charts+"/"+genre+"/"+page*20, function (){
						$("div#loadingIndicator").hide();
						$(this).fadeIn()											 						   
					})
				})										   
			});
		}
		
	},info:{
		getPage : function()
		{
			$("div#loadingIndicator").show();
			$("#content").fadeOut("slow", function(){
					$(this).load("/info/"+action, function(){
						$(this).fadeIn("fast");
						$("div#loadingIndicator").hide();
					})
					
				})
			currController = "info";
		}
	},
	searches :{
		getPage : function()
		{
			$("#content").fadeOut("slow", function(){
					$(this).load("/searches/"+action+"/"+variable).fadeIn("fast");
					$("div#loadingIndicator").hide();
				})
			currController = "searches";
		}
	},
	artist : {
		getPage : function(url)
		{
			if(currController == "artists")
			{
				$("#content").fadeOut("slow", function(){
					$(this).empty().load("/artists/index/"+url).fadeIn("fast")
				})
			}else{
				$("#content").empty().load("/artists/index/"+url).fadeIn("fast")
				currController = "artists";
			}
			
			/*
			if(userSubPage == "play"){
				//trigger function play song kat sini.. base on the song id yg aku alert tu...
				//alert(songId)
				var autoPlay = 'true';
				var autoPlaySong = songId;
			}
			*/
		},
		
		getAccPage : function(url,page)
		{
			if(currController == "artists")
			{
				$("#content").fadeOut("slow", function(){
					$(this).empty().load("/accounts/artist/"+url).fadeIn("fast")
				})
			}else{
				$("#content").empty().load("/accounts/artist/"+url).fadeIn("fast")
				currController = "artists";
			}
		}
	},
	listener : {
		getPage : function(url)
		{
			if(currController == "listener")
			{
				$("#content").fadeOut("slow", function(){
					$(this).load("/listeners/index/"+url).fadeIn("fast")
				})
			}else{
				$("#content").empty().load("/listeners/index/"+url).fadeIn("fast")
				currController = "listener";
			}
			$("div#loadingIndicator").hide();
			
		},
		
		getAccPage : function(url,page)
		{
			if(currController == "listener")
			{
				$("#content").fadeOut("slow", function(){
					$(this).empty().load("/accounts/listener/"+url).fadeIn("fast")
				})
			}else{
				$("#content").empty().load("/accounts/listener/"+url).fadeIn("fast")
				currController = "listener";
			}
		}
	}
}


//Show the flashtooltip
function flashToolTip(){
	$("#flashtooltip").flash({   // test.swf is the flash document   
		swf: "http://"+document.domain+"/swf/flashtooltip.swf",
		width: '300',
		height: '140',
		wmode: 'transparent',
		name:'flashtooltip',
		id:'flashtooltip',
		params:{
			movie: "http://"+document.domain+"/swf/flashtooltip.swf"
			}
	})
}

//Show the Twitter
function loadTwitter(){
        $("#tweets").tweet({
            username: "cravecharts",
            join_text: "auto",
            count: 3,
            auto_join_text_default: "",
            auto_join_text_ed: "",
            auto_join_text_ing: "",
            auto_join_text_reply: "",
            auto_join_text_url: "",
            loading_text: "loading twitter..."
        });
    };


// Popup the registration form when user click the "Register" link
$('a#register, a.register').live("click",function(){
	$("a#register").fancybox({
		'showCloseButton' : false,
		'hideOnContentClick'	: false 
	});
	
	$('a#register').click()
	
	return false;
})

// Popup the login form when user click the "Login" link
$('a#login, a.login').live("click",function(){
	$('a#login').fancybox({
		'showCloseButton' : false,
		'hideOnContentClick'	: false 
	});
	
	$('a#login').click()
	
	return false;
})

// Popup the warning
$('a#warningLoginListener').live("click",function(){
	$('a#warningLoginListener').fancybox({
		'hideOnContentClick'	: false,
		'showCloseButton' : false,
		'hideOnOverlayClick' : false
	});
	
	$('a#warningLoginListener').click()
	
	return false;
})

// AJAX logout
$("a#logout").live("click", function(){
	$.ajax({
		type	: 	'POST',
		url		: 	'/users/logout',
		data	: 	'logout=yes',
		success	: 	function(data)
					{
						var userLink = 	"<a class='blueLink' id='login' href='/users/login'>Login</a>";
							userLink += " or ";
							userLink += "<a class='blueLink' id='register' href='/registers'>Register</a>";
						
						$('div.welcome_userMenu').fadeOut('fast', function(){
							$(this).html(userLink).fadeIn("fast", function(){
								var pathNames	=	$.address.pathNames()
    							navigate.route(pathNames)
							});
						})
					}
	})
	
	return false;
})

// <a class="defButton"></a> Style when mouseover and mouseout
$('a.defButton').live('mouseover', function(){
	$(this).parent().removeClass("borderDefButton_default").addClass("borderDefButton_hover")
})  
$('a.defButton').live('mouseout', function(){
	$(this).parent().removeClass("borderDefButton_hover").addClass("borderDefButton_default")
});


// <input class="defButton" type="button"></a> Style when mouseover and mouseout
$('input.defButton').live('mouseover', function(){
	$(this).parent().removeClass("borderDefSubmit_default").addClass("borderDefSubmit_hover")
})    
$('input.defButton').live('mouseout', function(){
	$(this).parent().removeClass("borderDefSubmit_hover").addClass("borderDefSubmit_default")
});

// <input class="defButton" type="button"></a> Style when mouseover and mouseout
$('input.defButtonFancyBox').live('mouseover', function(){
	$(this).parent().removeClass("borderDefButtonFancyBox_default").addClass("borderDefButtonFancyBox_hover")
})    
$('input.defButtonFancyBox').live('mouseout', function(){

	$(this).parent().removeClass("borderDefButtonFancyBox_hover").addClass("borderDefButtonFancyBox_default")
}); 