/***********************************
 * 자동완성 기능 함수 
 ***********************************/
/**
 * 해당 DOM 객체에 자동완성기능 이벤트 추가. 
 * 
 *  @param elementId : 입력박스 ID
 */
function buildAutoComplete(){
	var element = getElement('input-keyword');
	var options = new Array();
	options["width"] = 207;		
	
	element.addEvent('keyup', function(){		
		loadAutoCompletion(element, options);
    });	
}

function loadAutoCompletion(element, options) {
	var input = element.getValue();
    
    if(isCompletlyString(input)){
    	var request = new Json.Remote('/bio/presearch/', {
            onComplete: function(response){
                var resultSet = response.resultSet;
				                    
                if(resultSet.length < 1){
                	removeElement('search-autocomplete');
                    return;
                }
                
                if(!$('search-autocomplete')){
                	var width = 282;
                    var coordinate = element.getCoordinates();
                    var layerName = ($('layout-content')? 'layout-content':'layout-search-content');
                    
                    if(options != null && options['width'] != null) {
                    	width = options['width'];
                    } 
                    
                    new Element('div', {
                        id: 'search-autocomplete',
                        styles: { 
                            'position': 'absolute',
                            'left': coordinate.left,
                            'top': coordinate.bottom,
                            'min-width' : width,
                            'z-index': 10000,
                            'display': 'block',
                            'border': '1px solid cornflowerblue',
                            'backgroundColor': 'aliceblue'
                        }
                    }).inject(layerName);
                }

                $('search-autocomplete').setHTML('');
                var isEnglish = (response.lang == "en");
                var links = new Element('div');

                for(var index = 0; index < resultSet.length; index++){
                    var row = resultSet[index];
                    var valueString = (isEnglish) ? row.ename : row.kname;
                    var label = ""; 
                    if(row.kname != null) {
                        label = (!isEnglish)? row.ename : 
                            		row.ename.replace(response.keyword, '<strong>' + response.keyword + '</strong>');
                    }

                    if(row.ename != null) {
                        if(label.length > 0)
                            label += " | ";
                        
                        label += (isEnglish)? row.kname : 
                    		row.kname.replace(response.keyword, '<strong>' + response.keyword + '</strong>');
                    }
                      
                    new Element('span', {
                        'class': 'entry',
                        searchWord : valueString,
                        events: {
                            click: function(){
                                element.setProperty('value', this.getProperty('searchWord'));
                        		removeElement('search-autocomplete');                                    
                            }
                        }
                    }).setHTML(label).inject(links);
                }
                
                links.inject('search-autocomplete');
            }
        }).send({ keyword: input});
    } else if(input.trim().length == 0){
    	removeElement('search-autocomplete');
    }
}

function getElement(elementId) {
	return document.getElementById(elementId);
}

/**
 * 입력된 문자가 정상적으로 작성된 상태인지를 확인하고 정상인 경우 true를 반환한다. 
 * 공백문자, 특수문자, 한글의 경우 모음 혹은 자음으로만 구성된 경우 false를 반환한다. 
 */
function isCompletlyString(string) {
	if(string == null) 
		return false;

	if(string.trim().length == 0)
		return false;

	if(string.test(/[^a-zA-Z0-9ㄱ-힣\-\~]+/))  
		return false;
	
	for(var i=0; i < string.length ; i++) {
		var c = string.charCodeAt(i);

		// 한글 모음 혹은 자음이 단독으로 존재하는 경우. 
		if(( 0x3131 <= c && c <= 0x318E ))
			return false; 
	}

	return true;
}

/**
 * 해당ID의 DOM 객체를 제거한다.  
 */
function removeElement(elementId) {
	if(elementId == undefined || elementId.trim() == "")
		return;	

	if(document.getElementById(elementId))
		document.getElementById(elementId).remove();  
}

function appendSequence(id, sci_name, seq_no, seq) {
	var request = new Json.Remote('/bio/appendseq/', {
            onComplete: function(response){
				alert(response.message);
				var storedCount = response.storedCount;
				if(storedCount < 2) {
					$("storedButton").setStyle("display", "none");
				} else {
					$("storedButton").setStyle("display", "inline");
				}
            }
        }).send({ id: id, sci_name: sci_name, seq_no: seq_no, seq: seq});
	
	return false;
}

