$(document).ready(function(){
	
	setAutoComplete = [ null, null];
	autoDivName 	= [ null, null];
	lastDate		= null;
	var idAutoStartApank = false;
	var startAutoAutoCompFocus = false;

	(function( $ ) {
		$.fn.autoCompleteApank = function(option){

			$(this).each(function(){
				idName = this.id;
			})
			
			var defaults = $.extend({
				url : '',
				minCharacter : 1,
				width : 0,
				size : 150,
				header : true,
				expSelect : false,
				emptyNull : false,
				newVar : [],
				clickEvent : false,
				model : 'default',
			})
			
			autoDivName[idName] 	= 'div'+idName;
			setAutoComplete[idName] = $.extend({}, defaults, option);
			
			width = setAutoComplete[idName]['width'];
			if(width == 0){
				width = setAutoComplete[idName]['size'];
			}
			
			if(setAutoComplete[idName]['model'] === 'default'){
				classDiv = 'divApankAutocomplete';
				_Nwidth = width+'px';
			} else if(setAutoComplete[idName]['model'] === 'div_top'){
				classDiv = 'divApankAutocompleteTop';
				_Nwidth = '100%';
			} else if(setAutoComplete[idName]['model'] === 'manGrid'){
				classDiv = 'divApankAutocompleteManual';
				_Nwidth = width+'px';
			}
			
			$('#'+idName).keyup(function(e){

				read = $('#'+idName).attr('readonly');
				if(read === 'readonly' & setAutoComplete[idName]['model'] === 'div_top'){
					return;
				}else if(setAutoComplete[idName]['model'] === 'default' & (e.keyCode == 45 || e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40)){
					return;
				}else if(setAutoComplete[idName]['model'] === 'manGrid' & (e.keyCode == 45 || e.keyCode == 37 || e.keyCode == 39)){
					return;
				}else{
				
					if (e.keyCode == 40 || e.keyCode == 38) {
						setFocus(1);
					}else
					if (e.keyCode == 13) {
						$('.divApankAutocompleteTop').empty();
					}else{
						idName 	= this.id;
						data 	= $(this).val();
						
						if(data.length >= setAutoComplete[idName]['minCharacter']){
							
							$('#'+idName).removeClass('text').addClass('text loadingAutocompleteApank');
							
							value = $(this).val();
							value = replaceValue(value);
							
							date = dateNow();

							timeInterval(setAutoComplete[idName], value, idName, autoDivName[idName], date);
						}else{
							JsonError (autoDivName[idName]);
						}
					}
				}
			})
			.after('<div class="'+classDiv+'" id="'+autoDivName[idName]+'" style="width: '+_Nwidth+'px"></div>')
			.css('width', setAutoComplete[idName]['size']+'px')
			.attr('autocomplete', 'off');
			clickTd(autoDivName[idName], idName, setAutoComplete[idName]);
			closeDiv(autoDivName[idName]);
			makeOffEnter(idName);
			
			if(setAutoComplete[idName]['clickEvent'] === true){
				$('#'+idName).click(function(e){

					read = $('#'+idName).attr('readonly');
					if(read === 'readonly'){
						return;
					}else{
					
						if (e.keyCode == 40 || e.keyCode == 38) {
							setFocus(1);
						}else
						if (e.keyCode == 13) {
							$('.divApankAutocompleteTop').empty();
						}else{
							idName 	= this.id;
							data 	= $(this).val();
							
							if(data.length >= setAutoComplete[idName]['minCharacter']){
								
								$('#'+idName).removeClass('text').addClass('text loadingAutocompleteApank');
								
								value = $(this).val();
								value = replaceValue(value);
								
								date = dateNow();

								timeInterval(setAutoComplete[idName], value, idName, autoDivName[idName], date);
							}else{
								JsonError (autoDivName[idName]);
							}
						}
					}
				})
			}
		};
	})( jQuery );
	
	makeLoadData = function(setting, value, idName, divId){
		
		vt = setting['newVar'];
		dVt = '/&q='+value;
		pVt = '';
		for(i = 0; i < vt.length; i++){
			dVt+= '&'+vt[i]+'='+$('#'+vt[i]).val();
			pVt+= '/'+$('#'+vt[i]).val();
		}
		
		if(idAutoStartApank !== false){
			idAutoStartApank.abort();
		}
		
		idAutoStartApank = $.ajax( {	
				type : "GET",
				url : setting['url']+value+pVt+dVt,	
				dataType : "json",	
				data : $(this).serializeArray(),
				success : function(obj,status,xhr) {
					if(obj != null){
						if(obj.total > 0){
							JsonViewObject (obj, setting, divId);
						}else{
						
							if(setting['emptyNull'] == true){
								$('#'+idName).val('');
							}
						
							JsonError (divId);
						}
					}else{
						JsonError (divId);
					}
					$('#'+idName).removeClass('text loadingAutocompleteApank').addClass('text');
				},
			error : function(x,e){
					JsonError (divId);
				}
		})
		
	}
	$('#close-tableAutoCompleteTop').live('click', (function(){
		$('.divApankAutocompleteTop').empty();
	}))
	
	setFocus = function(id){
		$('#trAutoComplete_'+id+' td').css('background-color', 'yellow');
		$('#cehAutoHide_'+id).focus();
	}
	
	makeColorTr = function(id){
		$('.trAutoCompleteHide td').removeAttr('style');
		id = id.split('_');
		id = id[1];
		id = parseInt(id);
		return id;
	}
	
	makeAutoFocus = function(id, no, jum){
		setTimeout(function(){    
			id = id+no;
			$('.trAutoCompleteHide td').removeAttr('style');
			setFocus(id);
			if(id < jum){
				if(startAutoAutoCompFocus === true){
					makeAutoFocus(id, no, jum, true);
				}
			}else{
				startAutoAutoCompFocus = false;
			}
		}, 300);    
	}
	
	var dblClickTop = 0;
	var dblClickBottom = 0;
	
	$('.cehAutoHide').live('keyup', (function(e){
		if(startAutoAutoCompFocus === true){
			startAutoAutoCompFocus = false;
		}else{
			jum = $('#'+this.id).attr('title');
			if (e.keyCode == 38) {
				id = makeColorTr(this.id);
				id = id-1;
				if(id < 1){
					id = jum;
				}
				setFocus(id);
				
				dblClickTop += 1;   

				if(dblClickTop==2){
					startAutoAutoCompFocus = true;
					makeAutoFocus(id, -1, jum);
				}   

				setTimeout(function(){    
				  dblClickTop = 0; 
				}, 200);    
				
			}else
			if (e.keyCode == 40) {
				id = makeColorTr(this.id);
				id = id+1;
				if(id > jum){
					id = 1;
				}
				setFocus(id);
				
				dblClickBottom += 1;   

				if(dblClickBottom==2){
					startAutoAutoCompFocus = true;
					makeAutoFocus(id, 1, jum);
				}   

				setTimeout(function(){    
				  dblClickBottom = 0; 
				}, 200);    
				
			}else
			if (e.keyCode == 13) {
			}else
			if (e.keyCode >= 65 & e.keyCode <= 90) {
				makeInput(e.keyCode);
			}else
			if (e.keyCode >= 48 & e.keyCode <= 57) {
				makeInput(e.keyCode);
			}else
			if (e.keyCode >= 190 || e.keyCode >= 188) {
				makeInput(e.keyCode)
			}else{
				$('.divApankAutocompleteTop').empty();
				alt = this.alt;
				alt = alt.split('___');
				id  = alt[0];
				$('#'+id).focus().val();
			}
		}
	}))
	makeInput = function(kode){
		idT = '#cehAutoHide_'+this.id;
		cls = $(idT).attr('class');
		nm = cls.split('div');
		nm = nm[1];
		
		convr = makeAbjad();
		abjad = convr[kode];
		
		val = $('#'+nm).val()+abjad;
		
		$('#'+nm).val(val).focus();
	}
	makeAbjad = function(){
		kode[65] = 'a';
		kode[66] = 'b';
		kode[67] = 'c';
		kode[68] = 'd';
		kode[69] = 'e';
		kode[70] = 'f';
		kode[71] = 'g';
		kode[72] = 'h';
		kode[73] = 'i';
		kode[74] = 'j';
		kode[75] = 'k';
		kode[76] = 'l';
		kode[77] = 'm';
		kode[78] = 'n';
		kode[79] = 'o';
		kode[80] = 'p';
		kode[81] = 'q';
		kode[82] = 'r';
		kode[83] = 's';
		kode[84] = 't';
		kode[85] = 'u';
		kode[86] = 'v';
		kode[87] = 'w';
		kode[88] = 'x';
		kode[89] = 'y';
		kode[90] = 'z';
		kode[48] = '0';
		kode[49] = '1';
		kode[50] = '2';
		kode[51] = '3';
		kode[52] = '4';
		kode[53] = '5';
		kode[54] = '6';
		kode[55] = '7';
		kode[56] = '8';
		kode[57] = '9';
		kode[190] = '.';
		kode[188] = ',';
		return kode;
	}
	makeOffEnter = function(id){
		$('.inputNone, .text').live('keypress', (function(e){
			
			if (e.which == 13) {
				cId = this.id;
				val = $('#'+cId).attr('alt');
				$('.divApankAutocompleteTop, .divApankAutocompleteManual').empty();
				enterKey(val);
				
				return false;
			}	
		}))
	}
})

function timeInterval(settings, value, idName, divId, date){
	var timer = setInterval( showDiv, 500);

	function showDiv() {
	
		newVal = $('#'+idName).val();
		newVal = replaceValue(newVal);
		
		if(newVal == value && lastDate != date){
			lastDate = date;
			$('.divApankAutocomplete').empty();
			$('.divApankAutocompleteTop').empty();
			makeLoadData(settings, value, idName, divId);
		}
		
		clearInterval(timer);
	}
}

function replaceValue(val){
	
	val = val.split('/');
	
	jumVal = val.length;
	
	value = '';
	
	no = 0;
	for(i = 0; i < jumVal; i++){
	
		if(no > 0){
			value+= ';';
		}
		no++;
		
		value+= val[i];
	}
	
	return value;
}

function displayDefault(obj, settings, divId){
    var str = '<a id="close-tableAutoComplete">';
		str+= '<img class="close" src="assets/apankPlugin/close.png">';
		str+= '</a>';
		str+= '<table class="tableAutoComplete" cellspacing="2" cellpadding="2" border="0">';
		
	if(obj.header != null){
		if(obj.header.length > 0){
			str+= '<thead><tr>';
			for(i = 0; i < obj.header.length; i++){
					str+= '<td>'+obj.header[i]+'</td>';
			}
			str+= '</tr></thead>';
		}
	}
	
	for(i = 1; i <= obj.total; i++){	
        str += '<tr class="click-'+divId+'" id="'+obj.data[i]['value']+'">';
		for(n = 0; n < obj.data[i]['data'].length; n++){
			str += '<td>'+obj.data[i]['data'][n]+'</td>';
		}
		str += '</tr>';
	}
	
	str+= '</table>';

    $('#'+divId).html(str);
}


function displayDivTop(obj, settings, divId){
			
    var str = '<a id="close-tableAutoCompleteTop">';
		str+= '<img class="close" src="assets/apankPlugin/close.png">';
		str+= '</a>';
		str+= '<table class="divAutoComplete" cellspacing="1" cellpadding="1" border="0">';
	
	if(obj.total > 5){
		wDefT = 47;
		wDefB = 30;
	}else{
		wDefT = 30;
		wDefB = 30;
	}
	
	if(obj.header != null){
		if(obj.header.length > 0){
			str+= '<thead><tr>';
			for(i = 0; i < obj.header.length; i++){
					str+= '<td width="'+obj.size[i]+'">'+obj.header[i]+'</td>';
			}
			str+= '<td width="'+wDefT+'px"></td>';
			str+= '</tr></thead>';
		}
	}
	
	str+= '</table>';
	str+= '<div style="overflow:auto;width:100%;height:155px">';
	str+= '<table class="divAutoComplete" cellspacing="1" cellpadding="1" border="0">';
	for(i = 1; i <= obj.total; i++){	
        str += '<tr class="trAutoCompleteHide clickTop-'+divId+'" id="trAutoComplete_'+i+'" title="'+obj.data[i]['value']+'">';
		for(n = 0; n < obj.data[i]['data'].length; n++){
			str += '<td valign="center" width="'+obj.size[n]+'">'+obj.data[i]['data'][n]+'</td>';
		}
		str+= '<td width="'+wDefB+'px" style="padding-top: 0px"><input title="'+obj.total+'" type="text"  style="margin-top: -3px; border: none; width: 1px; color:#fff" class="inputNone cehAutoHide '+divId+'" id="cehAutoHide_'+i+'" alt="'+obj.data[i]['value']+'"></td>';
		str += '</tr>';
	}
	
	str+= '</table>';
	str+= '</div>';

    $('#'+divId).html(str);
}

function JsonViewObject(obj, settings, divId){
	
	if(settings['model'] == 'default'){
		displayDefault(obj, settings, divId);
	}else{
		displayDivTop(obj, settings, divId);
	}
	
}
	
function clickTd(divId, idName, settings){
	$('.click-'+divId).live('click',(function(){
		$('#'+idName).val(this.id);
		JsonError(divId);
		
		if(settings['expSelect'] == true){
			expSelect(this.id);
		}
		
	}))
	$('.clickTop-'+divId).live('click',(function(){
		$('#'+idName).val(this.id);
		JsonError(divId);
		
		if(settings['expSelect'] == true){
			val = this.title;
			$('.divApankAutocompleteTop, .divApankAutocompleteManual').empty();
			enterKey(val)
		}
		
	}))
}
	
function closeDiv(divId){
	$('#close-'+divId).live('click',(function(){
		JsonError(divId);
	}))
}
	
function JsonError(divId){
    $('#'+divId).empty();
}

function dateNow(){
	date = new Date();
	return date.toString('yyyy-MM-dd');
}
