/*
 * Forms
 *
 * 20081027
 * Eerste versie
 * gebaseerd op PrettyForms van Patrick Ryan http://www.agavegroup.com
 * 
 * Todo
 * DONE toevoegen functionaliteit .focus voor ie > fixFocus
 * DONE input text
 * DONE textarea
 * DONE select
 * DONE	img instelbaar via css door transparante afbeelding?
 * DONE radio
 * button
 * 
 * checkbox,radio,select label ook aanklikbaar maken
 * 
 * Remarks
 * labels werken niet bij checkbox etc
 * Geprobeerd met onChange event maar werkt niet in IE.
 * ? formulier doorzoeken naar labels > overeenkomstig element nakijken (checkbox, radio, etc ) > juiste toggle uitvoeren
 * Zie ook http://www.quirksmode.org/dom/usableforms.js
 * analoog met jQuery: http://www.whitespace-creative.com/jquery/jNice/
 * 
 */

/*************/
/* Variables */
/*************/
var transparentImage= "/site/images/transparent.gif";
var forms; //variabele om te wijzigen vormul

//the rest of the images are in the CSS

/*
 * Startfunctie
 */
function forms(){
	forms = getElementsByClassName(document,"form","form");
	for (var t=0; t<forms.length;t++){
        forms[t].className += " formJS"; //Voeg formJS toe als class
	    fixTextBoxes(forms[t]); // opmaak input>text,input>password
	    fixTextareas(forms[t]); // opmaak textarea
	    // fixSelects(forms[t]);
	    fixChecks(forms[t]); // opmaak checkbox
	    fixRadios(forms[t]);
	    fixButtons(forms[t]);
	}
}


//****
//**** functions that apply the look to the form elements
//****	


/*
 * this function is run for all form elements (except radio buttons)
 * this function accepts one element, and wraps it in four divs that are styled with shadows 
 */
function appendParentsTo(currItem,type){
    //create the divs
    tl = document.createElement("div");
    br = document.createElement("div");
    bl = document.createElement("div");
    tr = document.createElement("div");
    
    if (document.all) { //IE
        //give them the proper class
        tl.className = "frmBgTopLt "+type;
        br.className = "frmBgBottomRt "+type;
        bl.className = "frmBgBottomLt "+type;
        tr.className = "frmBgTopRt "+type;
        //insert the top level div
        t1 = currItem.insertAdjacentElement("BeforeBegin", tl);
    }
    else { //FFX
        //give them the proper class
        tl.setAttribute("class", "frmBgTopLt "+type);
        br.setAttribute("class", "frmBgBottomRt "+type);
        bl.setAttribute("class", "frmBgBottomLt "+type);
        tr.setAttribute("class", "frmBgTopRt "+type);
        inputParent = currItem.parentNode;
        //insert the top level div
        tl = inputParent.insertBefore(tl, currItem);
    }
    
    //append children
    br = tl.appendChild(br);
    bl = br.appendChild(bl);
    tr = bl.appendChild(tr);
    //move input to child of divs
    tr.appendChild(currItem);
}


//apply look to text boxes
// toegevoegd type password
function fixTextBoxes(theForm){
    inputs = theForm.getElementsByTagName("input");
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "text" || inputs[i].type == "password") {
			appendParentsTo(inputs[i],"bgText");
			fixFocus(inputs[i]); // base
        }
    }
}

//apply look to textareas
function fixTextareas(theForm){
    textareas = theForm.getElementsByTagName("textarea")
    for (i = 0; i < textareas.length; i++) {
        appendParentsTo(textareas[i],"bgTextarea");
		fixFocus(textareas[i]); // base
    }
}


//apply look to submit buttons
function fixButtons(theForm){
    inputs = theForm.getElementsByTagName("input");
    for (i = 0; i < inputs.length; i++) {
//        if (inputs[i].type == "submit") {
        if (/submit|button|reset/.test(inputs[i].type)) {
            appendParentsTo(inputs[i],"bgButton");
            //inputs[i].className += " frmButton";
        }
    }
}


//apply look to radio buttons
function fixRadios(theForm){
    inputs = theForm.getElementsByTagName("input");
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "radio") {
            lnk = document.createElement("a");
            //lnk.style.margin = "4px"; exported to css
            //lnk.className = "frmRadioReplace";
            img = document.createElement("img");
			img.src = transparentImage;
            if (inputs[i].checked == true) {
                lnk.className = "frmRadioReplace on";
            }
            else {
                lnk.className = "frmRadioReplace off";
            }
            
            //elements created, now pass functionality
            //give the checkbox an id if it doesn't have one
            if (inputs[i].id) {
                realId = inputs[i].id;
            }
            else {
                realId = "radio" + i;
                inputs[i].id = realId;
            }
            
            //give the fake check an id
            fakeId = "fake" + realId;
            lnk.id = fakeId
            
            lnk.href = "javascript:toggleRadio('" + realId + "','" + fakeId + "')";
            
            //insert the new image into the document
            if (document.all) { //IE
                lnk = inputs[i].insertAdjacentElement("BeforeBegin", lnk)
            }
            else {
                inputParent = inputs[i].parentNode;
                lnk = inputParent.insertBefore(lnk, inputs[i]);
            }
            lnk.appendChild(img);
            
            //remove the actual radio
            inputs[i].style.display = "none";
        }
    }
}



//apply look to check boxes
function fixChecks(theForm){
	//20090513 DIRK Gewijzigd omwille van conflict met $.beltrami()
	if($("form .bgCheckbox").length==0){
		inputs = theForm.getElementsByTagName("input");
		for (i = 0; i < inputs.length; i++) {
			if (inputs[i].type == "checkbox") {
				appendParentsTo(inputs[i],"bgCheckbox"); // background around checkbox
				//need to create an <a> element AND an <img> element because IE won't happily put an onclick on the img alone
				lnk = document.createElement("a");
				img = document.createElement("img");
				img.src = transparentImage;
				if (inputs[i].checked == true) {
					lnk.className = "frmCheckboxReplace on";
				}
				else {
					lnk.className = "frmCheckboxReplace off";
				}
			   
				//elements created, now pass functionality
				//give the checkbox an id if it doesn't have one
				if (inputs[i].id) {
					realId = inputs[i].id;
				}
				else {
					realId = "check" + i;
					inputs[i].id = realId;
				}
				
				//give the fake check an id
				fakeId = "fake" + realId;
				lnk.id = fakeId
				
				lnk.href = "javascript:toggleCheck('" + realId + "','" + fakeId + "')";
				
				
				//insert the new link into the document
				if (document.all) { //IE
					lnk = inputs[i].insertAdjacentElement("BeforeBegin", lnk)
				}
				else {
					inputParent = inputs[i].parentNode;
					lnk = inputParent.insertBefore(lnk, inputs[i]);
				}
				lnk.appendChild(img);
				
				//remove the actual checkbox
				inputs[i].style.display = "none";
				
	
			}
		}
	}

}

//apply look to select boxes
function fixSelects(theForm){
    selects = theForm.getElementsByTagName("select")
    for (i = 0; i < selects.length; i++) {
        //create the standard shadows
        appendParentsTo(selects[i],"bgSelect");
        
        //give this thing an id if it doesn't have one
        if (selects[i].id == "") {
            selects[i].id = "dynId" + i;
        }
        
        //create new div to hold list
        //this is a wrapper div to hold everything together
        fakeSelectWrapper = document.createElement("div");
        fakeSelectWrapper.className ="frmSelectWrapper";
//		fakeSelectWrapper.style.width = selects[i].clientWidth + "px";
		fakeSelectWrapper.style.zIndex = 100-i; /* nodig om stacking probleem in ie op te lossen */
        
        //this is the link that holds the select's drop down arrow
        fakeSelectBtn = document.createElement("a")
		fakeSelectBtn.className = "frmSelectBtn"; // classname for dropdown button
        
        if (document.all) { //IE

        
			// Dropdownknop
			//nog nakijken > functie??
            fakeSelectBtn.href = "javascript:toggleDropdown(\"frmSelectDropdown"+selects[i].id+ i + "\")"; 
            fakeSelectBtn.innerHTML = "<img src=\"" + transparentImage + "\" />"; // set transparent image as link, button > backgroundimage
            
			//a element dat huidige selectie toont 
            fakeSelectedHolder = document.createElement("a");
            fakeSelectedHolder.className = "frmSelectSelected";
            fakeSelectedHolder.id = "frmSelectSelected" + i; //i = verwijzing naar select[]
//            fakeSelectedHolder.style.width = selects[i].clientWidth - 20 + "px"; // breedte instellen op breedte van origineel formulier element
            // nog nakijken > functie??
            fakeSelectedHolder.href = "javascript:toggleDropdown(\"frmShdwMenu" + i + "\", \"frmSelectSelected" + i + "\",\"" + selects[i].id + "\")"; // Wanneer klik op item> moet ook opengaan
			
			// Dropdownlijst
            // this is the div that actually contains the list of options
            fakeSelect = document.createElement("div");
            fakeSelect.id = "frmSelectDropdown"+selects[i].id + i;
            fakeSelect.className = "frmSelectDropdown";
//			fakeSelect.style.width = selects[i].clientWidth  + "px";
			//Haal options uit select
            options = selects[i].getElementsByTagName("option");
            //Doorloop options en plak ze als koppelingen in div container
            for (j = 0; j < options.length; j++) {
                //create a tag for each element, and append it to the parent div
                fakeOption = document.createElement("a")
                fakeOption.innerHTML = options[j].innerHTML;
//                fakeOption.style.width = selects[i].clientWidth - 16 + "px"; // zelfde breedte als oorspronkelijk element
                // nog nakijken > functie
                fakeOption.href = 'javascript:chooseSelect("' + selects[i].id + '",' + j + ',"frmSelectDropdown'+selects[i].id + i + '", "frmSelectSelected' + i + '")'
                fakeSelect.appendChild(fakeOption); //plak aan div element
                //set the default text to show
                if (options[j].selected == true) {
					// Indien dit element geselecteerd was > plak dit in geselecteerd element
                    fakeSelectedHolder.innerHTML = options[j].innerHTML;
                    fakeOption.className = "selected"; // weergave selected
                }
            }
            
            //construct the menu parts Wrapper around list of options and image
            fakeSelectWrapper.appendChild(fakeSelectedHolder); // huidig item
            fakeSelectWrapper.appendChild(fakeSelectBtn); //knop
            fakeSelectWrapper.appendChild(fakeSelect); // dropdownlijst

            
            //now put the new div inside the shadows, above the select box
            selectParent = selects[i].parentNode;
            
            
            // more crazy IE stuff : push the dropped down menu to the left where it belongs
            //fakeSelect.style.margin = "3px 3px 3px -" + (selects[i].clientWidth - 5) + "px"; //uitgeschakeld > op te lossen met position absolute
            
            // element toevoegen voor select element
            fakeSelectWrapper = selects[i].insertAdjacentElement("BeforeBegin", fakeSelectWrapper)
            //hide the real select box
            selects[i].style.display = "none";            
        }
        else {
			//Dropdownknop
            fakeSelectBtn.setAttribute("href", "javascript:toggleDropdown(\"frmSelectDropdown"+selects[i].id + i + "\")");
            fakeSelectBtn.innerHTML = "<img class=\"fakeSelectImg\" src=\"" + transparentImage + "\" />";

			//a element dat huidige selectie toont 
            fakeSelectedHolder = document.createElement("a");
            fakeSelectedHolder.setAttribute("class", "frmSelectSelected");
            fakeSelectedHolder.setAttribute("id", "frmSelectSelected" + i);
//            fakeSelectedHolder.style.width = selects[i].clientWidth - 15 + "px";
            fakeSelectedHolder.setAttribute("href", "javascript:toggleDropdown(\"frmSelectDropdown"+selects[i].id + i + "\", \"frmSelectSelected" + i + "\",\"" + selects[i].id + "\")");
			
			//Dropdownlijst
            //this is the div that actually contains the list of options
            fakeSelect = document.createElement("div");
            fakeSelect.setAttribute("id", "frmSelectDropdown"+selects[i].id + i);
            fakeSelect.setAttribute("class", "frmSelectDropdown");
            options = selects[i].getElementsByTagName("option");
            
            
            for (j = 0; j < options.length; j++) {
                //create a p tag for each element, and append it to the parent div
                fakeOption = document.createElement("a")
                fakeOption.innerHTML = options[j].innerHTML;
                fakeOption.setAttribute("href", "javascript:chooseSelect(\"" + selects[i].id + "\"," + j + ",\"frmSelectDropdown"+selects[i].id + i + "\", \"frmSelectSelected" + i + "\")"); //clicking calls the function chooseSelect passing the select object, and the chosen index
                fakeSelect.appendChild(fakeOption);
                
                //set the default text to show
                if (options[j].selected == true) {
                    fakeSelectedHolder.innerHTML = options[j].innerHTML;
                    fakeOption.setAttribute("class", "selected");
                }
            }
            
            //construct the menu parts Wrapper around list of options and image
            fakeSelectWrapper.appendChild(fakeSelectedHolder);
            fakeSelectWrapper.appendChild(fakeSelectBtn);
            fakeSelectWrapper.appendChild(fakeSelect);
            
            //now put the new div inside the shadows, above the select box
            selectParent = selects[i].parentNode;
//           	fakeSelect.style.width = selects[i].clientWidth  + "px";
            fakeSelectWrapper = selectParent.insertBefore(fakeSelectWrapper, selects[i]);
            //hide the real select box
            selects[i].style.display = "none";
        }
    }
}






//****
//**** functions that apply the functionality to the form elements
//****		

//function runs when a radio button is clicked
function toggleRadio(realRadioId, fakeRadioId){
    realRadio = document.getElementById(realRadioId);
    fakeRadio = document.getElementById(fakeRadioId);
    //want to ONLY look in the correct form, so get this radio button's parent form (supports multiple forms)
    radioForm = realRadio.parentNode;
    tmpCnt = 1;
    while (radioForm.tagName != "FORM") {
		//look for first parent node FORM
        radioForm = radioForm.parentNode;
        tmpCnt++;
        if (tmpCnt > 50) {
            window.alert("encountered javascript error\n[parentNode]")
            break;
        }
    }
    inputs = radioForm.getElementsByTagName("input");
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type == "radio") {
            //IDs look like this:  realId: blah    fakeId: fakeblah
            if (inputs[i].name == realRadio.name) { //is part of the same radio group, uncheck it.
                inputs[i].checked = false; //uncheck the actual button
                document.getElementById("fake" + inputs[i].id).className = document.getElementById("fake" + inputs[i].id).className.replace("on","off");
                if (inputs[i].id == realRadioId) {
                    inputs[i].checked = true; //check the actual button
                document.getElementById("fake" + inputs[i].id).className = document.getElementById("fake" + inputs[i].id).className.replace("off","on");
                }
            }
        }
    }
    
    //**** EVENT HANDLING
    // Clicking the radiobutton equivalent to the button's onClick event and onChange event . fire it.
    triggerEvent(realRadio, "change");
    triggerEvent(realRadio, "click");
}


//this function handles the actual check box handling
function toggleCheck(realCheckId, fakeCheckId){
    fakeCheck = document.getElementById(fakeCheckId);
    realCheck = document.getElementById(realCheckId);
    if (fakeCheck.className.indexOf("on") != -1) {
        fakeCheck.className  = fakeCheck.className.replace("on","off");
		realCheck.checked = false;
    }
    else {
         fakeCheck.className  = fakeCheck.className.replace("off","on");
		 realCheck.checked = true;
   }
   
   $("#" + realCheckId).trigger("click");

    //**** EVENT HANDLING
    // Clicking the box equivalent to the box's onClick event and onChange event . fire it.
    //triggerEvent(realCheck, "change");
    //NOTE cannot use click event on checkbox - it causes bubbling (that cannot be prevented:mozilla bug?) and the change event gets fired multiple times

}


//function runs when drop down arrow next to select box is clicked
function toggleDropdown(menuId){
	//alert(document.getElementById(menuId).style.display);
    document.getElementById(menuId).style.display = document.getElementById(menuId).style.display=="block"?"none":"block";
}

//function runs when a drop down item is clicked
function chooseSelect(chosenSelect, chosenIndex, menuId, chosenMenuId){

    realDropdown = document.getElementById(chosenSelect);
    fakeDropDown = document.getElementById(menuId);
    fakeChosenItem = document.getElementById(chosenMenuId)
    //set the chosen item to be selected in the REAL drop down		
    currSelect = realDropdown.selectedIndex = chosenIndex;
    
    //put the chosen text into the display div
    //for some reason setting innerHTML breaks in IE
    fakeChosenItem.childNodes[0].nodeValue = realDropdown[chosenIndex].innerHTML;
    
    //deselect all the items under the dropdown
    fakeOptions = fakeDropDown.getElementsByTagName("a");
    
    for (i = 0; i < fakeOptions.length; i++) {
        fakeOptions[i].className = "";
        //if this is the selected item, set to selected
        if (fakeOptions[i].innerHTML == realDropdown[chosenIndex].innerHTML) {
            fakeOptions[i].className = "selected";
        }
    }
    
    //hide the rest of the dropdown
    toggleDropdown(menuId);
	
	$("#" + chosenSelect).trigger("change");    
}




//function to trigger events that are built into the form elements that have been hidden
function triggerEvent(obj, evt){
    if (document.all) {
        if (evt == "click") {
            res = obj.fireEvent("onclick");
        }
        else 
            if (evt == "change") {
                res = obj.fireEvent("onchange");
            }
    }
    else {
        //NOTE - in the mozilla event model, I am cancelling the bubbleUp!  (1st false)
        // this is needed to prevent odd interaction, but could cause other issues!
        if (evt == "click") {
            mouseEvent = document.createEvent('MouseEvents');
            mouseEvent.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
            obj.dispatchEvent(mouseEvent);
        }
        else 
            if (evt == "change") {
                mouseEvent = document.createEvent('HTMLEvents');
                mouseEvent.initEvent('change', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
                obj.dispatchEvent(mouseEvent);
            }
    }
}

/**** Start script *****/
addLoadEvent(forms);
