/*#############################################################
Name: Niceforms
Version: 0.9
Author: Lucian Slatineanu
URL: http://www.badboy.ro/

Feel free to use and modify but please provide credits.
#############################################################*/

//global variables that can be used by all the functions on this page.
var selects;
var TabOptionsDiv = new Array();

//this function runs when the page is loaded so put all your other onload stuff in here too.
function initNiceForms() {
	replaceSelects();
}

function replaceSelects() {
	//get all the select fields on the page
    selects = document.getElementsByTagName('select');
	
	//cycle trough the select fields
    for(var i=0; i < selects.length; i++){
        replace_one_select(selects[i]);
	}
}

function replace_one_select(the_select){
		
        // retrieve offsetWidth before hidding the select
		var widthSelect = the_select.offsetWidth;
		
		var selectArea = createDivStructure(the_select,widthSelect);

		//hide the select field
        the_select.style.display='none';
		
		//insert select div
		the_select.parentNode.insertBefore(selectArea, the_select);
		
		//build & place options div
		addOptionsDiv(selectArea,the_select,widthSelect);
		
}


function replace_selectArea(the_select){
        
		//what is the row of this select inside the selects-collection?
	    var i=0;
	    for(var i=0; i < selects.length; i++){
           if(selects[i]==the_select){break;};
	    }
        
		
		//delete former selectArea and former optionsDiv 
		var  selectArea_id = "selectArea"+i;
		var former_selectArea =  document.getElementById(selectArea_id); // a smartest way to do it : "var former_selectArea = the_select.previousSibling;" ?? 

        var  optionsDiv_id = "optionsDiv"+i;
		var former_optionsDiv =  document.getElementById(optionsDiv_id);

		former_optionsDiv.parentNode.removeChild(former_optionsDiv);

		former_selectArea.parentNode.removeChild(former_selectArea);

		// to retrieve offsetWidth, the "display none" attribute has to be remove (without showing the select)
		the_select.style.visibility = 'hidden';
		the_select.style.display='block';
		var widthSelect = the_select.offsetWidth;
		the_select.style.display='none';
	    the_select.style.visibility = 'visible';


        var new_selectArea = createDivStructure(the_select,widthSelect);
		//insert select div
		the_select.parentNode.insertBefore(new_selectArea,the_select);
		//build & place options div
		addOptionsDiv(new_selectArea,the_select,widthSelect);

		
}


function createDivStructure(the_select,widthSelect){
     //what is the row of this select inside the selects-collection?
	 var i=0;
	 for(var i=0; i < selects.length; i++){
        if(selects[i]==the_select){break;};
	    }
		
	 //create and build div structure
		var selectArea = document.createElement('div');
		selectArea.style.width = widthSelect + 'px';
		
		var left = document.createElement('div');
		var right = document.createElement('div');
		var center = document.createElement('div');
		var button = document.createElement('a');
		var text = document.createTextNode('');
		center.id = "mySelectText"+i;
		center.i = i;
		center.onclick = function() { showOptions(this.i); }
		center.style.cursor = 'pointer';
		
		button.href="javascript:showOptions("+i+")";
		selectArea.className = "selectArea";
		selectArea.id = "selectArea"+i;
		left.className = "left";
		right.className = "right";
		center.className = "center";
		
		center.style.width = widthSelect - 4 - 1 - 15 + 'px';
		right.appendChild(button);
		center.appendChild(text);
		selectArea.appendChild(left);
		selectArea.appendChild(right);
		selectArea.appendChild(center);
     return selectArea; 
}




function addOptionsDiv(selectArea,the_select,widthSelect){    
	 //what is the row of this select among the selects-collection?
	 var i=0;
	 for(var i=0; i < selects.length; i++){
        if(selects[i]==the_select){break;};
	    }
		

	//build & place options div
		var optionsDiv = document.createElement('div');
		optionsDiv.className = "optionsDivInvisible";
		optionsDiv.id = "optionsDiv"+i;
		optionsDiv.style.left = findPosX(selectArea) + 'px';
		optionsDiv.style.top = findPosY(selectArea) + 16 + 'px';
		optionsDiv.style.width = widthSelect - 6 +  'px';
		
		TabOptionsDiv.push(
			new Array ( optionsDiv.id, "selectArea"+i )
		);
		
	//get select's options and add to options div
		var OnchangeFunc = "";
		var First = "";
		var optionDefaultSelected = "";
		
		for(var j=0; j < the_select.options.length; j++) {
			var optionHolder = document.createElement('p');
			var optionLink = document.createElement('a');
			var optionTxt = document.createTextNode(selects[i].options[j].text);
			
			if(the_select.options[j].value != "null") {
				if(selects[i].onchange) {
					OnchangeFunc = selects[i].onchange.toString();
					OnchangeFunc = OnchangeFunc.replace(/function (.*)\((.*)\)/,"");
					OnchangeFunc = OnchangeFunc.replace(/\{/,"");
					OnchangeFunc = OnchangeFunc.replace(/\}/,"");
					// 19 oct 2006 : Bypass of the (strange) line below (to avoid the change of the parameters of the function wich was in the onChange)
					// OnchangeFunc = OnchangeFunc.replace(/\(.*\)/,"("+the_select.options[j].value+")");
					
					if(j == 0)
						First = OnchangeFunc;
			   }
			}
			
			optionLink.href = "javascript:showOptions("+i+");selectMe('"+the_select.id+"',"+j+","+i+");"+OnchangeFunc;
			optionLink.appendChild(optionTxt);
			optionHolder.appendChild(optionLink);
			optionsDiv.appendChild(optionHolder);
			
			if(the_select.options[j].defaultSelected)
				var optionDefaultSelected = j;
		}
		
		// Default selected
		
		/*
		// Si on veut que le onchange s'active au onload
		if(selects[i].onchange && OnchangeFunc != "" && First != "") {
			selects[i].onchange();
			selectMe(selects[i].id,selects[i].options[selects[i].selectedIndex].value,i);
			//selectMe(selects[i].id,selects[i].selectedIndex,i);
		} else if(optionDefaultSelected != "") {*/
		
		if(optionDefaultSelected != "") {
			selectMe(the_select.id,optionDefaultSelected,i);
		} else {
			selectMe(the_select.id,0,i);
		}
		
		optionsDiv.onmouseover = function() {
			this.className="optionsDivVisible";
			CountOverlay = 1;
		}
		
		//insert options div
		document.getElementsByTagName("body")[0].appendChild(optionsDiv);
}




function ResizeSelects() {
	for(i=0; i<TabOptionsDiv.length; i++) {
		document.getElementById(TabOptionsDiv[i][0]).style.left = findPosX(document.getElementById(TabOptionsDiv[i][1])) + 'px';
		document.getElementById(TabOptionsDiv[i][0]).style.top = findPosY(document.getElementById(TabOptionsDiv[i][1])) + 16 + 'px';
	}
}



function showOptions(g) {
	
    ResizeSelects();   // correction (4 sept 2008), mauvais positionement des options 

	elem = document.getElementById("optionsDiv"+g);
	if(elem.className=="optionsDivInvisible") { elem.className = "optionsDivVisible"; }
	else if(elem.className=="optionsDivVisible") { elem.className = "optionsDivInvisible"; }
	
	WindowHeight = getWindowHeight();
	
	if( (!document.getElementById("overlayNiceForms")) ) {
		insertHtmlAfter(document.getElementsByTagName("div")[0],'<div id="overlayNiceForms" onmouseover="javascript:HideOverlayNiceForms('+g+',\'over\');" onclick="javascript:HideOverlayNiceForms('+g+',\'click\');" style="height:'+WindowHeight+'px;"></div>');
	} else {
		removeHtml(document.getElementById("overlayNiceForms"));
		insertHtmlAfter(document.getElementsByTagName("div")[0],'<div id="overlayNiceForms" onmouseover="javascript:HideOverlayNiceForms('+g+',\'over\');" onclick="javascript:HideOverlayNiceForms('+g+',\'click\');" style="height:'+WindowHeight+'px;"></div>');
	}
}

CountOverlay = 0;
function HideOverlayNiceForms(g,action) {
	elem = document.getElementById("optionsDiv"+g);
	
	if(CountOverlay == 1 || action == "click") {
		document.getElementById("overlayNiceForms").style.display = 'none';
		elem.className='optionsDivInvisible';
		CountOverlay = 0;
	}
}


function selectMe(selectFieldId,linkNo,selectNo) {
	//feed selected option to the actual select field
	selectField = document.getElementById(selectFieldId);
	for(var k = 0; k < selectField.options.length; k++) {
		if(k == linkNo)
			selectField.options[k].selected = "selected";
		else
			selectField.options[k].selected = "";
	}
	//show selected option
	textVar = document.getElementById("mySelectText"+selectNo);
	var newText = document.createTextNode(selectField.options[linkNo].text);
	textVar.replaceChild(newText, textVar.childNodes[0]);
	
	if(document.getElementById("overlayNiceForms")) {
		document.getElementById("overlayNiceForms").style.display = 'none';
		CountOverlay = 0;
	}
}

function findPosY(obj) {
	var posTop = 0;
	while (obj.offsetParent) {
		posTop += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return posTop;
}
function findPosX(obj) {
	var posLeft = 0;
	while (obj.offsetParent) {
		posLeft += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return posLeft;
}

// addLoadEvent(initNiceForms); // Replace select/radio/checkbox
function try_initNiceForms(){
    try{ 
    	initNiceForms(); 
    } catch(err){ 
		var text= document.createTextNode('<!--  Erreur js (initNiceForms)'+err+'  -->');
		document.body.appendChild(text);
		// alert('Erreur JS (initNiceForms): '+err); 
		}
}
addLoadEvent(try_initNiceForms); // Replace select/radio/checkbox !!! avec traitement des erreurs  !!! 




addResizeEvent(ResizeSelects); // Move select/radio/checkbox