var rss_timer;
	
$(document).ready(function(){

/*-----------------JS for event list-------------------------*/
    // $("#event_list").tabs();

//AUTO Hyperlink form all class richeditor
	function autolink(s){   
		var hlink = /\s(ht|f)t(p|ps):\/\/([^ \,\;\:\!\)\(\"\'\<\>\f\n\r\t\v])+/g;
		return (s.replace (hlink, function ($0,$1,$2){
				s = $0.substring(1,$0.length);
		// remove trailing dots, if any
		while (s.length>0 && s.charAt(s.length-1)=='.')
			s=s.substring(0,s.length-1);
			// add hlink
			if(s.match(window.location.host)){
				var auto = s.link(s);
			}else{
				auto = '<a href="'+s+'" target="_blank">'+s+'</a>';
			}
			 return " " + auto;
			 }) 
		);
	}
	$('.richeditor').each(function(){
		$(this).html(autolink($(this).html()));
	});
//end AUTO Hyperlink form all class richeditor

/*
|--------------------------------------------------------------------------
|JS for index
|--------------------------------------------------------------------------
*/
/*	$("#sub-pane1").scrollable({size: 1,clickable: false }).navigator({
		navi: "#sub-tap1",
		naviItem: 'a',
		activeClass: 'current'
	});
	
	$("#sub-pane2").scrollable({size: 1,clickable: false }).navigator({
		navi: "#sub-tap2",
		naviItem: 'a',
		activeClass: 'current'
	});	
*/
	if($('#tab_2_block.short-course').length>0)$('#tab_2_block.short-course').load(site_url+'main/ajax_short_course');
	$("div.quicklinks").scrollable({prev:".qleft",next:".qright",size: 2,clickable: false,circular: true}); 

	$("#tab1-lv3").minitabs();
        $("#tab1-lv3").css('background-color','rgb(255, 255, 255)');


	$("#tab1-lv3").each(function(){
		$('#tab1-lv3 a').mouseover(function(){
			div_id = $(this).attr('href');
			content_height = $('div#'+div_id+' div ul').height();
			container_height = $('#tab1-lv3').height();
			div_index = div_id.substring(div_id.lastIndexOf('-')+1,div_id.length)
			if(content_height > container_height){
				$('#slider'+div_index).css('display','block');
//				document.getElementById('slider'+div_index).style.display = 'block';
			}else{
				$('#slider'+div_index).css("display","none");
			}
		})
        listlen=$('#tab1-lv3 .cat-list a').length;
//        var randomnumber=Math.floor(Math.random()*listlen)
//        $('#tab1-lv3 .cat-list a:eq('+randomnumber+')').trigger('mouseover');
	});
    
    



/**************  BILLY COMMENT THIS
	$('.subject-list-scroll').css({
		'position':'relative',
		'overflow':'hidden',
		'height':'275px'
	});
	$('.sub_list_btn').css('float','right');
	$('.subject-list-scroll').scrollable({
		prev:'.list_up',
		next:'.list_down',
		vertical:true,
		size: 3
	});
*/
/*-----------------------End JS for index---------------------------------*/
	$('#button_search').click(function(){
		$('#form_site_search').submit();
	});
        $('#site_search').focus(function () {
            var $this = $(this);
            if ($this.val()==$this.attr('title')) $this.val('');
        });
        $('#site_search').blur(function () {
            var $this = $(this);
            if ($this.val()==''){
		    $this.val($this.attr('title'));
		    $this.css('background','#fff');
	    }
        });

	var init_dialog = false;
	var font_cookies_expire_days = 365;
	var default_font_size = "75%";
	var max_font_size = 105;
	var min_font_size = 60;
	var factor = 5;
	var date_array = new Array(2);
	var total_select_block = 1;

	$('.level1 > li').addClass('item');
	
	$("#font_larger").click(function(){
		var current_font_size;
		var font_size_number;
		var adjusted_font_size;
		
		if ($.cookie("font")) {
			current_font_size = $.cookie("font");
		}else {
			current_font_size = $("body").css("fontSize");
		}
		
		font_size_number = current_font_size.replace("%","");
		
		if (font_size_number < max_font_size) {
			adjusted_font_size = (parseInt(font_size_number) + factor)+'%';
			$.cookie("font", adjusted_font_size, { path: '/', expires: font_cookies_expire_days });
			$("body").css("fontSize", adjusted_font_size);
		}
	});
	
	$("#font_smaller").click(function(){
		var current_font_size;
		var font_size_number;
		var adjusted_font_size;

		if ($.cookie("font")) {
			current_font_size = $.cookie("font");
		}else {
			current_font_size = $("body").css("fontSize");
		}
		
		font_size_number = current_font_size.replace("%","");
		
		if (font_size_number > min_font_size) {
			adjusted_font_size = (parseInt(font_size_number) - factor)+'%';
			$.cookie("font", adjusted_font_size, { path: '/', expires: font_cookies_expire_days });
			$("body").css("fontSize", adjusted_font_size);
		}
	});
	
	$("#font_normal").click(function(){
		$.cookie("font", default_font_size, { path: '/', expires: font_cookies_expire_days });
		$("body").css("fontSize", default_font_size);
	});
	
	$("#left_menu ul.level2 li").hover(	
		function() { show_submenu($(this)); },
		function() { hide_submenu($(this)); }
    );
	
	$("#left_menu ul.level3 li").hover(	
		function() { show_submenu($(this).parent(0).prev()); },
		function() { hide_submenu($(this).parent(0).prev()); }
    );
	
	function show_submenu(item){
		var submenu = item.find(".left_submenu");
		var atag = item.find("a:first-child");
		var position = atag.position();
		
		if (is_ie6())
			submenu.css("top", (position.top - 2) + "px");
		else
			submenu.css("top", position.top + "px");
	
		submenu.show();
	}
	
	function hide_submenu(item){
		var submenu = item.find(".left_submenu");
		submenu.hide();
	}
	
//	function show_sharing() {
//		//$('.sharing span.prev,.sharing span.next,.sharing p,.sharing div img,.sharing div .name a,.programme_sharing .student .name a').click(function() {
//		$('.sharing span.prev,.sharing span.next,.sharing .student .name a').click(function() {
//			var div=$(this).parents('.sharing').eq(0);
//			$('#tab_sharing_block').load(site_url + 'share/' + 'ajax_get_sharing', {data:div.attr('id')}, function(data) {
//				show_sharing();
//			});
//		});
//
//		$('.sharing .photo img,.programme_sharing .student .name a').click(function() {
//			var div=$(this).parents('.sharing').eq(0);
//			$('#tab_sharing_block').load(site_url + 'share/' + 'ajax_get_sharing', {data:div.attr('id')}, function(data) {
//				show_sharing();
//				$("div#tabs a#tab_sharing").click();
//			});
//		});
//        
//		$('.sharing span.prev,.sharing span.next,.sharing .student a').click(function() {
//			var div=$(this).parents('.sharing').eq(0);
//			$('#tab_sharing_block').load(site_url + 'share/' + 'ajax_get_sharing', {data:div.attr('id')}, function(data) {
//				show_sharing();
//			});
//		});
//	}
	//show_sharing();

	function show_sharingV2(){
		if(! $.fn.fancybox) {
			$("head").append("<link>")
			css = $("head").children(":last");
			css.attr({
				rel:  "stylesheet",
				type: "text/css",
				href: "/assets/css/jquery.fancybox-1.3.1.css"
			});
			$.getScript("/assets/js/jquery.fancybox-1.3.1.pack.js");
		}
		$('ul.sharing_type:not(.sharing_index) a').live('click', function(){
			var adata = $(this).attr('data');
			$('#tab_sharing_block').load(site_url + 'share/ajax_index', {data:adata});
			$('div#tabs a#tab_sharing').click();
			return false;
		});
		$('#tab_sharing_block li.detail_list div.back_to_previous a').live('click',function(){
			hash = window.location.hash.split('_');
			window.location.hash = hash[0];	
		})
		$('.sharing span.prev,.sharing span.next,.sharing .student .name a').live('click', function(){
			var div=$(this).parents('.sharing').eq(0);
			$('#tab_sharing_block').load(site_url + 'share/ajax_get_detail', {data:div.attr('id')},
				function() {
					$(".photo_gallery_thumbnail a").fancybox({ 'titlePosition': 'inside', 'autoScale' : false,  'centerOnScroll' :false });
				});
			hash = window.location.hash.split('#');
			if(hash.length > 1){	
				parm = hash[1].split('_');
				window.location.hash = '#'+parm[0]+'_'+div.attr('id').replace(/\|/g,'&');	  
			}
			$('div#tabs a#tab_sharing').click();
		});
		
		$('.newspaper .newspaper_title a').live('click', function(){
			var div=$(this).parents('.newspaper').eq(0);
			$('#tab_sharing_block').load(site_url + 'share/ajax_get_detail', {data:div.attr('id')},
				function() {
					$(".photo_gallery_thumbnail a").fancybox({ 'titlePosition': 'inside', 'autoScale' : false,  'centerOnScroll' :false });
				});
			hash = window.location.hash.split('#');
			if(hash.length > 1){
				parm = hash[1].split('_');
				window.location.hash = '#'+parm[0]+'_'+div.attr('id').replace(/\|/g,'&');
			}

			$('div#tabs a#tab_sharing').click();
		});

		$('.sharing .photo img,.programme_sharing .student .name a').live('click', function(){
			var div=$(this).parents('.sharing').eq(0);
			$('#tab_sharing_block').load(site_url + 'share/ajax_get_detail', {data:div.attr('id')},
				function() {
					$(".photo_gallery_thumbnail a").fancybox({ 'titlePosition': 'inside', 'autoScale' : false,  'centerOnScroll' :false });
				});
			hash = window.location.hash.split('#');
			if(hash.length > 1){
				parm = hash[1].split('_');
				window.location.hash = '#'+parm[0]+'_'+div.attr('id').replace(/\|/g,'&');
			}

			$('div#tabs a#tab_sharing').click();
		});

		$('.sharing span.prev,.sharing span.next,.sharing .student a').live('click', function(){
			var div=$(this).parents('.sharing').eq(0);
			$('#tab_sharing_block').load(site_url + 'share/ajax_get_detail', {data:div.attr('id')},
				function() {
					$(".photo_gallery_thumbnail a").fancybox({ 'titlePosition': 'inside', 'autoScale' : false,  'centerOnScroll' :false });
				});
			hash  = window.location.hash.split('#');
			if(hash.length > 1)
			{
				parm = hash[1].split('_');
				window.location.hash = '#'+parm[0]+'_'+div.attr('id').replace(/\|/g,'&');
			}
			$('div#tabs a#tab_sharing').click();
		});
		$("div.sharing_ajax div.sort_block ul.options li a").live('click', function(){
			var adata = $(this).attr('data');
			$('#tab_sharing_block').load(site_url + 'share/ajax_index', {data:adata});
			$('div#tabs a#tab_sharing').click();
			return false;
		});
	}

	show_sharingV2();

        
	var sharingtypeshow = 0;
	$('ul.sharing_type li').each(function(){
		if($(this).css('display') !='none') 
			sharingtypeshow++;	
	});
	var sharingcount = 0;
        var sharingtimeout = null;

	sharing_move_init();
	
	function sharing_move_init()
	{
		var totalitem =  $('ul.sharing_type li').length;
		if(totalitem > 0)
		{
			var activeItem = -1;
			$('ul.sharing_type li').each(function(index){
				if($(this).find('a').hasClass('active'))
				{
					activeItem = index;
				}
			});
			var index = 0;
			if(activeItem != -1 && activeItem!=0)
			{
				index = parseInt(activeItem/sharingtypeshow);
			}
			for(i = 0; i < index ; i++)
			{
				sharing_move_left(0);
			}
		}
	}

        function sharing_move_left(time){
                var currentpos = -1;
                var totalcount = 0;
                $('ul.sharing_type li').each(function(index){
                        if($(this).is(':visible')){
                                if(currentpos == -1) currentpos = index;
                        }
		        totalcount++;
                });
                if(totalcount - currentpos > sharingtypeshow){
		        $('ul.sharing_type li').eq(currentpos).hide(time);
                        $('ul.sharing_type li').eq(currentpos+sharingtypeshow).show(time);
                        if(sharingcount+1 < sharingtypeshow){
                                sharingtimeout = setTimeout(sharing_move_left, time);
                                sharingcount++;
                        }
			if($('div.sharing_right').is(':invisible')) $('div.sharing_right').removeClass('sharing_move_disabled');
                        if(currentpos+sharingtypeshow==totalcount-1){
                                $('div.sharing_left').addClass('sharing_move_disabled');
                        }
                }
        }

        function sharing_move_right(time){
                var currentpos = -1;
                var totalcount = 0;
                $('ul.sharing_type li').each(function(index){
                        if($(this).is(':visible')){
                                if(currentpos == -1) currentpos = index-1;
                        }
                        totalcount++;
                });
                
                if(currentpos >= 0 && sharingtypeshow + currentpos < totalcount){
                        $('ul.sharing_type li').eq(currentpos+sharingtypeshow).hide(time);
                        $('ul.sharing_type li').eq(currentpos).show(time);
                        if(sharingcount+1 < sharingtypeshow){
                                sharingtimeout = setTimeout(sharing_move_right, 500);
                                sharingcount++;
                        }
                        if($('div.sharing_left').is(':invisible')) $('div.sharing_left').removeClass('sharing_move_disabled');
                        if(currentpos == 0){
                                $('div.sharing_right').addClass('sharing_move_disabled');
                        }
                }
        }
        
        $('div.sharing_left').live('click',function(){
                sharingcount = 0;
                clearTimeout(sharingtimeout);
                sharing_move_left(500);
        });
                
        $('div.sharing_right').live('click',function(){
                sharingcount = 0;
                clearTimeout(sharingtimeout);
                sharing_move_right(500);
	});
        
        $("#left_menu ul.level1 li a.item").click(
                function() {
                        expand_sublevel($(this).parent(0));
                }
    );

	
	
	$("#left_menu ul.level1 li a.item").click(	
		function() { 
			expand_sublevel($(this).parent(0)); 
		}
    );
	
	function expand_sublevel(item){
		
		var level2_ul;
		var expandible = false;
		
		if (item.next().is("ul")){
			if (item.next().attr("class") == "level2") {
				level2_ul = item.next();
				expandible = true;
			}
		}else{
			//ie7
			level2_ul = item.find("ul.level2");
			expandible = true;
		}

		if (expandible) {
			if (!level2_ul.is(':visible')) {
				$("#left_menu ul.level2").hide();
				
				var active_level1_li = $("#left_menu ul.level1 li.active").find("a.item");
				$(active_level1_li).parent(0).removeClass("active");
				 
				item.addClass("active");
				level2_ul.show();
			}
			else {
				level2_ul.hide();
				item.removeClass("active");
			}
		}
		
	}
	
	function collapse_sublevel(item){
		if (item.next().attr("class") == "level2") {
			item.next().hide();
		}		
	}

	$("span.staff_detail,span.staff_detail_cht,span.staff_detail_eng").click(function(){
		var my_site_url;
		if ($(this).hasClass('staff_detail_eng') && lang != 'eng')
			my_site_url = site_url.replace('cht/', '/');
		else if ($(this).hasClass('staff_detail_cht') && lang != 'cht')
			my_site_url = site_url + 'cht/';
		else
			my_site_url = site_url;
		var staff_name = $(this).html();
		$.getJSON(my_site_url+'college/json_get_staff_profile', {name:staff_name}, function (data) {
			$('#staff_eng_name').html(data.name);
			$('#staff_chi_name').html(data.name_cht);
			$('#staff_title').html(data.title);
			$('#staff_email > a').html(data.email).attr('href','mailto:'+data.email);
			if(data.email == '')
				$('#staff_email').hide();
			else
				$('#staff_email').show();
			$('#staff_telephone > a').html(data.phone);
			if(data.phone == '')
				$('#staff_telephone').hide();
			else
				$('#staff_telephone').show();
//			$('#staff_website > a').html(data.website).attr('href', data.website);
			if(data.website == '')
				$('#staff_website').hide();
			else
				$('#staff_website').show();
			if (data.photo) {
				$('#staff_photo').attr('src', base_url+'file/staff/'+data.id+'/'+data.photo+'?w=100&h=120&crop=1').show();
			} else {
				$('#staff_photo').hide();
			}
			if ($.trim(data.background) == '' || $.trim(data.background) == '<br />') {
				$('#staff_background_info').parents('li').eq(0).hide();
			}
			else {
				$('#staff_background_info').html(data.background);
				$('#staff_background_info').parents('li').eq(0).show();
			}
			if (!init_dialog){
				$("#dialog_staff_detail").dialog({
					bgiframe: true,
					width: 563,
					resizable: false,
					modal: true
				});
				init_dialog = true;
				$(".ui-widget-header").ifixpng();
				$(".dialog_bottom").ifixpng();
				$(".dialog_body").ifixpng();	
				$("span.ui-icon").ifixpng();	
			}else{
				// reset the background for body again
				$(".dialog_body").css('background','url("/assets/images/dialog_body.png") repeat scroll 0 0 transparent');
				$("#dialog_staff_detail").dialog('open');
				$(".dialog_body").ifixpng();	

			}	

                        if (data.programme_count == 0) {
                                $('#staff_related_prog').parents('li').eq(0).hide();
                                $('#college_staff_related_prog').parents('li').eq(0).hide();
                        }
                        else {
				related_prog_html = "";
				college_related_prog_html = "";
				for(i=0;i<data.programme_count;i++){
					related_prog_html = related_prog_html + "<div class='related'><a href='" + site_url + "prog/" + data.list[i]['url'][0] + "'>" + data.list[i]['name_'+lang][0] + "</a></div>";
					college_related_prog_html = college_related_prog_html + "<div class='related'><a href='" + site_url + "prog/" + data.list[i]['url'][0] + "'>" + data.list[i]['name_'+lang][0] + "</a></div>";
				}
        		        $('#staff_related_prog').html(related_prog_html);
        		        $('#college_staff_related_prog').html(college_related_prog_html);
                                $('#staff_related_prog').parents('li').eq(0).show();
                }
				
		$('#staff_qualification').html(data.qualification);
		});
	});
	
	
    function show_tab_content(){
        // var vars = [], hash;  
        // var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('#');
        /* alert(window.location.hash);
        for(var i = 0; i < hashes.length; i++)
            {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            */
        // if (vars.length > 0){
        // if (window.location.hash != ""){
        var tab_href = window.location.hash; //"#" + vars[1];
        var tab_href_split = tab_href.split('#');
        var isDetail = false;
        if (tab_href_split.length==2)
        {
            tab_href_split = tab_href_split[1].split('_');
            if(tab_href_split.length==2 )
            {
                if(tab_href_split[0]=='sharing'){
                    isDetail = true;
                } else {
                    tab_href_split[0]+=('_'+tab_href_split[1])
                }
            }
        }
        else {
            tab_href_split[0] = tab_href_split[1];
        }
        var path_href=window.location.pathname;
        var elements = $("div#tabs ul li a.tab");
        var total_elements = $(elements).length;
        if (total_elements > 0 && elements[0].id) {
            var visit_tab_id = elements[0].id;
        } 
        if(/^(\/preview)?\/event/.test(path_href) || /^(\/preview)?\/cht\/event/.test(path_href)) {
            var today=new Date();
            var current_month=today.getMonth()+1;
            if(path_href.indexOf("/year")>0){
                var visit_tab_id = current_month; 
            } else if (path_href.indexOf("/lastyear")>0){
                var visit_tab_id = 12; 
            } else if (path_href.indexOf("/nextyear")>0){
                var visit_tab_id = 1; 
            } else {
                var visit_tab_id = current_month; 
            }
        }
        if (total_elements > 0) {
            for (var t = 0; t < total_elements; t++) {
                var href_attr = $(elements[t]).attr("href");
                var tab_in_href_attr = href_attr.split('#');
                if (('#'+tab_in_href_attr[1]) == '#'+tab_href_split[0]){
                    visit_tab_id = $(elements[t]).attr("id");
                    break;
                }
            }
        }
        if(!isDetail) {
            if($('#' + visit_tab_id)) {
                process_tabs(visit_tab_id);
            }
        }
        // }
        else
            showSharingDetail(visit_tab_id);
    }

	function showSharingDetail(str)
	{
		var tab_href = window.location.hash;
                var tab_href_split = tab_href.split('_');
		if (tab_href_split.length == 2 && tab_href_split[0] == '#sharing')
		{
			if(tab_href_split[1].split('&').length == 4)
			{
				parm = tab_href_split[1].replace(/\&/g,'|');
				
				$('#tab_sharing_block').load(site_url + 'share/ajax_get_detail', {data:parm},function() {
					process_tabs(str);
					$(".photo_gallery_thumbnail a").fancybox({ 'titlePosition': 'inside', 'autoScale' : false,  'centerOnScroll' :false });
				});
				
			}
		}
	}	
	
	$("#programme_sharing_more a").click(function(){
		$("div#tabs a#tab_sharing").click();
	});

        $("#teaching_staff_prog_more a").click(function(){
		$(this).parent().hide();
                $(this).parent().parent().find('.related').css('display','inline');		
        });

	
	$("div#tabs a.tab").click(function(){
		process_tabs($(this).attr("id"));
		sharing_move_init();	
	});
	
	function process_tabs(tab_id){
		var li_objs = $("div#tabs ul li");
		var tab_block_id = tab_id  + "_block";		
		var num_li_objs = li_objs.length;
	
		for (var i=0; i<num_li_objs; i++){
			if ($(li_objs[i]))
				$(li_objs[i]).attr("class","");
		}
		
		if ($("#"+tab_id).parent(0))
			$("#"+tab_id).parent(0).attr("class","active");
		
		$("div.tab_block").removeClass("show");
		$("div.tab_block").addClass("hide");
		
		if ($("div#" + tab_block_id)){
			$("div#" + tab_block_id).removeClass("hide");
			$("div#" + tab_block_id).addClass("show");
		}	
	}
	
	
	/***** register form *****/
	$("div.reg_field input.attend").click(function(){
		if ($(this).attr("checked")){		
			$(this).next().attr("disabled", "");
		}else {
			$(this).next().val("");
			$(this).next().attr("disabled", "disabled");
		}
	});
	
	/***** Search result Expanded/Condense View *****/
	if (($("#programme-list").length) && ($.cookie("listing_view") != "")) {
		
		if ($.cookie("listing_view") == "condense"){
			$("div#expanded_view .expand_selected").hide();
			$("div#expanded_view .expand").show();
			$("div#condensed_view .condense_selected").show();
			$("div#condensed_view .condense").hide();
			$("#programme-list").removeClass("expand");
			
		}else{
			$("div#expanded_view .expand_selected").show();
			$("div#expanded_view .expand").hide();
			$("div#condensed_view .condense_selected").hide();
			$("div#condensed_view .condense").show();
			$("#programme-list").removeClass("condense");
		}
		
		$("#programme-list").addClass($.cookie("listing_view"));
	
	}else if (($("#programme-list").length) && ($.cookie("listing_view") == "")) {
		
		$.cookie("listing_view", "expand", { path: '/', expires: 3650 });
		$("div#expanded_view .expand_selected").show();
		$("div#expanded_view .expand").hide();
		$("div#condensed_view .condense_selected").hide();
		$("div#condensed_view .condense").show();
		$("#programme-list").removeClass("expand");
		$("#programme-list").removeClass("condense");
		$("#programme-list").addClass("expand");
	}
	
	$("div#expanded_view").click(function(){
		$("div#expanded_view .expand_selected").show();
		$("div#expanded_view .expand").hide();
		$("div#condensed_view .condense_selected").hide();
		$("div#condensed_view .condense").show();
		$.cookie("listing_view", "expand", { path: '/', expires: 3650 });
		$("#programme-list").removeClass("condense");
		$("#programme-list").addClass("expand");
	});
	
	$("div#condensed_view").click(function(){
		$("div#expanded_view .expand_selected").hide();
		$("div#expanded_view .expand").show();
		$("div#condensed_view .condense_selected").show();
		$("div#condensed_view .condense").hide();
		$.cookie("listing_view", "condense", { path: '/', expires: 3650 });
		$("#programme-list").removeClass("expand");
		$("#programme-list").addClass("condense");
	});
	


    /***** Frontpage sort selection box *****/
    $("div.drop_down_box_frontpage").click(function(){
        if ($(this).find("ul").is(':visible')) {
            $(this).find("ul").fadeOut('fast');
        }else {
            $("div.drop_down_box_frontpage ul").fadeOut('fast');
            $(this).find("ul").fadeIn('fast');
        }
    });

    $("div.drop_down_box_frontpage li").click(function(){
        $(this).find("ul").fadeOut('fast');
    });



	/***** sort selection box *****/
/*
	$("div.drop_down_box").mousedown(function(){
		if ($(this).find("ul").is(':visible')) {
			$(this).find("ul").fadeOut('fast');
		}else {
			$("div.drop_down_box ul").fadeOut('fast');
			$(this).find("ul").fadeIn('fast');
		}
	});
    
    $("div.drop_down_box").hover(function(){
    },function(){
        if ($(this).find("ul").is(':visible')) {
			$(this).find("ul").fadeOut('fast');
		}
    });

	$("div.drop_down_box li").click(function(){
        var tab_href = window.location.hash;
	        var selected_url=$(this).children("a").attr("href");
	        $(this).children("a").attr("href",selected_url+tab_href);
	        location.href=$(this).children("a").attr("href");
	        return false;
	});

*/	
	
	$("div.drop_down_box").live('mousedown',function(){
		if ($(this).find("ul").is(':visible')) {
			$(this).find("ul").fadeOut('fast');
		}else {
			$("div.drop_down_box ul").fadeOut('fast');
			$(this).find("ul").fadeIn('fast');
		}
	});

	$("div.drop_down_box").live("mouseleave", function(){
		if($(this).find("ul").is(':visible')){
			$(this).find("ul").fadeOut('fast');
		}
	});
	
	$("div.drop_down_box").live("click", function(){
		try{
			var tab_href = window.location.hash;
			var selected_url=$(this).children("a").attr("href");
			$(this).children("a").attr("href",seletected_url+tab_href);
			location.href=$(this).children("a").attr("href");
			return false;
		}catch(err){}
	});
	
	
	/***** RSS in header *****/
	$("div#header a.rss").hover(function(){
		var pos_left = parseInt($(this).position().left) + 10;
		$("div#header div.drop_down_box").attr('style',"left:"+pos_left+"px");
		$("div#header div.drop_down_box").find("ul").fadeIn('fast');
		if (rss_timer==null)
			rss_timer = setTimeout("hideRSSBlock()",1500);
	});
	
	$("div#header div.drop_down_box").mouseenter(function(){
		clearTimeout(rss_timer);
		rss_timer = null;
	});
	
	$("div#header div.drop_down_box").mouseleave(function(){
		hideRSSBlock();
	});

	/***** photo gallery fancybox init *****/
	if($.fn.fancybox)
	{
		$(".photo_gallery_thumbnail a").fancybox({ titlePosition: 'inside', autoScale : false,centerOnScroll :false, onComplete: function() { $('#fancybox-title').show(); } }); 
	}
	
	function init(){
		if ($.cookie("font")) {
			$("body").css("fontSize", $.cookie("font"));
		}
		else {
			$.cookie("font", default_font_size, { path: '/', expires: font_cookies_expire_days });
			$("body").css("fontSize", default_font_size);
		}
		/*
		if ($("#tab_1")) {
			$("#tab_1").parent(0).attr("class", "active");
			$("#tab_1_block").removeClass("hide");
			$("#tab_1_block").addClass("show");
		}
		*/
		show_tab_content();
		
		$('#left_menu').find('a.active').each(function(){
			$(this).parents('li,ul').addClass('active');
		});
		var active_level1_li = $("#left_menu ul.level1 li.active").find("a.item");
		
		if ($(active_level1_li).parent(0).next().attr("class") == "level2") 
			$(active_level1_li).parent(0).next().show();
		else 
			$(active_level1_li).parent(0).find("ul.level2").show();
							
	}
	
    saveProgramme = function (oid) {
        oid = oid.toString();
        var programmes = $.cookie('savedProgrammes');
        programmes = null==programmes ? [] : programmes.split(',');
        if (-1!=$.inArray(oid, programmes)) return;
        programmes.push(oid);
        $.cookie('savedProgrammes', programmes.join(','), {path:'/', expires: 14});
	alert('eng'==lang ? 'Programme Saved' : '課程已儲存');
        loadSavedProgramme();
    };

    deleteSavedProgramme = function (oid) {
        var programmes = $.cookie('savedProgrammes');
        programmes = null==programmes ? [] : programmes.split(',');
        new_programmes = [];
        for (var idx in programmes) {
            if (oid!=programmes[idx]) new_programmes.push(programmes[idx]);
        }

        $.cookie('savedProgrammes', new_programmes.join(','), {path:'/', expires: 14});
        loadSavedProgramme();
    }

    loadSavedProgramme = function () {
        $.getJSON(site_url + 'programme/saved_programme', {progs: $.cookie('savedProgrammes'), time:new Date().getTime()}, function (data, success) {
            if ('success'==success) {
                if (0==data.length) {
                    $('#saved_programme').remove();
                    return;
                }
                    var wrapper = $('<div id="saved_programme"><div class="top"></div><div class="content"><div class="title"><img src="' + base_url + 'assets/images/icon_save.png" width="55px" height="55px" alt="#"><div>' + ('eng'==lang ? 'My Saved Programmes' : '我的課程') + '</div></div></div><div class="bottom"></div><ul/></div>');
                    for (var idx in data) {
                        var item = data[idx];
		    if(item['course_code'].indexOf('ZZ')=='0'){
			itemcode_html = '';
		    }else{
                        itemcode_html = '<br/><a class="item-code">' + item['course_code'] + '</a>';
		    }
                        var li = $('<div class="save-item"><a class="item-name">' + item['name'] + '</a>' + itemcode_html + '<br/><span class="delete">' + (lang=='eng' ? 'Remove' : '移除') + '</span></div>');
                        li.find('a').attr('href', site_url + 'prog/' + item['url']);
                        li.find('.delete').css('cursor','pointer').click(function () {
                            deleteSavedProgramme(item['oid']);
                        });
                        li.appendTo(wrapper.find('div.content'));
                    }
                    if ($('#saved_programme').length>0) {
                        $('#saved_programme').replaceWith(wrapper);
                    }
                    else {
                        $('#left_menu').append(wrapper);
                    }
            }
        });
    }

	
	$('#advanced_search_page .checkbox_group input').click(function(){
		var parent = $(this).parents('.checkbox_group').eq(0);
		var other_checkboxes = ($(this).attr("class") == "all") ? parent.find("input.option") : parent.find("input.all");
		
		if ($(this).attr("checked"))
			other_checkboxes.attr("checked","");
	});
	
	
	$(function() {
		$("#datepicker_search_from_date").datepicker({
			showOn: 'button', 
			buttonImage: base_url + 'assets/images/button_cal.gif', 
			buttonImageOnly: true,
			showAnim: 'fadeIn',
			dateFormat: 'dd/MM/yy',
			yearRange: '-01:+01',
			hideIfNoPrevNext: true,
			onSelect: function(dateText, inst) { 
				date_array = dateText.split("/");
				$(".search_select_date select#from_day option:selected").attr("selected","");
				$(".search_select_date select#from_month option:selected").attr("selected","");
				$(".search_select_date select#from_year option:selected").attr("selected","");
				$(".search_select_date select#from_day option:contains('" + date_array[0] + "')").attr("selected","selected");
				$(".search_select_date select#from_month option:contains('" + date_array[1] + "')").attr("selected","selected");
				$(".search_select_date select#from_year option:contains('" + date_array[2] + "')").attr("selected","selected");
			}
		});
		
		$("#datepicker_search_to_date").datepicker({
			showOn: 'button', 
			buttonImage: base_url + 'assets/images/button_cal.gif', 
			buttonImageOnly: true,
			showAnim: 'fadeIn',
			dateFormat: 'dd/MM/yy',
			yearRange: '-01:+01',
			hideIfNoPrevNext: true,
			onSelect: function(dateText, inst) { 
				date_array = dateText.split("/");
				$(".search_select_date select#to_day option:selected").attr("selected","");
				$(".search_select_date select#to_month option:selected").attr("selected","");
				$(".search_select_date select#to_year option:selected").attr("selected","");
				$(".search_select_date select#to_day option:contains('" + date_array[0] + "')").attr("selected","selected");
				$(".search_select_date select#to_month option:contains('" + date_array[1] + "')").attr("selected","selected");
				$(".search_select_date select#to_year option:contains('" + date_array[2] + "')").attr("selected","selected");
			}
		});
	});
	
	
	/* add advanced search subject area selection list */ 
	$("#advanced_search_page div.search_add_more").live("click",function(){
		var parent = $(this).parents('.div_select_subject_area');
		var parent_clone = parent.clone();
		
		parent_clone.find("select").attr("id","subject_area_"+ ++total_select_block);
		parent_clone.appendTo("#td_select_subject_area");
	});
	
	/* delete advanced search subject area selection list */ 
	$("#advanced_search_page div.search_delete_more").live("click",function(){
		var parent = $(this).parents('.div_select_subject_area');
		var total_select_block = $("#td_select_subject_area").find("select").length;
		
		if (total_select_block > 1)
			parent.remove();
	});
	
	
    $('div.reg_timeline form').submit(function () {
        var $this = $(this);
        $this.find('p.error').remove();
        var pass = true;
        $this.find('input.mandatory').each(function () {
            var $that = $(this);
            if ($that.val()=='') {
                $that.after('<p class="error">Please fill in this field</p>');
                $that.focus();
                pass = false;
            }
        });
        if (!pass) return false;
    });

    $('#tab_1_block div.student div.name').click(function () {
        var name = $(this).text();
        $('#sharing_block div.student div.name:contains(' + name + ')').parents('.sharing').find('div.photo img').click();
        process_tabs('sharing');
    });

    loadSavedProgramme();
	
	
	if ($("#registration").length) {
		var validator = $("#registration").validate({meta: "validate"});
	}
	
    //kl area
    $('div.code_checkbox input[type=text]').keyup(function () {
        if (this.value.length >= this.maxLength) {
            var target = '';
            switch (this.id) {
                case 'course_code1':
                    target = 'course_code2';
                    break;
                case 'course_code2':
                    target = 'course_code3';
                    break;
                case 'course_code3':
                    target = 'course_code4';
                    break;
                case 'course_code4':
                    target = 'course_code6';
                    break;
            }
            if (''!=target) $('#' + target).focus();
        }
    });
    //kl area end
	

    //lang switch
    $('#lang_switch').click(function () {
/*	    
        var is_cht = /\/cht\//.test(site_url);
        var real_site_url = location.protocol+'//'+location.host+site_url;
        var url = location.href.replace(real_site_url, '');

        var prefix = is_cht ? site_url.replace('cht/', '') : (site_url + 'cht/');

        location.replace(prefix + url);
*/
	if(lang == 'cht'){
		location.href = location.href.replace('/cht/','/');
	}else{
		var href = location.href.match(/\?/) || location.href.match(/\/$/) || location.hash.length?  location.href : location.href+'/';
		var new_url = href.replace(location.host+site_url,location.host+site_url+'cht/');
		location.href = new_url;
	}
    });
	
	if (is_ie6()) {
		$("#tabs ul li").hover(	
			function() { if ($(this).attr("class")!="active") $(this).find("a").addClass("hover"); },
			function() { if ($(this).find("a").hasClass("hover")) $(this).find("a").removeClass("hover"); }
	    );
	}

	init();
});


function is_ie6(){
	return (($.browser.msie) && ($.browser.version=="6.0"));
}

function hideRSSBlock(){
	clearTimeout(rss_timer);
	rss_timer = null;
	$("div#header div.drop_down_box").find("ul").fadeOut('fast');
}



/* -------------------------------- IE6 PNG FIX -------------------------------- */

(function($) {

	/**
	 * helper variables and function
	 */
	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};
	
	$.ifixpng.regexp = {
		bg: /^url\(["']?(.*\.png([?].*)?)["']?\)$/i,
		img: /.*\.png([?].*)?$/i
	},
	
	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || '/assets/images/blank.gif';
	};
	
	var hack = {
		base	: $('base').attr('href'),
		ltie7	: $.browser.msie && $.browser.version < 7,
		filter	: function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};

	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */
	 
	$.fn.ifixpng = hack.ltie7 ? function() {
		function fixImage(image, source, width, height, hidden) {
			image.css({filter:hack.filter(source), width: width, height: height})
			  .attr({src:$.ifixpng.getPixel()})
			  .positionFix();
		}
		
    	return this.each(function() {
			var $$ = $(this);
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				var source, img;
				if (this.src && this.src.match($.ifixpng.regexp.img)) { // make sure it is png image
					// use source tag value if set 
					source = (hack.base && this.src.substring(0,1)!='/' && this.src.indexOf(hack.base) === -1) ? hack.base + this.src : this.src;
					// If the width is not set, we have a problem; the image is not probably visible or not loaded
					// and we need a work around.
					if (!this.width || !this.height) {
						$(new Image()).one('load', function() {
							fixImage($$, source, this.width, this.height);
							$(this).remove();
						}).attr('src', source);
					// If the image already has dimensions (it's loaded and visible) we can fix it straight away.
					} else fixImage($$, source, this.width, this.height);
				}
			} else if (this.style) { // hack png css properties present inside css
				var imageSrc = $$.css('backgroundImage');
				// Background repeated images we cannot fix unfortunately
				if (imageSrc && imageSrc.match($.ifixpng.regexp.bg) && this.currentStyle.backgroundRepeat == 'no-repeat') {
					imageSrc = RegExp.$1;
					var x = this.currentStyle.backgroundPositionX || 0, y = this.currentStyle.backgroundPositionY || 0;
					if (x || y) {
						var css = {}, img;
						if (typeof x != 'undefined') {
							if (x == 'left') css.left = 0; 
							// if right is 0, we have to check if the parent has an odd width, because of an IE bug
							else if (x == 'right') css.right = $$.width() % 2 === 1 ? -1 : 0;
							else css.left = x;
						}
						if (typeof y != 'undefined') {
							// if bottom is 0, we have to check if the parent has an odd height, because of an IE bug
							if (y == 'bottom') css.bottom = $$.height() % 2 === 1 ? -1 : 0; 
							else if (y == 'top') css.top = 0;
							else css.top = y;
						}
						img = new Image();
						$(img).one('load', function() {
							var x,y, expr = {}, prop;
							// Now the image is loaded for sure, we can see if the background position needs fixing with an expression (in case of percentages)
							if (/center|%/.test(css.top)) {
								expr.top = "(this.parentNode.offsetHeight - this.offsetHeight) * " + (css.top == 'center' ? 0.5 : (parseInt(css.top) / 100));
								delete css.top;
							}
							if (/center|%/.test(css.left)) {
								expr.left = "(this.parentNode.offsetWidth - this.offsetWidth) * " + (css.left == 'center' ? 0.5 : (parseInt(css.left) / 100));
								delete css.left;
							}
							// Let's add the helper DIV which will simulate the background image
							$$.positionFix().css({backgroundImage: 'none'}).prepend(
								$('<div></div>').css(css).css({
									width: this.width,
									height: this.height,
									position: 'absolute',
									filter: hack.filter(imageSrc)
								})
							);
							if (expr.top || expr.left) {
								var elem = $$.children(':first')[0];
								for (prop in expr) elem.style.setExpression(prop, expr[prop], 'JavaScript');
							}
							$(this).remove();
						});
						img.src = imageSrc;
					} else {
						$$.css({backgroundImage: 'none', filter:hack.filter(imageSrc)});
					}
				}
			}
		});
	} : function() { return this; };
	
	/**
	 * positions selected item relatively
	 */
	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			if ($$.css('position') != 'absolute') $$.css({position:'relative'});
		});
	};

})(jQuery);

$(document).ready(function(){
	if (is_ie6()) {
	
	jQuery.ifixpng('/assets/images/blank.gif');
	$("div#header div.links_row a").ifixpng();	
	$("#button_search").ifixpng();
	$("#button_keyword_search").ifixpng();
	$("div#main_content div.container_tl").ifixpng();
	$("div#main_content div.container_tr").ifixpng();
	//$("div#main_content div#left_menu .head_r").ifixpng();
	$("div#main_content div#left_menu .head_l").ifixpng();
	$("div#main_content div#left_menu div#left_menu_bottom").ifixpng();
	$("div#main_content div.container_br ").ifixpng();
	$("div#main_content div.container_bl").ifixpng();
	$("div#footer div.links_row a").ifixpng();
	$("div#main-bottom div.news h3 span a ").ifixpng();
	$("div#main_content #calendar .top").ifixpng();
	$("div#main_content #calendar .bottom").ifixpng();
	$("div#footer div#copyright img").ifixpng();
	$("div#main_content div.prog_sort div.sort_off, div#main_content div.prog_sort div.sort_asc, div#main_content div.prog_sort div.sort_desc").ifixpng();
	$("#course-code-tips, div#main_content div#advance_search div.code_checkbox div.arrow_course_code, div.icon_desc img").ifixpng();
	$("div#main_content div.programme_summary div.action div.course_icons img").ifixpng();
	$("div#main_content div#left_menu ul.level2 li div.left_submenu div.left_submenu_bottom").ifixpng();
	$("div#main_content div#left_menu ul.level2 li div.left_submenu div.left_submenu_top").ifixpng();
	$("div#main_content li.prog_list div.graphics img").ifixpng();
        $("h2 img").ifixpng();

	$.ifixpng('/assets/images/playplay.png');
	$("span.youtube_play").ifixpng();	
//        $("span.tab_l").ifixpng();

	/* 
	$(".ui-widget-header").ifixpng();
	$("div.dialog_bottom").ifixpng();
	$("div.dialog_body").ifixpng();	
	*/
	}
});


/* -------------------------------- IE6 PNG FIX -------------------------------- */




