function notify(head,text,callback)
{

/*	$.jGrowl(text, { 
		
		header: head,
		life: 50000,
		close: function(e,m,o) {
		
		
	},
		beforeClose: function(e,m,o) {
        
		if(callback) callback();
    		}
		
	}); */
	
	if(!window_focus)
	{
		var delay = function(){notify(head,text,callback);};
		
		setTimeout(delay,5000);
		document.title =" [Alerts]" +  window_title;
	}else
	{
	
	
		$.pnotify({
			pnotify_title: head,
			pnotify_text: text,
			pnotify_delay: 5000,
			pnotify_after_close: function(pnotify){
			if(callback) callback();
			}
	
		});
	}
	

}
function imgResizeHook()
{
	
	$(".embedImage").each(function(i,o){
		 
		if($(this).hasClass("resized"))
			return;
		//	 $(this).css("width", "auto").css("height", "auto"); // Remove existing CSS
		  //      $(this).removeAttr("width").removeAttr("height");
			 var w = $(this).width();
			 if(w > 0)
			 {
				 imgResize($(this), 500);
				 return;
			 }
			 
			 $(this).bind("click",function(event){
				// event.preventDefault();
				 window.open($(this).attr("src"));
			 });
			 $(this).load(function(){
			 	imgResize($(this), 500);
			 });
		 });
	//	 $(".embedImage").live("click",function(event){
			 
			 
			 
		// });
}
function imgResize(obj,max_size)
{

	 
	var w = obj.width();
	var h = obj.height();

	
	 if(w > max_size || h > max_size)
		{
	 if (w > h) {
	
	   h = h * max_size / w;
	   w = max_size;
	 } else {
	   w = w * max_size / h;
	   h = max_size;
	 }
		}
	 //document.images[name].width = w;
	 //document.images[name].height = h;
	obj.addClass("resized borderall border10");
	
	obj.attr("title","[Resized]");
	obj.css("height", h+"px");   // Set new height
	obj.css("width", w+"px");
	 
}
function replaceAll(txt, replace, with_this) {
	  return txt.replace(new RegExp(replace, 'g'),with_this);
	}
function getPHPSessionId() {
    var start=document.cookie.lastIndexOf('PHPSESSID=');
    var cookies=document.cookie.substr(start+10,document.cookie.length);
    var end=cookies.indexOf(';');
 
    if(end!=-1) {
    	return cookies.substr(0,end);
    }else {
    	return cookies;
    }
}
 
 function submitComment(txt)
 {
	 
	 
	 notify("Comment","Your comment is being posted...");
	 $("#divAddComment").slideUp();
	 
	 $.post("/muzik.ajax?action=postComment", { 
			action: "postComment", 
			song: songID, 
			comment: txt },function(data){
			
			
				$("#Comments").append(data);	
			
			
		},"html" );	
	 return false;
 }
 
 function share(type,id)
 {
	 if($( "#dialogEmbed" ).length > 0 ) // Don't reload if we already loaded it.
	 {

			$("#txtEmbedType").val(type);
			$("#txtEmbedID").val(id);
		 $( "#dialogEmbed" ).dialog("open");
		 return false;
	 }
	 
	 eJax("POST",'/embed.ajax',{action: "getForm",id: id,type: type },function(data){
			
			
			$("body").append(data);	
			 // init dialog box
		
			$( "#dialogEmbed" ).dialog({
				autoOpen: true,
				height: 300,
				width: 500,
				modal: true				
			});
			
			$("#txtEmbedType").val(type);
			$("#txtEmbedID").val(id);
			
			$("#dialogEmbed .js_embed_html").click(function(event){
				
				$("#dialogEmbed .divEmbed").hide();
				$("#dialogEmbed .embed_html").show();
								
			});
			$("#dialogEmbed .js_embed_fb").click(function(event){
				
				$("#dialogEmbed .divEmbed").hide();
				$("#dialogEmbed .embed_fb").show();
				var url = "/muzik.ebel";
				if($("#txtEmbedType").val() == "songs" )
				{
					url += "/detail/"+$("#txtEmbedID").val();
				}else
				if($("#txtEmbedType").val() == "playlist" )
				{
					url += "/playlist/"+$("#txtEmbedID").val();
				}
								
				facebookShare(url);
			});
			
			// Generate initial code.
			
			
			
			$("#txtEmbedHtml").val(shareEmbedRender());
			
			$("#txtEmbedHtml").click(function(event){
				
				$(this).focus();
				$(this).select();
				
			});
			
			$('#dialogEmbed .js_embed_Update').change(function(event){
			
				$("#txtEmbedHtml").val(shareEmbedRender());
				
			});
			
			
	});	
	 
	// window.open('/embed.ebel/'+type+"/"+id, 'newWindow', 'width=626, height=436'); return false;
	 
	 
 }
 function shareEmbedRender()
 {
	 var code = "";
	 var url = window.location.host;
	 var ext = url.split(".");
	 var autostart = 0;
	 if($("#chkEmbedAutoPlay").attr("checked"))
		 autostart = 1;
	 ext = ext[0];
		code = '<embed src="http://'+url+'/streamer_myspace.swf?AutoStart='+autostart;
		code += '&extension='+ext;
		if($("#txtEmbedType").val() == "songs" )
		{
			code += "&songs="+$("#txtEmbedID").val();
		}else
		if($("#txtEmbedType").val() == "playlist" )
		{
			code += "&playlist="+$("#txtEmbedID").val();
		}
		code +='" width="600" height="250" align="center" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed> ';
		
		return code;
 }
 function facebookShare(forceURL)
 { 
	 var url = window.location.href;
	if(forceURL)
		url = "http://"+window.location.host+ forceURL;
	 
	 window.open('http://www.facebook.com/sharer.php?u='+url, 'newWindow', 'width=626, height=436'); return false;
	 
 }
 
 
 
 function flashLogo()
 {
	 return;
	 var rgbString = $('#logo').css("color"); // get this in whatever way.
	// 	alert(rgbString);
	 if(rgbString.search("rgb") > -1)
	 {
	 var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
	 // parts now should be ["rgb(0, 70, 255", "0", "70", "255"]

	 delete (parts[0]);
	 for (var i = 1; i <= 3; ++i) {
	     parts[i] = parseInt(parts[i]).toString(16);
	     if (parts[i].length == 1) parts[i] = '0' + parts[i];
	 }
	 var hexString = parts.join('');
	 }
	 else
	 {
		 var hexString = rgbString;
	 }
	 if(hexString =="000000")
	 {
		 hexString="c0c0c0"; //securit�
	 }
	 
	 
	  $('#logo').empty().removeClass("logo").flash(
		        { src: '/flash/logo.swf',
		          width: 140,
		          height: 140,
		          flashvars: { newColor: '0x'+hexString },
		          wmode: 'transparent'},
		          {  update: false }
		          
		        
		    );
	 
 }
 
 
 function keepalive()
 {
	
	return;	 
		 eJax("GET","/myajax.ajax",{action:"keepalive"},function(){
			 //Only send the keepalive if all went well, and we finished.
			 setTimeout('keepalive()', 60000); 
			 
		 },"keepalive");

 }
 
 var ajaxLoader;
 var window_focus;
var window_title;
 

 $(document).ready(function(){
	
	 window_title = document.title;
	 
	 $(window).focus(function() {
	     window_focus = true;
	     document.title = window_title;
	 })
	     $(window).blur(function() {
	         window_focus = false;
	         
	     });
	 
	 //TODO: only send keepalive if we are logged in
	 setTimeout('keepalive()', 120000);  // KEEPALIVE
	 $("body").append('<div class="ajax_loader" style="display:none"></div>');
	 ajaxLoader = $("<div>").addClass("ajax_loader").hide();
	 $("body").append(ajaxLoader);
//	 $(ajaxLoader).hide();
//	var ajaxLoader = $('.ajax_loader');
	 $("body").mousemove(function(e){
	      $(ajaxLoader).css('top', e.pageY+10).css('left', e.pageX+10);
	    //  console.log(e.clientX);
	 });
	/* 	$(document).ajaxSend(function(r,s){  
			 $(ajaxLoader).show();
			// $("body").mousemove();
			
		 
		 });  
		   
		 $(document).ajaxStop(function(r,s){  
		 $(ajaxLoader).fadeOut("fast");  
		 //$("body").unbind('mousemove');
		 });  */
	 
//	 if(readCookie("css") == "black")
	//	 changeCSS();
	 var hideDelay = 500;  
	var currSettings="0";
	  var hideTimer = null;
	  var timer;
	 /* TOOLTIP */
	 var container = $('<div id="tooltip">'
		      + '<table width="" border="0" cellspacing="0" cellpadding="0" align="center" class="tooltipClass">'
		      + '<tr>'
		      + '   <td class="corner topLeft"></td>'
		      + '   <td class="top"></td>'
		      + '   <td class="corner topRight"></td>'
		      + '</tr>'
		      + '<tr>'
		      + '   <td class="left">&nbsp;</td>'
		      + '   <td><div id="tooltipContent"></div></td>'
		      + '   <td class="right">&nbsp;</td>'
		      + '</tr>'
		      + '<tr>'
		      + '   <td class="corner bottomLeft">&nbsp;</td>'
		      + '   <td class="bottom">&nbsp;</td>'
		      + '   <td class="corner bottomRight"></td>'
		      + '</tr>'
		      + '</table>'
		      + '</div>');

		  $('body').append(container);
		  $('.username').live('click', function(event)
				  {
			  event.preventDefault();
			  if(timer) {
                  clearTimeout(timer);
                  timer = null;
			  	}
			  var obj = $(this);
			  
			  timer = setTimeout(function() {
			  var settings = $(obj).attr('rel').split(';');
			  var portal = settings[0];
		      var userID = settings[1];
		      if(userID == 0)
				  return;
		      if (hideTimer)
		          clearTimeout(hideTimer);
		      
		      
		   //   alert(left);
		     //alert($(window).width() + " - " + left + " - " +$("#tooltip").width());
		      //left = Math.min(left,$(window).width()-$("#tooltip").width());
		     
		      if($(obj).attr('rel') != currSettings)
		      {
		    	  currSettings = $(obj).attr('rel');
		      $('#tooltipContent').html('nbsp;');
		    
		      eJax("POST", "/profile.ajax", {action:"getProfileBox",userid:userID,portal:portal}, function(data)
		          { 
		    	  var pos = $(obj).offset();
			      var width = $(obj).width();
			      var height= $(obj).height();
			      var top = (pos.top);

			      var left =  (pos.left + width);
			      if( (left+ $("#tooltip").width())  > $(window).width() )
			    	  left = pos.left - $("#tooltip").width();
			     //alert(top+ $("#tooltip").height());
			     //alert($(window).height());
			      if( (top+ $("#tooltip").height())  > ($(window).height()+$(window).scrollTop()) )
			    	  top = pos.top - $("#tooltip").height();
			      
			      $("#tooltip").css({
			          left: left+ 'px',
			          top: top + 'px'
			      });
			      $('#tooltipContent').html(data);
	             // $("#tooltip").css('display', 'block');
			      $("#tooltip").fadeIn("fast");
		    	  	
			    	  			     });
				      
		     
		      }
		      
			  },1);
				  });
		  $('.username').live('mouseout', function(event)  
				  {  
			  event.preventDefault();
			  		if(timer) 
			  		clearTimeout(timer);
				      if (hideTimer)  
				          clearTimeout(hideTimer);  
				      hideTimer = setTimeout(function()  
				      {  
				    	  $("#tooltip").css('display', 'none');  
				    	  currSettings=0;
				      }, hideDelay);  
				  });  
				  
				  // Allow mouse over of details without hiding details  
				  $('#tooltip').mouseover(function()  
				  {  
				      if (hideTimer)  
				          clearTimeout(hideTimer);  
				  });  
				  
				  // Hide after mouseout  
				  $('#tooltip').mouseout(function()  
				  {  
				      if (hideTimer)  
				          clearTimeout(hideTimer);  
				      hideTimer = setTimeout(function()  
				      {  
				          $("#tooltip").css('display', 'none');  
				          currSettings =  0;
				      }, hideDelay);  
				  });  
		  
	 
	 
	 $(".js_listen").live("click",function(event){
		 event.preventDefault();
		 var forcePlay = false;
		 if($(this).hasClass("js_listenPlay"))
			 	forcePlay = true;
		 playSong($(this).attr('rel'),forcePlay);
		 return false;
	 });
	 $(".js_playlist").live("click",function(event){
		 event.preventDefault();
		 playPlaylist($(this).attr('rel'));
		 return false;
	 });
	 
	 $(".js_embed").live("click",function(event){
		 
		 event.preventDefault();
		 arr = $(this).attr("rel").split(";");
		 share(arr[0],arr[1]);
		 
	 });
	 
	 
	 $(".js_toggle_div").live("click",function(event){
		 
		 event.preventDefault();
		 $("#"+$(this).attr("rel")).toggle();
		 
	 });
	 $(".js_slideToggle_div").live("click",function(event){
		 
		 event.preventDefault();
		 $("#"+$(this).attr("rel")).slideToggle();
		 
	 });
	 $(".js_toBottom").live("click",function(event){
		 
		 event.preventDefault();
		 $('body').animate({scrollTop: $("body").height()}, 800);
		 
	 });
	 $("#topnav li a").each(function(index) {
		 
		 if(window.location.toString().indexOf($(this).attr("href"))!=-1)
			 $(this).addClass('active');
	 });
	 
	 
	 function postPM(userID,portal,callback)
	 {
		  
		 eJax("POST","/profile.ajax",{ 
					action: "sendPM", 
					user: userID, 
					portal: portal,
					email: $("#txtMsgEmail").val(),
					title: $("#txtMsgTitle").val(),
					message: $("#txtMsgContent").val()
				},
				function(data)
				{
					
					if(callback)
						callback();
				});
		 
		 
	 }
	 
	 imgResizeHook();
	 
	 
	 $(".js_sendPM").live("click",function(event){
		 $("#tooltip").css('display', 'none'); 
		 // Ajax load the div for dialog box
		  var settings = $(this).attr('rel').split(';');
		  var portal = settings[0];
	      var userID = settings[1];
		 var obj=$(this);
		 $("#dialog-sendPM").remove();
		 eJax("POST","/profile.ajax",{action: "getDialogPM",user: userID,portal: portal },function(data){
				
				
					$("body").append(data);	
					 // init dialog box
					
					
					$( "#dialog-sendPM" ).dialog({
						autoOpen: true,
						height: 300,
						width: 350,
						modal: true,
						buttons: {
							"Send": function() {
						if($(obj).hasClass("js_captcha"))
						{
							captchaInit(function(){
								postPM(userID,portal,function(data){
									$( "#dialog-sendPM" ).remove();
									});
							});
							if(!captchaOK)
							{
								captchaValidate();
								return;
							}
						}
						else
							postPM(userID,portal,function(data){
								$( "#dialog-sendPM" ).remove();
								});
						
						
						
						$( this ).dialog( "close" );
						// LOADING .... 
							
							},
							Cancel: function() {
								$( this ).dialog( "close" );
							}
						},
						open: function() {
							
							$(this).parent().find('.ui-dialog-buttonpane button:last').addClass("delete");
							
						},
						close: function() {
							
						}
					});
					
					
					
					
			});	
		 
		 
		 
		
		 
	 });
	 
	 
	 
	 // Flash logo
	 
	//flashLogo();
		  
		
		    // End Flash Logo
 });
 
 // Open the song player and execute the play function.
 var newwindow = '';
 function playSong(id,forceplay)
 {
	 win = window.open('','flash_player_','location=yes,status=no,scrollbars=0,height=560,width=604');
	var wurl = ''+win.location; 
	if(wurl.indexOf('player') == -1)
 	{
		win.location ='/player.ebel#p='+id+"&c="+id;
 	//
 	}
	else
		win.enqueue(id,forceplay);
		
	win.focus();
 //self.location='/stay_online.php';
 return false;
	
	
	 
 }
 function playPlaylist(id)
 {
	 win = window.open('','flash_player_','location=yes,status=no,scrollbars=0,height=560,width=604');
	var wurl = ''+win.location; 
	if(wurl.indexOf('player') == -1)
 	{
		win.location ='/player.ebel#pl='+id;
		win.enqueuePlaylist(id);
 	//
 	}
	else
		win.enqueuePlaylist(id);
	win.focus();
 //self.location='/stay_online.php';
 return false;
	
	
	 
 }
 function parseURL()
	{
		var q =  window.location.hash.toString();
		
		q = q.substring(1, q.length);
		var myarray = q.split('&');
		var query = new Object();
		for (var i = 0; i < myarray.length; i++)
		{
			var a = myarray[i].split('=');
			var key = a[0];
			var val = a[1];
			if(key.length > 0)
				query[key] = val;
			
		}
	
	return query;	
	}
 function updateURL(q,update)
 {
	 var oldQ = q;
 	if(update)	
 	{
 	oldQ = parseURL();
 	for( var i in q )
 		{
 		//alert(i+" - " +oldQ[i]);
 		
 			oldQ[i] = q[i];
 		
 		}
 	}
 	var s = "";
 	for( var i in oldQ )
 		{
 		
 		s+= i + "=" + oldQ[i]+"&";
 			
 		
 		}
 	window.location.hash = s;
 	
 	



 }
function changeCSS()
{
	//$("link").attr("href",$(this).attr('rel'));
	//createCookie("css","black");
	$('link').each(function(index) {
//	    alert(index + ': ' + $(this).attr("href"));
	    
	    var t = $(this).attr("href");
	    
	    t = t.replace("blue-v3","black-web2");
	    $(this).attr("href",t);
	    
	  });
	
	setTimeout( 'flashLogo();', 5000);
	
	  
	
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
		
}


// EBEL AJAX COMMON FUNCTIONS
var pendingRequests = new Object();

function eJax(method,action,data,callback,name){
	if(name != "keepalive")
		$(ajaxLoader).show();
	
	if(name) // Name is set, we cancel pending ajax queries
	{
		var req = pendingRequests[name];
		if(req)
		{
		//s	console.log(req);
			try
			  {
				req.abort();
			  }
			catch(err)
			  {
			  //notify("ERROR",err);
			  }
			
			
		}
		
		
	}
	var req = $.ajax({
		   type: method,
		   url: action,
		   data: data,
		   dataType: "json",
		   timeout: 15000,
		   error:function (xhr, ajaxOptions, thrownError){
		       // alert(xhr.status);
		     //   notify(xhr.status,thrownError);
		        $(ajaxLoader).fadeOut();
			},
		   success: function(msg) {
				
				$(ajaxLoader).fadeOut();
				
				if(msg.status == 0)
				{
					notify("ERROR",msg.content);
				}
		   	 if(msg.notify)
		   	 {
		   		 notify("Notification",msg.notify);
		   		 
		   	 }
		   	 if(msg.popup)
		   	 {
		   		 notify("Popup",msg.popup);
		   		 
		   	 }
		   	if(msg.reload)
		   	 {
		   			location.reload(true);
		   		 
		   	 }
			if(msg.status == 1 && callback)
				callback(msg.content);
		   		
			pendingRequests[name]= null;
				}
		 });
	
	if(name) // Name is set, we save this request
	{
		pendingRequests[name]= req;
		
		
		
	}
}



