var combo_suggest_selectBoxIds = 0;
var combo_suggest_currentlyOpenedOptionBox = false;
var combo_suggest_editableSelect_activeArrow = false;
/* Preload images*/
var img_combo_suggest_arrowImage=new Image();
img_combo_suggest_arrowImage.src=combo_suggest_arrowImage;
var img_combo_suggest_arrowImageOver=new Image();
img_combo_suggest_arrowImageOver.src=combo_suggest_arrowImageOver;
var img_combo_suggest_arrowImageDown=new Image();
img_combo_suggest_arrowImageDown.src=combo_suggest_arrowImageDown;


function comboSuggest_setup(baseId, suggestionArray){
	var mainDiv = document.getElementById(baseId+combo_suggest_BOX_ID);
	var optionDiv = document.getElementById(baseId+ combo_suggest_SELECT_BOX_ID);
	mainDiv.style.zIndex = 250 - combo_suggest_selectBoxIds;
	combo_suggest_selectBoxIds = combo_suggest_selectBoxIds + 1;
	var inputElement = document.getElementById(baseId);
	inputElement.suggestionArray = suggestionArray;
	combo_suggest_filter(inputElement, baseId);
		
}

       
function comboSuggest_forceHideOptions(){
	if(combo_suggest_editableSelect_activeArrow)combo_suggest_editableSelect_activeArrow.src = img_combo_suggest_arrowImage.src;
	if(combo_suggest_currentlyOpenedOptionBox){
		combo_suggest_currentlyOpenedOptionBox.style.display='none';   
		if(navigator.userAgent.indexOf('MSIE')>=0)document.getElementById(combo_suggest_currentlyOpenedOptionBox.id.replace(combo_suggest_SELECT_BOX_ID,combo_suggest_IFRAME_ID)).style.display='none';
	}
	combo_suggest_currentlyOpenedOptionBox=false;
}



function comboSuggest_showOrHideOptions(img,optionDivId, iframeId, onlyShow){
	if(combo_suggest_editableSelect_activeArrow && combo_suggest_editableSelect_activeArrow!=img){
		combo_suggest_editableSelect_activeArrow.src = img_combo_suggest_arrowImage.src;
	}
	combo_suggest_editableSelect_activeArrow = img;
	var optionDiv = document.getElementById(optionDivId);
	if(optionDiv.style.display=='block' && !onlyShow){
		optionDiv.style.display='none';
		if(navigator.userAgent.indexOf('MSIE')>=0)document.getElementById(iframeId).style.display='none';
		img.src = img_combo_suggest_arrowImage.src;  
	}else{   
		optionDiv.style.display='block';
		if(navigator.userAgent.indexOf('MSIE')>=0){
			var iframe = document.getElementById(iframeId);
			iframe.style.display='block';
			var mainDiv = document.getElementById(iframeId.replace(combo_suggest_IFRAME_ID,combo_suggest_BOX_ID));
			var heightCalculated = optionDiv.offsetHeight + mainDiv.offsetHeight;
			iframe.style.height = heightCalculated+ 'px';		
		}
		img.src=img_combo_suggest_arrowImageDown.src;  
		if(combo_suggest_currentlyOpenedOptionBox && combo_suggest_currentlyOpenedOptionBox!=optionDiv){
			combo_suggest_currentlyOpenedOptionBox.style.display='none';   
			if(navigator.userAgent.indexOf('MSIE')>=0)document.getElementById(combo_suggest_currentlyOpenedOptionBox.id.replace(combo_suggest_SELECT_BOX_ID,combo_suggest_IFRAME_ID)).style.display='none';
		}
		combo_suggest_currentlyOpenedOptionBox= optionDiv;
		
	}
	
}
function comboSuggest_switchImageUrl(img){
	if(img.src.indexOf(combo_suggest_arrowImage) >= 0){
		img.src = img_combo_suggest_arrowImageOver.src; 
	}else if (img.src.indexOf(combo_suggest_arrowImageOver) >= 0){
		img.src = img_combo_suggest_arrowImage.src;
	}
}


function comboSuggest_highlightSelectBoxOption(){	

	var optionDivOpened = combo_suggest_currentlyOpenedOptionBox;
	if (optionDivOpened.optionAvailable){
		var optionsArray = optionDivOpened.optionAvailable;
		var optionsSelectedFound = false;
		for (var i = 0; (i < optionsArray.length) && !optionsSelectedFound ; i++){
			var currentOption = optionsArray[i];
			if (currentOption.combo_suggest_isSelected){
				currentOption.style.backgroundColor='';
				currentOption.style.color='';
				currentOption.combo_suggest_isSelected=false;
				optionsSelectedFound=true;
			}
		}
	}
	
	this.style.backgroundColor=combo_suggest_activeBackgroundColor;
	this.style.color=combo_suggest_activeColor;			
	this.combo_suggest_isSelected=true;
		
}

function combo_suggest_keyPressed(event,inputElem, baseId){
	
	if (event.keyCode == 40 || event.keyCode == 38){ //arrow
		combo_suggest_manageArrowPressed(event,inputElem, baseId);
	}	
	
}

function combo_suggest_keyUp(event,inputElem, baseId){
	if (event.keyCode != 40 && event.keyCode != 39 &&event.keyCode != 38 && event.keyCode != 37 && event.keyCode != 13 && event.keyCode != 15){ //arrow, return , tabs manage in the keypressed method
		combo_suggest_filter(inputElem, baseId);
		var img = document.getElementById(baseId+combo_suggest_IMAGE_ID);
		comboSuggest_showOrHideOptions(img, baseId+combo_suggest_SELECT_BOX_ID, baseId+combo_suggest_IFRAME_ID,true);
		
	}
}

function combo_suggest_keyDown(event,inputElem, baseId){
  if (event.keyCode == 13 || event.keyCode == 9){ //return or tab pressed -> if combo open -> don't submit the form and take the selected option
		if (combo_suggest_currentlyOpenedOptionBox && combo_suggest_currentlyOpenedOptionBox.id.search(baseId) != -1){
			if (combo_suggest_currentlyOpenedOptionBox.optionAvailable){
				var optionsArray = combo_suggest_currentlyOpenedOptionBox.optionAvailable;
				var optionsSelectedFound = false;
				for (var i = 0; (i < optionsArray.length) && !optionsSelectedFound ; i++){
					var currentOption = optionsArray[i];
					if (currentOption.combo_suggest_isSelected){
						inputElem.value = currentOption.innerHTML;
						optionsSelectedFound=true;						
					}
				}
			}
			comboSuggest_forceHideOptions();
			combo_suggest_filter(inputElem, baseId);
			if (event.keyCode == 13){
				return false; //stop the submit of the form
			}
		}
  }
  if(navigator.userAgent.indexOf('MSIE')>=0) combo_suggest_keyPressed(event,inputElem, baseId); //IE doesn't manage onkeypress with non-alphanumerical key...
  
  return true;
}

function combo_suggest_manageArrowPressed(event,inputElem, baseId){
	var img = document.getElementById(baseId+combo_suggest_IMAGE_ID);
	comboSuggest_showOrHideOptions(img, baseId+combo_suggest_SELECT_BOX_ID, baseId+combo_suggest_IFRAME_ID,true);
	var optionDivOpened = combo_suggest_currentlyOpenedOptionBox;
	if (optionDivOpened.optionAvailable){
		var optionsArray = optionDivOpened.optionAvailable;
		var optionsSelectedFound = false;
		for (var i = 0; (i < optionsArray.length) && !optionsSelectedFound ; i++){
			var currentOption = optionsArray[i];
			if (currentOption.combo_suggest_isSelected){
				currentOption.style.backgroundColor='';
				currentOption.style.color='';
				currentOption.combo_suggest_isSelected=false;
				var j = 0;
				if ((i<(optionsArray.length-1)) && event.keyCode == 40){
					j = i+1; //if exist select the next option					
				}else if (event.keyCode == 38){
					if (i > 0)	j = i-1; //if exist select the previous option
					else j = optionsArray.length-1;
				}
				//manage the scrollbar to ensure that the selected component is showed
				combo_suggest_manageScrollBar(optionDivOpened, optionsArray[j]);
				optionsArray[j].style.backgroundColor=combo_suggest_activeBackgroundColor;
				optionsArray[j].style.color=combo_suggest_activeColor;
				optionsArray[j].combo_suggest_isSelected=true;			
				optionsSelectedFound = true;
			}
		}
		if ( !optionsSelectedFound  && optionsArray.length>1){//select the first by default if it exist
			optionsArray[0].style.backgroundColor=combo_suggest_activeBackgroundColor;
			optionsArray[0].style.color=combo_suggest_activeColor;
			optionsArray[0].combo_suggest_isSelected=true;
		}
		
		
	}
	
}

function combo_suggest_manageScrollBar(selectBox, selectedOption){
	var selectBoxHeigth = parseInt(selectBox.style.height);
	if (selectedOption.offsetTop < selectBox.scrollTop) {
		selectBox.scrollTop =selectedOption.offsetTop;
	}else if (selectedOption.offsetTop+selectedOption.clientHeight > selectBox.scrollTop+selectBoxHeigth) {
		selectBox.scrollTop =selectedOption.offsetTop+selectedOption.clientHeight-selectBoxHeigth;
	}
	
}

function combo_suggest_filter(inputElem, baseId){
	var filter = inputElem.value;
	var isMatched = function(x) {   
		var myFilter = new RegExp("^"+filter.toUpperCase().trim());
		return myFilter.test(String(x).toUpperCase());
	}

	var filteredArray = inputElem.suggestionArray.filter(isMatched);
	combo_suggest_createList(filteredArray, baseId);	
}


function combo_suggest_createList(suggestionArray, baseId){
	var optionDiv = document.getElementById(baseId+ combo_suggest_SELECT_BOX_ID);
	optionDiv.innerHTML = '';
	var optionAvailable = new Array();
	var isFirst = true;
	for(var i=0;i<suggestionArray.length;i++){
		var anOption = document.createElement('DIV');
		anOption.id=baseId+"combo_box_option"+i;
		anOption.innerHTML = suggestionArray[i];
		anOption.className=combo_suggest_SELECT_OPTION_CLASS;
		anOption.style.width = optionDiv.style.width.replace('px','') - 20 + 'px'; 
		anOption.onclick = comboSuggest_selectOptionValue;
		anOption.style.Height="20px";
		anOption.onmouseover = comboSuggest_highlightSelectBoxOption;		
		anOption.myBaseId=baseId;//need to stock the property to retrieve it in the onclick and onmouseover
		if (!isFirst){
			anOption.combo_suggest_isSelected=false;			
		}else{
			anOption.combo_suggest_isSelected=true;
			anOption.style.backgroundColor=combo_suggest_activeBackgroundColor;
			anOption.style.color=combo_suggest_activeColor;			
			isFirst=false;
		}
		optionAvailable[i]=anOption;
		optionDiv.appendChild(anOption);	
	}
	//calculate the heigth of the selectBox
	optionDiv.optionAvailable = optionAvailable;
	var optionDivHeight = 40;
	if (optionAvailable.length > 0 && optionAvailable.length <= 10) {
			optionDivHeight = optionAvailable.length*20 + 20;
	}else if (optionAvailable.length > 10) {
			optionDivHeight= 220;
	}
	optionDiv.style.height = optionDivHeight+"px";
	
	
	
	// change the height of the iframe
	if(navigator.userAgent.indexOf('MSIE')>=0){
		var iframe =  document.getElementById(baseId+combo_suggest_IFRAME_ID);
		var mainDiv = document.getElementById(baseId+combo_suggest_BOX_ID);
		if (!iframe){//iframe doesn't exist create it
			iframe = document.createElement('<IFRAME src=\"about:blank\" frameborder=0>');
			iframe.style.width = optionDiv.style.width;
			iframe.style.display=optionDiv.style.display;
			iframe.className="jsfsdc-ComboSuggestIframe";
			iframe.id = baseId+combo_suggest_IFRAME_ID;
			iframe.style.zIndex = -1;
			mainDiv.appendChild(iframe); 
		}
		var heightCalculated = optionDiv.offsetHeight + mainDiv.offsetHeight;
		iframe.style.height = heightCalculated+ 'px';
		
	}
	
		
}

function comboSuggest_selectOptionValue(){
    var textInput = document.getElementById(this.myBaseId);
    textInput.value = this.innerHTML;
    comboSuggest_forceHideOptions();
    combo_suggest_filter(textInput, textInput.id);
}


//hide options when the user click outside the component
document.onclick = function (e) {
	e = e || window.event;   
	var element = e.target || e.srcElement; 
	if(combo_suggest_currentlyOpenedOptionBox){
		var baseId = combo_suggest_currentlyOpenedOptionBox.id.replace(combo_suggest_SELECT_BOX_ID, '');
		if (element.id.search(baseId) == -1) {     
			comboSuggest_forceHideOptions();   
		}
	}
};


//ensure filter method exist on array
if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}

// ensure trim method exist on string
if (!String.prototype.trim)
{
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};
}



