// jQuery based javascript 

$(document).ready(function(){
	$.ajaxSetup({cache:false}); 
	
	if($('#docSearch').length)
	{
		$('#docSearch').watermark('Dokumentum keresése...');
		$('#docSearch').bind('keyup',function(){
			$('#loader').show();
			$.get('/ajax/doc_search/'+$('#docSearch').attr('rel')+'/'+$('#docSearch').val(),function(v){
				$('#doc-list').html(v);
				$('#loader').hide();
			});
		});
	}
	
	if ($('#CompilationIdSelect').length)
	{
		$('#CompilationIdSelect').bind('change',function(){
			if($(this).find('option:selected').attr('rel') == 1)
			{
				if(confirm('Ez egy zárt tanfolyam. Kívánja ezt a videót is csak ebből a tanfolyamból elérhetővé tenni?'))
				{
					$('#video-closed').fadeIn('slow');
					$('#video-closed').find('b').text($(this).find('option:selected').text());
					$('#video-closed-input').val('1');
				}
			}
			else
			{
				$('#video-closed:visible').hide();
				$('#video-closed-input').val('');
			}
		});
	}

	if ($('#lessonCompilationIdSelect').length)
	{
		$('#lessonCompilationIdSelect').bind('change',function(){
			if($(this).find('option:selected').attr('rel') == 1)
			{
				if(confirm('Ez egy zárt tanfolyam. Kívánja ezt a tanórát is csak ebből a tanfolyamból elérhetővé tenni?'))
				{
					$('#lesson-closed').fadeIn('slow');
					$('#lesson-closed').find('b').text($(this).find('option:selected').text());
					$('#lesson-closed-input').val('1');
				}
			}
			else
			{
				$('#lesson-closed:visible').hide();
				$('#lesson-closed-input').val('');
			}
		});
	}

	
	if ($('#category-list').length){
		$('.cat-item').bind('mouseover',function(){$(this).addClass('shadow').children('span').show();});
		$('.cat-item').bind('mouseout',function(){$(this).removeClass('shadow').children('span').hide();});
		$('.cat-item').bind('click',function(){$(document).attr('location').href = $(this).find('a').attr('href');});
	}
	
	if ($('#head-menu').length)
		chkNotifications();
	
	if ($('#logo').length)
		$('#logo').click(function(){document.location.href = '/';});
	
	if ($('#tz-selector').length)
		$('#tz-selector').bind('change',function(){
			document.location.href='?tz='+$('#tz-selector').val();
		});
	
	if ($('#Alllogin').length){
		$('#login_email').watermark('E-mail address');
		$('#login_passwd').watermark('Password');
		$('#Alllogin').bind('click',function(){
			$('#LoginLayer').css('top',Math.round(($(window).height()-250)/2));
			$('#LoginLayer').css('left',Math.round(($(window).width()-500)/2));
			$('#LoginLayer').show();
		});
		$('#closeLogin').bind('click',function(){
			$('#LoginLayer').hide();			
		});
	}
	if ($('input[type="submit"]').length)
		$('input[type="submit"]').bind('click',function(){
			$.blockUI({ css: { 
	            border: 'none', 
	            padding: '15px', 
	            backgroundColor: '#000', 
	            '-webkit-border-radius': '10px', 
	            '-moz-border-radius': '10px', 
	            opacity: .5, 
	            color: '#fff' 
	        } }); 
		});
	
	if ($('#error').length){
			$('#error').hide();
	        $.blockUI({ 
	            theme:     true, 
	            title:    'Error', 
	            message:  $('#error').html(), 
	            timeout:   4000
	        }); 
	}
	
	if ($('.nodelete').length)
		$('.nodelete').bind('click',function(e){
			 $.blockUI({ 
		            message: $(this).attr('msg'), 
		            fadeIn: 700, 
		            fadeOut: 700, 
		            timeout: 2500, 
		            showOverlay: false, 
		            centerY: false, 
		            css: { 
		                width: '350px',
		                border: 'none', 
		                padding: '5px', 
		                backgroundColor: '#000', 
		                '-webkit-border-radius': '10px', 
		                '-moz-border-radius': '10px', 
		                opacity: .6, 
		                color: '#fff',
		                'font-size': '16px',
		                'font-weight': 'bold'
		            } 
		        });  
		});
	
	if ($('#video-new-upload').length)
		$('#video-new-upload').bind('click',function(){document.location.href = '/video/upload';});
	
	if ($('#video-new-record').length)
		$('#video-new-record').bind('click',function(){document.location.href = '/video/record';});
	
	if ($('#lesson-new').length)
		$('#lesson-new').bind('click',function(){document.location.href = '/lesson/new';});

	if ($('#datepicker').length)
	{
		$("#datepicker").watermark('mm/dd/yyyy');
		$("#datepicker").datepicker();
	}
	if ($('#timepicker').length){
		$("#timepicker").watermark('hh:mm');
		$("#timepicker").timepicker();
	}
	
	if ($('#video-mainpage').length)
		$.get('/ajax/video-mainpage',function(v){$('#video-mainpage').html(v);});

	if ($('#logout').length)
		$('#logout').bind('click',function(){$.get('/logout',function(){})});
	
	if ($('#compilation').length)
	{
		$('#compilation').hide();
		
		$('#addCompilation, #editCompilation').bind('click',function(){
			$('#compilation').html('<p align="center"><img src="/images/load.gif" border="0" /> Loading...</p>');
			
			var cId = $('#CompilationIdSelect').val() ? $('#CompilationIdSelect').length : $(this).attr('cmp');
			
			var url = '';
			if ($(this).attr('id') == 'addCompilation')
				url = '/compilation/new/0?type='+$(this).attr('type');
			
			if ($(this).attr('id') == 'editCompilation')
				url = '/compilation/edit/'+$(this).attr('cmp')+'/'+cId+'?type='+$(this).attr('type');
			if ($(this).attr('id') == 'editCompilation' && cId == 0) return;
			
			$('#compilation').load(url,function(){
				$('#compilation').slideDown('slow');

				$('#cancelCompilation').live('click',function(){
					$('#compilation').slideUp('slow',function(){
						$('#compilation').text('');
						$('#cancelCompilation').die('click');
					});
				});
				$('#saveCompilation').live('click',function(){
					if(    $('input[name="compilation[name]"]').val() == ''
						|| $('input[name="compilation[description]"]').val() == ''
						|| $('input[name="compilation[price]"]').val() == ''
					)
						alert('Összes mező kitöltése kötelező!');
					else
						$('#compilationForm').submit();
				});
			});
		});
	
	}
	
	if ($('.makeQuiz, #makeQuiz').length)
	{
		$('#makeQuiz, .makeQuiz').bind('click',function(){
			if ($('#quizBox').html() != ''){
				$('#quizBox').slideUp('slow',function(){$('#quizBox').html('')});
			}
			$('#quizBox').html('Quiz loading...');
			var ref = $(this).attr('ref') ? $(this).attr('ref') : 0;
			var cmp = $(this).attr('cmp') ? $(this).attr('cmp') : 0;
			$('#quizBox').load('/test/new/'+ref+'/'+cmp,function(){
				$('#quizBox').slideDown('slow');
				if ($('a[rel="1"]').length){
					$('a[rel="1"]').bind('click',function(){
						var next = parseInt($('table[ans="1"] tr:last').attr('rel')) + 1;
						$('table[ans="1"]').append('<tr style="display:none" rel="'+next+'"><td style="font-weight:normal;"><span>'+next+'</span>. '+quizLang.answer+'</td><td align="right"><input type="text" style="width:390px"  name="question[1][answer]['+next+']" /></td><td align="center"><input type="radio" value="'+next+'" name="question[1][correct]" /></td><td align="center"><img src="/images/delAnswer.png" border="0" class="del-answer" rel="1:'+next+'" /></td></tr>');
						$('tr[rel="'+next+'"]').fadeIn('slow');
					});
				}
				
				if ($('input[q="1"]').length){
					$('input[q="1"]').bind('click',function(){
						var next = parseInt($('#questions tr[q*=""]:last').attr('q')) + 1;
						$('#questions').append('<tr valign="top" q="'+next+'"><td class="first" style="border-bottom:solid 2px #fff" ><b>'+next+'. '+quizLang.question+'</b></td><td align="left"  style="border-bottom:solid 2px #fff"><input type="text" name="question['+next+'][text]" value="" style="width:545px;" /><br /><table cellpadding="3" cellspacing="0" border="0" ans="'+next+'" style="width:550px;"><tr><td style="font-weight:normal;">&nbsp;</td><td align="right">&nbsp;</td><td style="font-weight:normal;">'+quizLang.correct+'</td><td style="font-weight:normal;">'+quizLang.deleted+'</td></tr><tr rel="1"><td style="font-weight:normal;"><span>1</span>. '+quizLang.answer+'</td><td align="right"><input type="text" style="width:390px" name="question['+next+'][answer][1]" /></td><td align="center"><input type="radio" value="1" name="question['+next+'][correct]" checked="checked" /></td><td align="center"><img src="/images/delAnswer.png" border="0" class="del-answer" rel="'+next+':1"  /></td></tr><tr rel="2"><td style="font-weight:normal;"><span>2</span>. '+quizLang.answer+'</td><td align="right"><input type="text" style="width:390px" name="question['+next+'][answer][2]" /></td><td align="center"><input type="radio" value="2" name="question['+next+'][correct]" /></td><td align="center"><img src="/images/delAnswer.png" border="0" class="del-answer" rel="'+next+':2" /></td></tr></table><a rel="'+next+'" href="javascript:void(0);" style="font-weight:normal" ><img src="/images/addAnswer.png" border="0" /> '+quizLang.add_a_answer+'</a></td></tr>');
						$('tr[q="'+next+'"]').fadeIn('slow');
						$('a[rel="'+next+'"]').bind('click',function(){
							var next2 = parseInt($('table[ans="'+next+'"] tr:last').attr('rel')) + 1;
							$('table[ans="'+next+'"]').append('<tr style="display:none" rel="'+next2+'"><td style="font-weight:normal;"><span>'+next2+'</span>. '+quizLang.answer+'</td><td align="right"><input type="text" style="width:390px"  name="question['+next+'][answer]['+next2+']" /></td><td align="center"><input type="radio" value="'+next2+'" name="question['+next+'][correct]" /></td><td align="center"><img src="/images/delAnswer.png" border="0" class="del-answer" rel="'+next+':'+next2+'" /></tr>');
							$('tr[rel="'+next2+'"]').fadeIn('slow');
						});
					});
				}
				
				if ( test )
				{
					$.each(eval(test),function(i,q){
						j = i + 1; 
						if (i>0) $('input[q="1"]').click();
						$('input:text[name="question['+j+'][text]"]').val(q.text);
						$.each(q.answer,function(k,a){
							if (k>1) $('a[rel="'+j+'"]').click();
							$('input:text[name="question['+j+'][answer]['+(k+1)+']"]').val(a.answer);
							if (q.correct == (k+1))
								$('input:radio[name="question['+j+'][correct]"]:eq('+k+')').attr('checked','checked');
						});
					});
				}
			});
		});
	}

	if ($('#fill-the-quiz').length)
	{
		$('#fill-the-quiz').bind('click',function(){
			var rel = $(this).attr('rel') ? $(this).attr('rel') : 0;
			var cmp = $(this).attr('cmp') ? $(this).attr('cmp') : 0;

			$.fx.speeds._default = 1000;
			$('#quiz-dialog').dialog({
				draggable: false,
				height: 300,
				width: 540,
				resizable: false,
				modal: true,
				show: "blind",
				hide: "explode",
				stack: false,
				close: function() {
					$('input:radio[name="correct"]').die('click');
					$('#next-question').die('click');
					$('#CloseQuiz').die('click');
					$('#quiz-dialog').dialog( "destroy" );
					var current = 0;
					var ok_answer = 0;
					var nok_answer = 0;
				}
			});
			$('#CloseQuiz').live('click',function(){$('#quiz-dialog').dialog( "close" )});
			$('.ui-dialog-titlebar').css('display','none');
			$('.ui-widget-content').css('background','url(/images/dialog_bg.png) repeat-x top #bdccd0');
			$('#quiz-dialog').html('<p align="center">Loading...</p>');
			$('#quiz-dialog').load('/ajax/quiz-fill/'+rel+'/'+cmp);
			
		});
	}	
	
	if ($('#yuotubeURLsend').length)
		$('#yuotubeURLsend').bind('click',function(){
			$.get(
				'/ajax/youtube/set',
				{"id": $(this).attr('rel'), "url": $('#youtubeURLhidden').val()},
				function(ret){$('#youtube-ret').text((ret ? 'elküldve' : 'hibás link'));}
			);
		});
	
	if ($('#youtubeBox').length)
		setTimeout("chkYoutube("+$('#youtubeBox').attr('rel')+")",5000);
	
	if ($('#lessonType').length){
		$('#lessonType').bind('change',function(){
			if ($('#lessonType').val() == 1 && $('.group:hidden').length) $('.group').show();
			else if ($('.group:visible').length) $('.group').hide();
		});
		
	}
	
	
	// Youtube ajax search
	$("#youtubeURL").keyup(function()
	{
		var search_input = $(this).val();
		if (search_input != '')
		{
			var keyword= encodeURIComponent(search_input);
			// Youtube API 
			var yt_url='http://gdata.youtube.com/feeds/api/videos?q='+keyword+'&format=5&max-results=1&v=2&alt=jsonc';
	
			$.ajax({
				type: "GET",
				url: yt_url,
				dataType:"jsonp",
				success: function(response){
					if(response.data.items)
					{
						$.each(response.data.items, function(i,data)
						{
							var video_id=data.id;
							var video_title=data.title;
							var video_viewCount=data.viewCount;
							// IFRAME Embed for YouTube
							var video_frame="<iframe width='320' height='182' src='http://www.youtube.com/embed/"+video_id+"' frameborder='0' type='text/html'></iframe>";
							var final="<div id='title'>"+video_title+"</div><div>"+video_frame+"</div><input type='hidden' id='youtubeURLhidden' value='http://www.youtube.com/watch?v="+video_id+"'>";
							$("#youtube-ret").html(final); // Result
	
						});
					}
					else
					{
						$("#youtube-ret").html("<div id='no'>No Video</div>");
					}
				}
			});
		}
		else
			$("#youtube-ret").html("");
	});	
	
});
$('.del-answer').live('click',function(){
	var v = $(this).attr('rel').split(':');
	var w = $('input:radio[name="question['+v[0]+'][correct]"]:checked').val();
	$('table[ans="'+v[0]+'"] tr[rel="'+v[1]+'"]').fadeOut('slow',function(){
		$('table[ans="'+v[0]+'"] tr[rel="'+v[1]+'"]').remove();
		$.each($('table[ans="'+v[0]+'"] tr'),function(i,l)
		{
			if ($(l).attr('rel') && parseInt($(l).attr('rel')) != i)
			{
				$(l).attr('rel',i);
				$(l).find('span').animate({opacity: 0}, 200, function() {
					$(l).find('span').html(i);
					$(l).find('span').animate({opacity: 1}, 200, function() {});
				});
			}
		});
		if (w == v[1])
			$('input:radio[name="question['+v[0]+'][correct]"]:eq(0)').attr('checked','checked');
	});
})

function chkYoutube(id)
{
	$.get(
		'/ajax/youtube/get',
		{"id":id},
		function(v){
			if (v)
			{
				$('#youtubeBox').html('<object width="400" height="250"><param name="movie" value="http://www.youtube.com/v/'+v+'?fs=1&amp;hl=hu_HU&amp;rel=0&amp;color1=0x3a3a3a&amp;color2=0x999999"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+v+'?fs=1&amp;hl=hu_HU&amp;rel=0&amp;color1=0x3a3a3a&amp;color2=0x999999" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="400" height="250"></embed></object></br><a href="javascript:void(0);" id="getNextYoutube">get next video</a>');
				$('#getNextYoutube').live('click',function(){
					$('#youtubeBox').html('');
					setTimeout("chkYoutube("+$('#youtubeBox').attr('rel')+")",5000);
				});
			}
			else
				setTimeout("chkYoutube("+id+")",5000);
		}
	);
}

function chkPrivateStatus(id)
{
	$.ajax({
		type: "GET",
		url: '/live/chkPrivateStatus/'+id,
		success: function(msg){
			if (msg == 1){
				$.ajax({
					method: 'get',
					url: '/live/'+id+'/inner',
					success: function(msg) {
						$('#chat_wait').html(msg);
					}
				});
			} else {
				$('#chkCounter').html(parseInt($('#chkCounter').html()) + 1);
				setTimeout("chkPrivateStatus("+id+")",5000);
			}
		}
	});//
}

function getToken(id)
{
	if ($('#course-closed:checked').length){
		$('#url_id').fadeOut('slow');
		$('#token').html('http://www.theliveteacher.com/<img src="/images/loadingDotDot.gif" border="0" />');
		$.ajax({
			type: "GET",
			url: '/ajax/getToken/'+id,
			success: function(msg){
				$('#token').html('http://www.theliveteacher.com/<b>'+msg+'</b>');
				$('#hiddenToken').val(msg);
			}
		});
	}
	else{
		$('#token').html('');
		$('#hiddenToken').val('');
		$('#url_id').fadeIn();
	}
}

function chkNotifications(i,l){
	
	$.ajax({
		type: "GET",
		url: '/ajax/chkNotifications/',
		success: function(msg){
			eval(msg);
			if (notes.inbox > 0){
				if($('.m-inbox').length){
					if (i && i < notes.inbox){
						$('.m-inbox').html(notes.inbox);
						$('.m-inbox').css({
							'background'	: '#F03D25',
							'color'			: '#fff'
						});
					}
				}
				else
					$('#menu-Inbox').append(' <span class="menu_counter m-inbox">'+notes.inbox+'</span> &nbsp;');
			}
			if (notes.lesson > 0){
				if($('.m-lesson').length){
					if (l && l < notes.lesson){
						$('.m-lesson').html(notes.lesson);
						$('.m-lesson').css({
							'background'	: '#F03D25',
							'color'			: '#fff'
						});
					}
				}
				else
					$('#menu-Lesson').append(' <span class="menu_counter m-lesson">'+notes.lesson+'</span> &nbsp;');
			}
			setTimeout("chkNotifications("+notes.inbox+","+notes.lesson+")",30000);
		}
	});
}

function setDocPublic(id,pub)
{
	document.location.href = '/documents/public?id='+id+'&p='+pub;
}
function deleteDocument(id)
{
	if (confirm('Do you really want to delete this document?'))
		document.location.href = '/documents/delete?id='+id;
}
function delPrevDoc(id)
{
	if (confirm('Do you really want to delete this document preview?'))
		document.location.href = '/documents/deletePrev?id='+id;
}
function SetDocLink(docId,type,linkId)
{
	$('#di_'+docId).html('<img src="/images/load.gif" />');
	$.ajax({
		type: "GET",
		url: '/documents/link/'+type+'/'+docId+'/'+linkId,
		success: function(msg){
			if (msg == 1){
				$('#di_'+docId).html('<img src="/images/ok.png" />');
			}
			else if (msg == 2){
				$('#di_'+docId).html('');
			}
			else {
				$('#di_'+docId).html('<img src="/images/nok.png" />');
				//TODO: Hibaüzenet megjelenítése
			}
		}
	});//	
}
/* Ajax Chat*/
function AjaxChat(sid){
	$.ajax({
		type: "POST",
		data: "ajaxchat_text="+$('#ajaxchat_text').val(),
		url:'/ajaxchat/'+sid,
		success: function(ret) {
			/*$('chatlist').adopt(new Element('li', {text: 'nextelement'}));*/
			if ($('#chatlist').html().trim() != ret.trim()){
				$('#chatlist').html(ret);
				$('#chatTextBox').scrollTop = $('#chatTextBox').scrollHeight;
			}
			$('#ajaxchat_text').focus();
		}
	});
	$('#ajaxchat_text').val('');
}

function AjaxChatSave(sid){
	document.location.href = '/ajaxchat/'+sid+'/save';
}

function AjaxChatRefresh(sid){
	function count(){
		var ul = document.getElementById('chatlist');
		var i=0, c =0;
		while(ul.getElementsByTagName('li')[i++]) c++;
		return c;
	}
	$.ajax({
		type: "POST",
		url:'/ajaxchat/'+sid+'/'+count(),
		success: function(ret) {
			if ($('#chatlist').html().trim() != ret.trim()){
				$('#chatlist').html($('#chatlist').html() + ret);
				if (ret) $('#chatTextBox').scrollTop = $('#chatTextBox').scrollHeight;
			}
			setTimeout("AjaxChatRefresh('"+sid+"')",3000);
		}
	});
}

function chatSubmit(myfield,e,sid) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;
	if (keycode == 13) {
		AjaxChat(sid);
	   return false;
	}
	else return true;
}


