var playlist=null;
$().ready(function(){
	
	selectItem = 
	$("input.search_text").autocomplete(
		WWW+"ajax_manager.php",
		{
			delay:10,
			minChars:3,
			matchSubset:1,
			matchContains:1,
			cacheLength:15,
			onItemSelect:function(li){
					if( li == null ) return alert("No match!");
						$('#int_tag_id').val(( !!li.extra )?li.extra[0]:li.selectValue);
						$('#search_top').submit();
				},
				
			autoFill:false
		}
	);

	$('#search_top').submit(function(e){
		
		//window.location.replace(WWW+'search/latest-pakistani-songs/'+(this['qry'].value)+'.htm');
		//alert(WWW+"latest-pakistani-videos/tag/"+make_file_name($('#var_tag_title').val())+"/"+$('#int_tag_id').val()+"_0.htm");
		
		if($('#int_tag_id').val() =='')
			$('#int_tag_id').val(0);
			
		window.location.replace(WWW+"latest-pakistani-videos/tag/"+make_file_name($('#var_tag_title').val())+"/"+$('#int_tag_id').val()+"_1.htm");
		e.preventDefault();
		
	});
	
	youtube_id = $('#playlist>ul li:first')/*.addClass('selected')*/
										   .attr('id');
	playVideos('#player',youtube_id);
	
	$('#playlist a').click(function(e){
		str_link = $(this).attr('href');
		playVideos('#player',str_link.substring(1));
		e.preventDefault();
	});

	$(".dropdown").hover(function(){
		$("#submenu").show();
	},
	function(){
		$("#submenu").hide();
	}
	
	);

	$(".rate").each(function(){
	var opt = $(this).attr("id").split("_");
	$(this).rater(WWW+'ajax_manager.php', {type:opt[0],id:opt[1],curvalue:opt[2]});
		
	});
	
		$(".bookmark").click(function(){
			addBookmark(PAGE_TITLE,document.location);
		});
	
	$(".contact_us").click(function(e){
		var opt = $(this).attr("id").split("_");
			e.preventDefault();
			$.nyroModalManual({
				url: WWW+'contact_us.php'
			});
	});	
	
	$('.channel').click(function(e){
	
		$('.shows span').show();
		if($(this).attr('id')!='all')
			$('.shows span').not('.'+$(this).attr('id')).hide();
		e.preventDefault();
	});
	
	$(".share_page").click(function(e){
		$('#player-holder').hide();
		var opt = $(this).attr("id").split("_");
			e.preventDefault();
			$.nyroModalManual({
				/*height:350,
				width:700,*/
				url: WWW+'share_page.php',
				endRemove:function(){$('#player-holder').show();}
			});
	});	
	
	
	$(".post_comments").click(function(e){
		if($(this).hasClass('reply_comment'))
		{
			var opt = $(this).attr("id").split("_");
			var id = opt[2];
			$(".comments").data('reply','<span class="reply_info">Replying to <a href="#c'+id+'">'+$("#user_nme_"+id).text()+'</a></span>');
		}
		setTimeout("$(\"textarea[name='comments']\").focus()",500);
	});

	$(".comments").click(function(e){
		if(USER_ID==0)
		{
			checkLogin(e,$(this));	
			return false;
		}
		var obj_comments = $(this).parents("form").children("textarea[name='comments']");
		if($.trim(obj_comments.val()).length<5)
		{
			$.alert("Should have at least 5 characters");
			return false;
		}
		var opt = obj_comments.attr("id").split("_");
		str_reply_to = $(this).data("reply")?$(this).data("reply"):'';
		$.post(WWW+"comments.php", {"type": opt[0],"id": opt[1],"comment_txt":str_reply_to+obj_comments.val()  }, function(response){
			$(".no_comments").hide(); // if no comments hide them
			$(".comment_list").append(response);
			registerCommentRating();
			obj_comments.val("");
		});
		e.preventDefault();
	});
	
	$(".remove_comment").click(function(e){
	
		var opt = $(this).attr("id").split("_");
		$.post(WWW+"comments.php", {"type": opt[0],"comment_id": opt[2]}, function(response){
			$('#commentBox_'+opt[2]).hide();
			$('#commentBox_'+opt[2]).remove();
			$.alert(response);
		
		});
		e.preventDefault();
	
	});
	
registerPlaylist();
	
// end of document load
})

function registerPlaylist()
{
	int_parts = $('#playlist ul').children().length;
	if(int_parts>3)
	{
		playlist = $('#playlist');
		playlist.jScrollPane({animateTo:true});
	}else
	if(int_parts==1)
	$('#playlist').hide();
}

function playVideos(div_holder,video_id)
{
	type = $("#"+video_id).attr('type');
	if(type=='zshare')
		playZshareVideos(div_holder,video_id);
	else 
	if(type=='youtube')
		playYoutubeVideos(div_holder,video_id);	
	else
		playLocalVideos(div_holder,video_id);	
		
	$('#playlist>ul li.selected').removeClass();
		$('#'+video_id).addClass('selected');	
		
	if(playlist!=null)
		playlist[0].scrollTo('#'+video_id);	
}


function playYoutubeVideos(div_holder,video_id)
{
		var obj_holder = $(div_holder);
		obj_holder.html('<div id="player_holder">Loading...</div>');
		var params = { allowScriptAccess: "always",allowFullScreen:"true" };
		var atts = { id: "myytplayer" };
		var flashvarsObj ={autoplay:1,rel:0,fs:1,enablejsapi:1,autostart:"true"}
		/*
		if(obj_holder.attr('class'))
		{
			swfobject.embedSWF(WWW+"player/flvplayer.swf?file="+obj_holder.attr('class'), "player_holder", obj_holder.width(), obj_holder.height(), "8", null, flashvarsObj, params, atts);
		}
		
		$('#playlist>ul li.selected').removeClass();
		$('#'+video_id).addClass('selected');
		*/
	
		swfobject.embedSWF("http://www.youtube.com/v/"+video_id, "player_holder", obj_holder.width(), obj_holder.height(), "8", null, flashvarsObj, params, atts);

}


function playZshareVideos(div_holder,video_id)
{
		file_name = $("#"+video_id).attr('name');
		var obj_holder = $(div_holder);
		width = obj_holder.width();
		height = obj_holder.height();
		
		obj_holder.html('<div id="player_holder"><iframe style="margin-top:-42px;" src="'+file_name+'&iframewidth='+width+'&iframeheight='+(height+42)+'&width='+width+'&height='+height+'" height="'+(height+32)+'" width="'+width+'" border=0 frameborder=0 scrolling=no id="videoframe"  name="videoframe"></iframe></div>');
}

function playLocalVideos(div_holder,video_id)
{
		file_name = $("#"+video_id).attr('name');
		var obj_holder = $(div_holder);
		obj_holder.html('<div id="player_holder">Loading...</div>');
		var params = { allowScriptAccess: "always",allowFullScreen:"true" };
		var atts = { id: "myytplayer", name: "myytplayer"};
		var flashvarsObj ={autoplay:1,rel:0,fs:1,enablejsapi:1,autostart:"true",file:file_name}
		
		if(obj_holder.attr('class'))
		{
			swfobject.embedSWF(WWW+"player/flvplayer.swf?file="+obj_holder.attr('class'), "player_holder", obj_holder.width(), obj_holder.height(), "8", null, flashvarsObj, params, atts);
		}else swfobject.embedSWF(WWW+"player/player.swf", "player_holder", obj_holder.width(), obj_holder.height(), "8", null, flashvarsObj, params, atts);
}

var locat_player=null;
function playerReady(thePlayer) {

	locat_player = document.getElementById(thePlayer.id);
	addListeners();
}

function addListeners() {
	if (locat_player) { 
		locat_player.addModelListener("STATE", "stateListener");
	} else {
		setTimeout("addListeners()",100);
	}
}
function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	
	if(obj.newstate=='COMPLETED')
		moveNext();
}



function onYouTubePlayerReady(playerId) 
{
	ytplayer = document.getElementById("myytplayer");
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
	ytplayer.addEventListener("onError", "onPlayerError");
}

function onytplayerStateChange(newState)
{
	if(newState==0)
		moveNext();
}

function moveNext()
{
	nowPlaying = $('#playlist>ul li.selected');
	nextToPlay = nowPlaying.next();
	if(nextToPlay.length==0)
		nextToPlay = $('#playlist>ul li:first');
		
	/*nextToPlay.addClass('selected');
	nowPlaying.removeClass('selected');	
	*/
	playVideos('#player',nextToPlay.attr('id'));
}

	
function changePassword(e,source)
{
		$.nyroModalManual({
			height:300,
			width:500,
			url: WWW+'registration_modal.php#change_password'
		});
}	

function checkLogin(e,source)
{
	$('#player-holder').hide();
	e.preventDefault();
			$.nyroModalManual({
				height:300,
				width:800,
				url: WWW+'registration_modal.php#login',
			endRemove:function(){if(USER_ID!=0){source.click();doLogin();}$('#player-holder').show();}
			});
			
}
	
function openPlayer(str_type,int_id)
{
	var plyWin = window.open(WWW+"player/play.php?type="+str_type+"&id="+int_id,"temp","status=no,toolbar=no,location=no,height="+POP_HEIGHT+",width="+POP_WIDTH+",scrollbars=no,resizable=no");
	plyWin.focus();
}	

function playSelected()
{
	str_id="";
	$("#form_song_list input:checkbox[checked]").each(function(){
		str_id+=(str_id==""?$(this).val():","+$(this).val());
	});
	if(str_id=="")
	$.alert("You have not selected any things!");
	else
	openPlayer("song",str_id);

}

	jQuery.extend({
	
	alert:function(msg){
		if($("#player-holder").length>0)
		{
			alert(msg);
			return;
		}
			$.nyroModalManual({
				content: '<p class="alert">'+msg+'</p>'+
							'<a class="button small_o bc_white nyroModalClose" href=""><span>OK</span></a>',
				width: 440,
				autoSizable:true,
				closeButton:''
				
			});
		//setTimeout("$.nyroModalRemove();",5000);
	},
	promt:function(data){
			
				$.nyroModalManual({
				content: data,
				width: 440,
				autoSizable:true
			});
			
	}/*,
	msg:function(data){
			
				$.nyroModalManual({
				content: data,
				width: 440,
				autoSizable:true
			});
			
	}*/
	});
		
	function doLogin()
	{
		$(".header_login").html('Welcome '+USER_NAME+'!  <a href="'+WWW+'logout.php">Logout</a> - <a href="'+WWW+'my-profile.php">My Profile</a>')
	}
function addPlayList()
{
	return	'<div id="add_playlist_wrapper">'+
				'<h2>Add New Playlist</h2>'+
				'<form id="add_to_playlist" action="#" method="post" class="block">'+
					'<label for="cd_title_txt">Playlist Title: </label><input type="text" name="cd_title_txt" id="cd_title_txt" class="textbox shaded large" />'+
					'<label for=""cd_desc_txt"">Playlist Description:</label> <textarea name="cd_desc_txt" id="cd_desc_txt" class="textbox shaded large"></textarea>'+
					'<br /><br />'+
					'<button type="submit">	<span class="button orange bc_white"><em>Add Playlist!</em></span></button>'+
					/*'<input type="submit" value="Add Playlist" class="butt" />'+*/
				'</form>'+
			'</div>';
	
}


function selectPlayList(str_options)
{
	return	'<div id="add_playlist_wrapper">'+
				'<h2>Add to Playlist</h2>'+
				'<form id="add_playlist" action="'+WWW+'user_playlist.php" method="post" class="block">'+
					'<select id="user_cd_id_select" name="user_cd_id"><option value="-1">Select Playlist to add...</option>'+str_options+'</select>'+
					'<br /><br />OR<br /><br />'+
					'<a class="button small_g bc_white" href="#" id="create_new_playlist"><span>Create and Save in New Playlist</span></a>'+
				'</form>'+
			'</div>';
	
}


function registerCommentRating()
{
	$(".comment_rating").click(function(e){
	
		if(USER_ID==0)
		{
			checkLogin(e,$(this));	
			return false;
		}
		var opt = $(this).attr("id").split("_");
		$.post(WWW+"comments.php", {"type": opt[1],"id": opt[2],"int_rate":opt[3]}, function(response){
			$("#comment_rating_"+opt[2]).removeClass();
			if(response<0)
			{
				$("#comment_rating_"+opt[2]).addClass("red");				
			}else
			if(response>0)
			{
				$("#comment_rating_"+opt[2]).addClass("green");
				response = "+"+response;
			}
			$("#comment_rating_"+opt[2]).html(response);
		});
		e.preventDefault();	
	});
}
function addNewPlaylist()
{
	$.promt(addPlayList());
	$("#add_to_playlist").submit(function(e){
		if($.trim($("#cd_title_txt").val())=="")
		{
			$.alert('Please fill Playlist Name');
			e.preventDefault();
			return false;
		}
		$.post(WWW+'user_playlist.php',{"cd_title_txt":$("#cd_title_txt").val(),"cd_desc_txt":$("#cd_desc_txt").val(),"song_id":$().data('song_id')},function(res){
			$.alert(res);
		});
		e.preventDefault();
	});
}

function appendPlaylist(response)
{
	
	var obj_playlists = JSON.parse(response);
	var str_playlist = ''; 
	$.each(obj_playlists,function(ctr,item){
		str_playlist += '<option value="'+item.user_cd_id+'">'+item.cd_title_txt+'</option>'; 
	});
	// add new playlist link
	//str_playlist += '<option value="0" class="new_playlist">Create New Playlist</option>'; 
	
	$.promt(selectPlayList(response));
	
	$("#user_cd_id_select").append(str_playlist);
	$("#create_new_playlist").click(function(e){addNewPlaylist();e.preventDefault();});
	$("#user_cd_id_select").change(function(e){
	
				$.post(WWW+'user_playlist.php',{"playlist_id":$(this).val(),"song_id":$().data('song_id')},function(res){
					$.alert("Added to Playlist");
				});
		
		});// end of change
	
	
	//alert(response);
	
	/*response +=', <a href="#" class="add_new_play_link">Add to New Playlist</a>';
	$('.playlist').remove();
	$('#song_list_'+id).after('<div title="'+id+'" class="playlist">Add to Playlist: '+response+'</div>');
	$('.playlist a').click(function(){
		if($(this).hasClass("add_new_play_link"))
		addNewPlaylist();
		else
		{
			$.post(WWW+'user_playlist.php',{"playlist_id":$(this).attr('id'),"song_id":$('.playlist').attr('title')},function(res){	
			$.alert("Added to Playlist");
			});
		}
		e.preventDefault();
		
	});
*/	
	
}

/*
function appendPlayer(response)
{
	$('.inline_player').remove();
	$('#song_list_'+id).after('<div title="'+id+'" class="inline_player"></div>');
}
*/

function validatePlaylist()
{
	$("#add_playlist").validate(
	{
		rules: {
			cd_title_txt: {
				required: true,
				minlength: 5,
				remote: WWW+"manager.php?what=check_user_playlist"
			},
			cd_desc_txt: {
				required: false,
				minlength: 10,	
				maxlength: 150
			}
		},
		messages: {
			cd_title_txt: {
				required: "Enter the Playlist Title",
				minlength: jQuery.format("Enter at least {0} characters"),
				remote: jQuery.format("{0} is already in use")
			},
			cd_desc_txt: {
				maxlength: jQuery.format("Enter at most  {0} characters"),
				minlength: jQuery.format("Enter at least {0} characters")
			}
		}

	}
	);
}
function findPassword()
{
	$(".show_forgot").click(function(e){
		$("#frm_login").hide();
		$("#frm_forgot").show();
		e.preventDefault();
	});
	
	$(".show_login").click(function(e){
		$("#frm_forgot").hide();
		$("#frm_login").show();
		e.preventDefault();
	});
}


function addBookmark(title,url) 
{

	if (window.sidebar) 
	{
		window.sidebar.addPanel(title, url,"");
	} else if( document.all ) 
	{
		window.external.AddFavorite( url, title);
	} 
	else if( window.opera && window.print ) 
	{
		return true;
	}
}

function make_file_name(str_name)
{
	str_name=str_name.toLowerCase();
	str_name=str_name.replace(" ","-");
			
	//str_name.replace("/\-+/g","-");
	//alert(str_name);
	return str_name;//strtolower(preg_replace("/\-+/","-",preg_replace)));
}