//JavaScript Document
//Copy Right CyberDesign (C) 2011
//Create 08-09-2011
var d = new Date(),
	boxWidth = 238,
	perPage = 4,
	coutContent = 4,
	maxWidth = boxWidth*coutContent-(boxWidth*perPage),
    marginLeft = 0,
    tb = "",
    str = "";
	
	Y = d.getFullYear();
	m = d.getMonth();
	f = d.getDate();
	
	//alert(Y);
	//alert(new Date(Y, 1-1, m) )
$(function(){
	var navDuration = 600; 
	var navDurationMobile = 600; 
	var navDownHeight = "310px";
	var isMobile = detach_mobile_browser();
	//alert(isMobile)
	//regis_dialog();
	
	/*$(".datepicker").datepicker({
		minDate: new Date(Y, m, f)
	});*/
	$(".close-task").live("click",function(){
		$(location).attr('href','/admin');
	})
	//Handle addnew for current task
	$(".add-new").live("click",function(l){
		var task = $(this).attr("ref");
		switch(task){
			case "slide" :
				$(location).attr('href','/admin/mediaform');
				break;
			case "course" :
				$(location).attr('href','/admin/course');
				break;
			case "newsletter" :
					$("#dialog").dialog({
						height: 700,
						width: 1050,
						modal: true
					}); 
				break;
			case "activities" :
				$(location).attr('href','/admin/activitiesform');
				break;
			case "instructor" :
				$(location).attr('href','/admin/instructorform');
				break;
				
		}
	})
	$(".save-task").live("click",function(l){
		var task = $(this).attr("ref");
		switch(task){
			case "saveslide" :
					var data = $("#mediaForm").serialize();
					$.ajax({
						url: "/admin/saveslide",
						type: "post",
						data:data,
						success: function(data){
							$(location).attr('href','/admin/media');
						}
					
					
					});
				break;
			case "course" :
				break;
			case "editslide":
				var data = $("#mediaForm").serialize();
				$.ajax({
					url: "/admin/seditmedia",
					type: "post",
					data:data,
					success: function(data){						
							$(location).attr('href','/admin/media');
					}
				
				
				});
				break;
			case "activities" :
				var subject    = $("#txt-subject").val(),
				    details    = $("#txt-details").val(),
				    cover	   = $("#txt-cover").val()!=""?$("#txt-cover").val().split("/"):$(".image_cover:checked").val().split("/"),
				    show       = $("#text-show:checked").val()?$("#text-show:checked").val():'n',
				    id		   = $("#txt-id").val(),
				    hightlight = $("#txt-hightlight:checked").val()?$("#txt-hightlight:checked").val():'N';
				    
				    //alert(cover[cover.length-1])				    
				    $.ajax({
					url: "/admin/saveactivities",
					type: "post",
					data:{
						"txt-subject":subject,
						"txt-cover":cover[cover.length-1],
						"txt-details":details,
						"text-show":show,
						"text-hightlight":hightlight,
						"txt-id":id
					},
					success: function(data){
						if(data)
						{
							$(location).attr('href','/admin/activities');
						}
					}				
				
				});
				break;
			case "instructor" :
				var teacherName	= $("#txt-name").val(),
				 	teacherDept	= $("#txt-department").val(),
				 	teacherPos	= $("#txt-positions").val().replace(/\n/gi,"<br/>"),
				 	teacherEdu	= $("#txt-educations").val().replace(/\n/gi,"<br/>"),
				 	teacherExp	= $("#txt-experiens").val().replace(/\n/gi,"<br/>"),
				 	teacherGrp	= $("#txt-group").val(),
				 	teacherPhoto= ($("#txt-file").length>0)?$("#txt-file").val():$("#txt-photo-id").val(),
					isshow		= $("#txt-show:checked").val(),
					id			= $("#txt-id").val();
				//alert($("#txt-educations").val().replace(/\n/gi,'<br>'));
				$.ajax({
					url: "/admin/saveinstructor",
					type: "post",
					data:{
						"txt-name":teacherName,
						"txt-department":teacherDept,
						"txt-positions":teacherPos,
						"txt-educations":teacherEdu,
						"txt-experiens":teacherExp,
						"txt-group":teacherGrp,
						"txt-photo":teacherPhoto,
						"txt-show":isshow,
						"txt-id":id
					},
					success: function(data){
						$(location).attr('href','/admin/instructors');
					}
				});				
				break;
			case "youtube" :
				var data = $("#upload_form").serialize();
				$.ajax({
					url : '/youtube/ytmanage',
					type: 'post',
					data: data,
					success: function(data){
						alert(data);				
					}
				})
					
				break;
			
				
		}
	})
	$(".upload-task").live("click",function(){
		uploadVideo();
	})
	$(".reload-task").live("click",function(){
		feedVideo();
	})
	$("a.manage").live("click",function(){
		var id  = $(this).attr("ref"),
		    act = $(this).attr("act");
		switch(act){
			case "edit" :
				 $(location).attr('href','/admin/editmedia/id/'+id+'/');
				break;
				break;
			case "delete" :
				$.post("/admin/deleteslide",{id:id},function(data){
					$(location).attr('href','/admin/media')
				})
				break;
		}
	})
	$("a.ins-manage").live("click",function(){
		var id	= $(this).attr("ref"),		
			act = $(this).attr("act")
		
		switch(act){
			case "edit" :
				 $(location).attr('href','/admin/instructorform/id/'+id+'/');
				break;
				break;
			case "delete" :
				$.post("/admin/deleteinstructor",{id:id},function(data){
					alert(data);
					$(location).attr('href','/admin/instructors')
				})
				break;
		}
	})
	
	$(".text_logout, .btnLogout").live("click",function(){
		if($("#confirm_dialog").length) $("#confirm_dialog").remove();
		$("<div/>").attr({id:"confirm_dialog"})
		.html("ยืนยันการออกจากระบบ?").css({
			"font-size":"23px",
			"padding": "25px 0 0 0px",
			"text-align":"center"
		})
		.appendTo("body");
		$("#confirm_dialog").dialog({
			height: 200,
			width: 300,
			modal: true,
			buttons: {
				"ยืนยัน": function() {
					$(location).attr("href","/auth/logout")	
				},
				"ยกเลิก": function(){
					$("#confirm_dialog").dialog('close');
				}
			},
			zIndex:9999
		});
		$(".ui-dialog-titlebar").remove();
		$(".ui-dialog").css({background:"#FFF","-moz-opacity":1, filter:"alpha(opacity=100)", opacity:1});
	});
	$("#text_search").focus(function(){ var str = $(this).val(); str = str=="SEARCH"?"":str; $(this).val(str) });
	$("#text_search").blur(function(){ var str = $(this).val(); str = str==""?"SEARCH":str; $(this).val(str) });
	$('#btnlogin').live("click",function(){
		var username = $('#username').val(),
			password = $('#password').val(),
			flag = $('#login_flag').val(),
			url = flag=='admin'?'/admin':'/member';
			//alert(url+'-->'+flag)
		$("#login_form").submit();
		/*$.post("/auth/login",{'username':username,'password':password},function(data){
			//alert('xxx');
			//alert(data);

			$(location).attr('href',data);
		})*/
	})
	$("#username").live("keydown",function(event){
		var key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if(key==13){
				$("#password").focus();
		}		
	})
	$("#password").live("keydown",function(event){
		var key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if(key==13){
			var username = $("#username").val(),
				password = $(this).val();
			if(username=="" || password==""){
				alert('กรุณากรอกข้อมูลการเข้าสู่ระบบให้ครบถ้วน');
				$("#password").focus();
			}else{
				$("#btnlogin").click();
			}
				
		}		
	})
	$("#link_register_course").live("click",function(){
			var course = $(this).attr('ref');
			if( window.confirm("ยืนยันการลงทะเบียน "+course )){
		//		alert('xx')
			};
			$(location).attr('href','/course/confirm?id='+cid)
			//alert(cid)
			$.get("/course/confirm",{ 'id':cid },function(data){
				//alert(data);
				$(location).attr('href','/course/confirm')
			})
			
	})
	//Page Contents
	if(isMobile){
		//alert(isMobile)
		$("#template_contents li ul")
		.animate({ height : '0px',"-moz-opacity":0, filter:"alpha(opacity=0)", opacity:0}, navDurationMobile)
		.bind("click",
			function(){
				if( $(this).attr("visible")!="1" || !$(this).attr("visible") ){
					$(this).parent().find('span').css({background:'transparent url(/images/arrow.png)  no-repeat 0 -20px'});
					$(this).stop(true,true).animate({height:'120px',"-moz-opacity":1, filter:"alpha(opacity=100)", opacity:1},navDurationMobile).attr("visible","1");
					
				}else{
					$(this).stop(true,true).animate({height:'0px',"-moz-opacity":0, filter:"alpha(opacity=0)", opacity:0},navDurationMobile).attr("visible","");
				}
			}
		)		
				
		//Pages Menu Up To Group	
		$('li.tab_anchor ul.tab_menu')
		.bind("click",			
				function() {
					if( $(this).attr("visible")!="1" || !$(this).attr("visible") ){
						$(this).parent().find('span').css({background:'transparent url(/images/arrow_white_all.png)  no-repeat 0 -21px'});
						$(this).stop(true,true).animate({ "-moz-opacity":1, filter:"alpha(opacity=100)", opacity:1 }, navDurationMobile).attr("visible","1");            
					}else{
						$(this).stop(true,true).animate({ "-moz-opacity":0, filter:"alpha(opacity=0)", opacity:0 }, navDuration).attr("visible","");;
					}
				}
		);
		
	}else{
		$("#template_contents li ul")
		.animate({ height : '150px',"-moz-opacity":0, filter:"alpha(opacity=0)", opacity:0}, navDuration)
		.hover(
				function(){
					$(this).parent().find('span').css({background:'transparent url(/images/arrow.png)  no-repeat 0 -20px'});
					if(jQuery.support.opacity){
						$(this).stop(true,true).animate({height:'180px',"-moz-opacity":1, filter:"alpha(opacity=100)", opacity:1},navDuration);
					}else{
						$(this).stop(true,true).animate({height:'180px',"-moz-opacity":1, filter:"alpha(opacity=100)", opacity:1},navDuration)
					}
					
				},
				function(){ 
					$(this).parent().find('span').css({background:'transparent url(/images/arrow.png) no-repeat'});
					if(jQuery.support.opacity){
						$(this).stop(true,true).animate({height:'180px',"-moz-opacity":0, filter:"alpha(opacity=0)", opacity:0},navDuration);
					}else{
						$(this).stop(true,true).animate({height:'180px',"-moz-opacity":0, filter:"alpha(opacity=0)", opacity:0},navDuration)
					}
				}
		);
		
		//Pages Menu Up To Group	
		$('li.tab_anchor ul.tab_menu')
		.animate({ height : '310px',"-moz-opacity":0, filter:"alpha(opacity=0)", opacity:0}, navDuration)
		.hover(
				function() {
						$(this).parent().find('span').css({background:'transparent url(/images/arrow_white_all.png)  no-repeat 0 -21px'});
						$(this).stop(true,true).animate({ "-moz-opacity":1, filter:"alpha(opacity=100)", opacity:1 }, navDuration);            
				}, 
				function() {
						$(this).parent().find('span').css({background:'transparent url(/images/arrow_white_all.png) no-repeat'});
						$(this).stop(true,true).animate({ "-moz-opacity":0, filter:"alpha(opacity=0)", opacity:0 }, navDuration);
				}
		);
	}
	$("ul.tab_menu li a").click(
		function(){
			$(this).next().not("p").animate({height:70},navDuration);
		}
	)
	//loging Dialog
	$(".text_login").click(function(){
		login_dialog();
		$("#login_dialog").dialog({
			modal: true,
			closeText: 'hide',
			resizable: false,
			closeOnEscape: true,
			width: 350,
			height:300,
			title: 'เข้าสู่ระบบ',
			zIndex:9999
		});
		$(".ui-dialog-titlebar").remove();
	})
	
	$(".image_cover").live("click",function(){
		clearChecked('image_cover');
		$(this).attr("checked","checked");
	})
	/*$("a.register").live("click",function(){
		//regis_dialog();
		$("#login_dialog").dialog('close');
		$("#register_containner").dialog( "destroy" ).dialog({
			modal: true,
			closeText: 'hide',
			resizable: false,
			closeOnEscape: true,
			width: 860,
			height:900,
			title: 'ลงทะเบียน',
			zIndex:9999
		});
		$(".ui-dialog-titlebar").remove();
	})*/
	
	$(".close_dialog").live("click",function(){ var dialog_id = $(this).parents().parents().attr("id"); $("#"+dialog_id).dialog('close'); })
	
	function clearChecked(eleclass)
	{
		$ele_class = $("."+eleclass);
		$ele_class.each(function(){ $(this).removeAttr("checked") })
	}
	function login_dialog(){
		if($("#login_dialog").length) $("#login_dialog").remove();
		var login_dialog = $("<div/>").attr({ id:"login_dialog"}),
			login_dialog_contain = $("<div/>").attr({ id:"login_dialog_contain"}),
			login_form = $("<form/>").attr({id:'login_form',method:'post',action:'/auth/login'}),			
			login_dialog_footer = $("<div/>").attr({ id:"login_dialog_footer"});
			login_dialog_contain.append(login_form);
			login_form.append('<dl><dt>*Username</dt><dd><input type="hidden" id="login_flag" value="user"/><input type="text" id="username" name="username" /></dd><dt>*Password</dt><dd><input type="password" id="password" name="password" /></dd></dl>');
			login_dialog_footer.append('<div class="btn"><div class="btnlogin"><a href="#" id="btnlogin">LOGIN</a></div></div><div class="link"><a href="/regis/form" class="register">ลงทะเบียน</a>|<a href="/regis/forget">ลืมรหัสผ่าน</a></div>');
			login_dialog.append('<div id="login_dialog_top"><a class="close_dialog" href="#"><div></div></a></div>',login_dialog_contain,login_dialog_footer).appendTo("body");		
		
	}
	function regis_dialog(){	
		if($("#register_containner").length) $("#register_containner").remove();
		$.get("/regis/form",function(data){ 
			var register_containner = $("<div/>").attr({ id:"register_containner" }).append(data).appendTo("body")
		});
		
	}
	function detach_mobile_browser(){
		var result;
		if( navigator.userAgent.match(/Android/i) ||
		 navigator.userAgent.match(/webOS/i) ||
		 navigator.userAgent.match(/iPhone/i) ||
		 navigator.userAgent.match(/iPod/i)||
		 navigator.userAgent.match(/iPad/i)
		 ){
		 	result = navigator.userAgent;
		}
		return result;

	}
	$("input[name=news-group-radio]").live("change",function(){
		var opt_news = $(this).val();
		if(opt_news==2){
			$(".sub_register_contain").slideDown(300);
		}else{
			$(".sub_register_contain").slideUp(300);
		}
	})
	$("input[name=newsedu]").live("change",function(){
		if( $(this).is(":checked") ){
			$(".course-check").each(function(){ $(this).not(":checked").click() });
		}else{
			$(".course-check:checked").each(function(){ $(this).click() });
		}
	})	
	$(".course-check").live("click",function(){
		$("input[name=newsedu]").not(":checked").click();
	})
	$("#link-next").live("click",function(){
		if(marginLeft<maxWidth){
			marginLeft = marginLeft+boxWidth;
			$(".content_box").animate({left:-marginLeft},500)
		}
	});
	$("#link-prev").live("click",function(){
		if(marginLeft>0){
			marginLeft = marginLeft-boxWidth;		
			$(".content_box").animate({left:-marginLeft},500);
		}
	});
	$(".content_box").live("mouseover",function(){ 
		if(coutContent>perPage){
			$("#link-prev, #link-next").fadeIn(500);
		}
	})
	.live("mouseleave",function(){ 
		if(coutContent>perPage){
			$("#link-prev, #link-next").fadeOut(500);
		}
	})
	
	/*Media form*/
	$("#radio01").focus().attr("checked",true);
	//38 up 40 down
	$("#image-listbox li").live("keydown",function(e){ 
			var key = e.which;		
			if(key==38){
					clearFocus();				
					$(this).prev().addClass("active");				 
			}else if(key==40){
					clearFocus();
					$(this).next().addClass("active")
			}else if(key==13){
				  alert( $(this).text());
			}		
	}).live("click",function(){
			clearFocus();
			$(this).addClass("active").find("input").attr("checked",true).focus() ;
			//alert( $(this).text());
	})
	$("#image-listbox li div").live("click",function(){  //When click promotion
			$(this).addClass("active").find("input").attr("checked",true).focus() ;
	})
	function clearFocus(){
			$("#image-listbox li").each(function(){  $(this).removeClass("active") });
	}
	function feedVideo()
	{		
		    tb = $(".tb-youtube-feed");
		    str = "<li class=\"w50\">No.</li>"+
			  	  "<li class=\"w250\">Video</li>"+
			      "<li class=\"w350\">Title</li>"+
			      "<li class=\"w400\">Keyword</li>"+
			      "<li class=\"w100\">Category</li>";
		
		$.getJSON("/youtube/setvsource",function(data){
			$.each(data,function(i,val){				
				$.each(val.data,function(n,txt){
					str+= "   <li class=\"w50\">"+(n+1)+"</li>"+
						  "   <li class=\"w250\">"+txt.File+"</li>"+
						  "   <li class=\"w350\">"+txt.Title+"</li>"+
						  "   <li class=\"w400\">"+txt.Keyword+"</li>"+
					      "   <li class=\"w100\">"+txt.Category+"</li>";
					 
				})
			})
			$(".tb-youtube-feed").html(str);
		})
	}
	function uploadVideo()
	{		
		$.ajax({
			url :"/youtube/ytupload",
			type: "post",
			dataType: "json",
			data:{},			
			success :function(data){
				//alert(data)
				tb = $(".tb-youtube-feed");
			    str = "<li class=\"w50\">No.</li>"+
				  	  "<li class=\"w250\">Video</li>"+
				      "<li class=\"w350\">Title</li>"+
				      "<li class=\"w400\">Link</li>"+
				      "<li class=\"w100\">Category</li>"+
			    	  "<li>Keyword</li>";
				
				$.each(data,function(i,val){
					//alert(val.error);
					$.each(val.data,function(n,txt){						 
						str+= "   <li class=\"w50\">"+(n+1)+"</li>"+
							  "   <li class=\"w250\">"+txt.video+"</li>"+
							  "   <li class=\"w350\">"+txt.title+"</li>"+
							  "   <li class=\"w400\">http://www.youtube.com/watch?v="+txt.video+"</li>"+
							  "   <li class=\"w100\">"+txt.category+"</li>"+	
						  	  "   <li>"+txt.tags+"</li>";
					})
				})
				
				$(".tb-youtube-feed").html(str);
				
			}
		});
	}
	
})

