(function ($) {
    $(document).ready(function () {
        $('#search_keyword').focus(function () {
            var $this = $(this);
            if ($this.val()==$this.attr('title')) $this.val('');
        });
        $('#search_keyword').blur(function () {
            var $this = $(this);
            if ($this.val()=='') $this.val($this.attr('title'));
        });
        var refreshCourseCode = function () {
            var cc_input = $('input[name=course_code]');
            var value = '';
            $('.code_checkbox input[id^=course_code][type=text]').not('#course_code6').each(function (idx) {
                if (''==this.value) return false;
                if (1==idx) value += ' ';
                if (1<idx && 5>idx) value += '-';
                value += this.value.toUpperCase();
            });
            var cc6 = $('#course_code6');
            if (''!=cc6.val()) value += ' (' + cc6.val() + ')';
            cc_input.val(value);
        };
        $('.code_checkbox input[type=text]').each(function (idx) {
            //handle course code segment
            $this = $(this);
            //$this.attr('disabled', idx!=0 && ''==$this.val().replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1') && ''==$this.prev('input').val().replace(/^\s*((?:[\S\s]*\S)?)\s*$/, '$1'));
            $this.bind('keyup change', function (e) {
                //$that = $(this);
                //if (''==$that.val()) {
                //    $that.nextAll('input[type=text]').not('#course_code6').val('').attr('disabled',true);
                //}
                //$next = $that.next();
                //$next.attr('disabled', ''==$that.val());
                refreshCourseCode();
            });
        });
        refreshCourseCode();
        $('#search_keyword_form form').submit(function() {
            var search_form = $(this);
            var q = $('#search_keyword');
            if (q.val()==q.attr('title')) q.val('');
            //check adv form exists and submit adv field
            var adv_form = $('#advance_search');
            if (adv_form.length>0 && location.href.indexOf('/category/')==-1 && location.href.indexOf('/subject/')==-1) {
                var invisble = $('<div style="display:none"/>');
                invisble.append(adv_form.find(':input').clone(true)).appendTo(search_form);
            }
        });

        $('#search_keyword, #programme-search-form input[name=q]').parents('form').bind('keypress',function(e){
		if(13==e.keyCode) return false;
	});
        $('#search_keyword, #programme-search-form input[name=q]').attr('autocomplete','off').keyup(function (e) {
            var $this = $(this);
            var $suggest = $('#search-suggest');
            var $form = $this.parents('form');
            var keycode = e.keyCode || window.event.keyCode;
	    var suggest_list = $suggest.children('ul');
	    var getActiveItem = function(){
		    var idx = -1;
		    suggest_list.children().each(function(){
			    if($(this).data('active')=='active'){
				    idx = $(this).parent().children().index(this);
				    return false;
			    }
		    });
		    return idx;
	    }
	    var highlightItem = function(idx){
		    suggest_list.children().each(function(){
			    if($(this).parent().children().index(this) == idx){
				    $(this).data('active','active');
				    $(this).css('background','#FFCC00');
			    }else{
				    $(this).data('active','');
				    $(this).css('background','#EEEEEE');
			    }
		    });
	    }
            if (27==keycode || ''==this.value) {
                $suggest.fadeOut();
                return;
	    }else if(13==keycode){
		    var i = getActiveItem();
		    if(i==-1){
			    $this.parents('form').submit();
			    return false;
		    }else{
			    suggest_list.children().eq(i).click();
			    $this.parents('form').submit();
			    return false;
		    }
            }else if(40==e.keyCode){
		    var i = getActiveItem();
		if(i==-1)
			var active = 0;
		else
			var active = i+1;
		highlightItem(active);
		return;
	   }else if(38==e.keyCode){
		   var i = getActiveItem();
		if(i==-1 || i==0)
			var active = suggest_list.children().length-1;
		else
			var active = i-1;
		highlightItem(active);
		return;
	   }  
            var $ul = $suggest.find('ul');
            $ul.empty();
            $.getJSON($form.attr('action') + '_json', {q:this.value.toLowerCase()}, function (data, status) {
                if ('success'==status) {
                    if (0<data.length) {
            $ul.empty();
                        for (var idx in data) {
                            (function () {
                                var item = data[idx];
                                var $li = $('<li/>');
                                $li.text(item).css('cursor','pointer');
                                $li.click(function () {
                                    $this.val(item);
                                    $this.parents('form').submit();
                                    $suggest.fadeOut();
                                }).hover(function(){$(this).css('background','#FFCC00');},function(){$(this).css('background','#EEEEEE');});
                                $li.appendTo($ul);
                            })();
                        }
                        $suggest.fadeIn();
                        $('body').not($suggest).one('click', function () {
                            $suggest.fadeOut();
                        });
                    }
                }
            });
        });
    });

        $('.subject_select').mouseover(function(){
            $('.subject_select').removeClass("hover");
            $(this).addClass("hover");
        });

        $('.subject_select_level').mouseover(function(){
            $('.subject_select_level').removeClass("hover");
            $(this).addClass("hover");
        });


//    $('#course-code-tips').tooltip({top:30, left: -300});
})(jQuery);

