/*******************
Author: Patrick Ryan
URL: http://www.agavegroup.com

Feel free to use this however you like.  Credit is always appreciated.
*******************/

//need to set a couple of images here:
imagePath="/fileadmin/template/images/forms/";
widthSelectDrop=14;
widthSelectDefault=186;

//the rest of the images are in the CSS

function prettyForms(){
	fixTextareas();
	fixSelects();
	fixInputs();
}


//****
//**** 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 appendFormDivs(currItem){
	//create the divs
	all=document.createElement('table');
	allt=document.createElement('tbody');
	rowt=document.createElement('tr');
	rowm=document.createElement('tr');
	rowb=document.createElement('tr');
	lt=document.createElement('td');
	t=document.createElement('td');
	rt=document.createElement('td');
	l=document.createElement('td');
	c=document.createElement('td');
	r=document.createElement('td');
	lb=document.createElement('td');
	b=document.createElement('td');
	rb=document.createElement('td');

	if(document.all){							//IE
		//give them the proper class
		all.className="Form Form"+currItem.type;
		if(currItem.id) all.id="Form_"+currItem.id;
		lt.className="FormLT";
		t.className="FormT";
		rt.className="FormRT";
		l.className="FormL";
		c.className="FormC";
		r.className="FormR";
		lb.className="FormLB";
		b.className="FormB";
		rb.className="FormRB";
		//insert the top level div
		currItem.insertAdjacentElement("BeforeBegin",all);
	}else{										//FFX
		//give them the proper class
		all.setAttribute("class", "Form Form"+currItem.type);
		if(currItem.id) all.setAttribute("id", "Form_"+currItem.id);
		lt.setAttribute("class", "FormLT");
		t.setAttribute("class", "FormT");
		rt.setAttribute("class", "FormRT");
		l.setAttribute("class", "FormL");
		c.setAttribute("class", "FormC");
		r.setAttribute("class", "FormR");
		lb.setAttribute("class", "FormLB");
		b.setAttribute("class", "FormB");
		rb.setAttribute("class", "FormRB");
		inputParent = currItem.parentNode;
		//insert the top level div
		inputParent.insertBefore(all,currItem);
	}
	
	//append children
	c.appendChild(currItem)
	rowt.appendChild(lt);
	rowt.appendChild(t);
	rowt.appendChild(rt);
	rowm.appendChild(l);
	rowm.appendChild(c);
	rowm.appendChild(r);
	rowb.appendChild(lb);
	rowb.appendChild(b);
	rowb.appendChild(rb);
	allt.appendChild(rowt);
	allt.appendChild(rowm);
	allt.appendChild(rowb);
	all.appendChild(allt);
}

function appendFormFDivs(currItem){
	//create the divs
	all = document.createElement("div");
	l = document.createElement("div");
	r = document.createElement("div");

	if(document.all){							//IE
		//give them the proper class
		all.className="FormF Form"+currItem.type;
		if(currItem.id) all.id="Form_"+currItem.id;
		l.className="FormFL";
		currItem.className+=" FormFM";
		r.className="FormFR";
		//insert the top level div
		currItem.insertAdjacentElement("BeforeBegin",all);
	}else{										//FFX
		//give them the proper class
		all.setAttribute("class", "FormF Form"+currItem.type);
		if(currItem.id) all.setAttribute("id", "Form_"+currItem.id);
		l.setAttribute("class", "FormFL");
		//currItem.setAttribute("class", "FormFM");
		currItem.className+=" FormFM";
		r.setAttribute("class", "FormFR");
		inputParent = currItem.parentNode;
		//insert the top level div
		inputParent.insertBefore(all,currItem);
	}
	
	//append children
	all.appendChild(l);
	all.appendChild(currItem);
	all.appendChild(r);

	return r;
}

function fixTextareas(){
	textareas = document.getElementsByTagName('textarea')
	for(i=0;i<textareas.length;i++){
		if(textareas[i].className.indexOf('nopretty')==-1){
			appendFormDivs(textareas[i]);
		}
	}
}

function fixInputs(){
	inputs=document.getElementsByTagName('input');
	for(i=0;i<inputs.length;i++){
		if(inputs[i].className.indexOf('nopretty')==-1){
			switch(inputs[i].type){
				case 'password':
				case 'reset':
				case 'submit':
				case 'text':
					appendFormFDivs(inputs[i]);
				break;
				case 'checkbox':
				case 'radio':
					lnk = document.createElement('a');
					lnk.className='Form'+inputs[i].type;
					img = document.createElement('img');
					if(inputs[i].checked==true){
						img.src = imagePath+inputs[i].type+'Checked.png';
					}else{
						img.src = imagePath+inputs[i].type+'Unchecked.png';
					}
					//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 = inputs[i].type+i;
						inputs[i].id = realId;
					}
					//give the fake check an id
					fakeId = 'fake'+realId;
					img.id=fakeId
					
					lnk.href="javascript:toggle"+inputs[i].type+"('"+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 checkbox
					inputs[i].style.visibility="hidden";
					inputs[i].style.position="absolute";
				break;
				case 'file':
					inputs[i].className=inputs[i].className+' nopretty';
					div=document.createElement('div');
					div.className='Formfile';
					inp=document.createElement('input');
					inp.id='test';
					inputs[i].relatedElement=inp;
					inputs[i].onchange=function(){this.relatedElement.value = this.value;}
					img=document.createElement('img');
					img.src=imagePath+'left.png';
					inputParent=inputs[i].parentNode;
					inputParent.insertBefore(div,inputs[i]);
					div.appendChild(inputs[i]);
					div.appendChild(inp);
					div.appendChild(img);
				break;
			}
		}
	}
}

//apply look to select boxes
function fixSelects(){
	selects = document.getElementsByTagName("select")
	for(i=0;i<selects.length;i++){
		if(selects[i].className.indexOf('nopretty')==-1){
			if(selects[i].size>1){
				r=appendFormDivs(selects[i]);
			}else{
				//create the standard shadows
				r=appendFormFDivs(selects[i]);
		
				//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");
				
				if(document.all){				//IE
					// Take attributes
					fakeSelectWrapper.className=selects[i].className;
		
					// onclick div didn't work in IE, so create an a tag
					all=document.createElement("a");
					r.insertAdjacentElement("BeforeBegin",all);
					all.appendChild(r);
					r=all;
		
					//this is the div that actually contains the list of options
					fakeSelect = document.createElement("div");
					fakeSelect.id="frmShdwMenu"+i;
					fakeSelect.className="frmShdwSelectDrop";
					options = selects[i].getElementsByTagName("option");
					//this div is displayed when the box is NOT dropped down.  Shows currently displayed item
					fakeSelectedHolder = document.createElement("a");
		
					fakeSelectedHolder.className="frmShdwSelectDropChosen";
					fakeSelectedHolder.id="frmShdwMenuChosen"+i;
					if(selects[i].offsetWidth>widthSelectDrop) fakeSelectedHolder.style.width=selects[i].offsetWidth-widthSelectDrop+"px";
					fakeSelectedHolder.href="javascript:dropDownMenu(\"frmShdwMenu"+i+"\", \"frmShdwMenuChosen"+i+"\",\""+selects[i].id+"\")";
					r.href="javascript:dropDownMenu(\"frmShdwMenu"+i+"\", \"frmShdwMenuChosen"+i+"\",\""+selects[i].id+"\")";
		
					for(j=0;j<options.length;j++){
						//create a p tag for each element
						if(!options[j].disabled){
							fakeOption = document.createElement("a")
							//here's some crazy IE stuff.
							fakeOption.href='javascript:chooseSelect("'+selects[i].id+'",'+j+',"frmShdwMenu'+i+'", "frmShdwMenuChosen'+i+'")'
						}else{
							fakeOption = document.createElement('span')
						}
						//append it to the parent div
						fakeOption.innerHTML = options[j].innerHTML;
						fakeSelect.appendChild(fakeOption);
						//set the default text to show
						if(options[j].selected==true){
							fakeSelectedHolder.innerHTML=options[j].innerHTML;
							fakeOption.className="selected";
						}
					}
					
					//now put the new div inside the shadows, above the select box
					selectParent = selects[i].parentNode;
					
					// more crazy IE 6,7 stuff : push the dropped down menu to the left where it belongs
					if(navigator.userAgent.substr(navigator.userAgent.indexOf('MSIE')+5,1)<8) fakeSelect.style.marginLeft=(-selects[i].offsetWidth+widthSelectDrop)+"px";
		
					fakeSelectWrapper = selects[i].insertAdjacentElement("BeforeBegin",fakeSelectWrapper)
				}else{
					// Take attributes
					fakeSelectWrapper.setAttribute("class",selects[i].className);
		
					//this is the div that actually contains the list of options
					fakeSelect = document.createElement("div");
					fakeSelect.setAttribute("id","frmShdwMenu"+i);
					fakeSelect.setAttribute("class","frmShdwSelectDrop");
					options = selects[i].getElementsByTagName("option");
					//this div is displayed when the box is NOT dropped down.  Shows currently displayed item
					fakeSelectedHolder = document.createElement("div");
					fakeSelectedHolder.setAttribute("class","frmShdwSelectDropChosen");
					fakeSelectedHolder.setAttribute("id","frmShdwMenuChosen"+i);
					if(selects[i].offsetWidth==0){
						fakeSelectedHolder.style.width=parseInt(selects[i].style.width)-widthSelectDrop+"px";
					}else{
						fakeSelectedHolder.style.width=selects[i].offsetWidth-widthSelectDrop+"px";
					}
					fakeSelectedHolder.setAttribute("onclick","javascript:dropDownMenu(\"frmShdwMenu"+i+"\", \"frmShdwMenuChosen"+i+"\",\""+selects[i].id+"\")");
					r.setAttribute("onclick","javascript:dropDownMenu(\"frmShdwMenu"+i+"\", \"frmShdwMenuChosen"+i+"\",\""+selects[i].id+"\")");
					
					for(j=0;j<options.length;j++){
						//create a p tag for each element
						if(!options[j].disabled){
							fakeOption = document.createElement("a")
							fakeOption.setAttribute("href","javascript:chooseSelect(\""+selects[i].id+"\","+j+",\"frmShdwMenu"+i+"\", \"frmShdwMenuChosen"+i+"\")");	//clicking calls the function chooseSelect passing the select object, and the chosen index
						}else{
							fakeOption = document.createElement('span')
						}
						//and append it to the parent div
						fakeOption.innerHTML = options[j].innerHTML;
						fakeSelect.appendChild(fakeOption);
						//set the default text to show
												
						if(options[j].selected==true){
							/*if (options[j].innerHTML.indexOf('&nbsp;&nbsp;&nbsp;')){
								options[j].innerHTML.substring(15, options[j].innerHTML.lenght);
							}*/
							fakeSelectedHolder.innerHTML=options[j].innerHTML;
							fakeOption.setAttribute("class","selected");
						}
					}
					
					//now put the new div inside the shadows, above the select box
					selectParent = selects[i].parentNode;
					fakeSelectWrapper = selectParent.insertBefore(fakeSelectWrapper,selects[i]);
				}
		
				if(selects[i].offsetWidth==0) fakeSelect.style.width=widthSelectDefault+"px";
				if(selects[i].offsetWidth>widthSelectDrop) fakeSelect.style.width=selects[i].offsetWidth-widthSelectDrop+"px";
		
				//hide the real select box
				//selects[i].style.display="none";
				selects[i].style.visibility="hidden";
				selects[i].style.position="absolute"; 
		
				//construct the menu parts Wrapper around list of options and image
				fakeSelectWrapper.appendChild(fakeSelectedHolder);
				fakeSelectWrapper.appendChild(fakeSelect);
			}
		}
	}
}






//****
//**** 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"){
		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).src=imagePath+'radioUnchecked.png';
				if(inputs[i].id==realRadioId){
					inputs[i].checked=true;	//check the actual button
					document.getElementById("fake"+inputs[i].id).src=imagePath+'radioChecked.png';
				}
			}
		}
	}
	
	//**** 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 togglecheckbox(realCheckId, fakeCheckId){
	fakeCheck = document.getElementById(fakeCheckId);
	realCheck = document.getElementById(realCheckId);
	
	if(realCheck.checked==true){
		fakeCheck.src=imagePath+'checkboxUnchecked.png';
		realCheck.checked=false;
	}else{
		fakeCheck.src=imagePath+'checkboxChecked.png';
		realCheck.checked=true;
	}
	
	//**** 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 dropDownMenu(menuId, chosenMenuId, realMenuId){
	fakeDropDown=document.getElementById(menuId);
	state=fakeDropDown.className=='frmShdwSelectDrop';

	closeDropDowns();
	//hide the default Text item
	//document.getElementById(chosenMenuId).style.display="none";
	//show the full list
	if(state){
		fakeDropDown.className='frmShdwSelectDropShown';
	}
	
	//**** EVENT HANDLING
	// Clicking the list is equivalent to the selects onClick event. fire it.
	realMenu = document.getElementById(realMenuId);
	if(document.all){
		res = realMenu.fireEvent("onclick");
	}else{
		mouseEvent = document.createEvent('MouseEvents');
		mouseEvent.initMouseEvent('click',true,true,window,1,0,0,0,0,false,false,false,false,0,null);
		realMenu.dispatchEvent(mouseEvent); 
	}
	
}

//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
	//fakeChosenItem.innerHTML=realDropdown[chosenIndex].innerHTML;
	//for some reason setting innerHTML breaks in IE
	
	// Andreas Heling
	var tempVal= realDropdown[chosenIndex].innerHTML;
	if (tempVal.indexOf('&nbsp;') > -1) {
		fakeChosenItem.childNodes[0].nodeValue = tempVal.replace(/&nbsp;/g,"");
	}
	else {// ================
	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
	fakeDropDown.className="frmShdwSelectDrop";
	
	//show the display div
	fakeChosenItem.style.display="block";
	
	//**** EVENT HANDLING
	// Choosing an item is equivalent to the selects onChange event. fire it.
	triggerEvent(realDropdown,"change");
}

function closeDropDowns(){
	divs=document.getElementsByTagName('div');
	for(i=0;i<divs.length;i++){
		if(divs[i].className=='frmShdwSelectDropShown') {
			divs[i].className='frmShdwSelectDrop';
		}
  }
}

//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);
		}
	}
}

