/* 
	Common JavaScript
	
	(c) Nextime Solutions Oy
	
	includes basic javascript functions:
	- find objects by name
	- change object properties
	- show/hide layers
	- check/uncheck checkboxes
	- find out selected radiobutton values
	- check the length of text typed in fields
*/

// macromedia's cross browser find object -function
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

// macromedia's change property
function MM_changeProp(objName,x,theProp,theValue) { //v6.0
  var obj = MM_findObj(objName);
  if (obj && (theProp.indexOf("style.")==-1 || obj.style)){
    if (theValue == true || theValue == false) { eval("obj."+theProp+"="+theValue); }
    else { 
	var doMe = "obj." + theProp + "='" + theValue + "'" ;
	eval( doMe );
	}
  }
}

// macromedia's show/hide layers
function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

// macromedia's go to url
// onclick="MM_goToURL('parent','employee_modifyInfo.html');return document.MM_returnValue"
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

// macromedia's jumpmenu
// <select onchange="MM_jumpMenu(this.document, this, 0);"><option value="url_address_with_needed_get_parameters">Jump to url</option></select>
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

// macromedia's open new window
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

/*
	checkboxInvert(document.theform, 'nameprefix')
	JavaScript version needed: 1.1 -> .type property
	checks/unchecks (or "inverts") all checkboxes in a form 
	having 'nameprefix' in name.

	i.e. you have checkboxes like <input type="checkbox" name="plop_1" value="1" /> from plop_1 to plop_n
	and you want to "invert" them all. add a link or button or whatever that has event
	onclick="Javascript:checkAll( document.form_name ,'plop')" 
*/
function checkboxInvert(daform, daprefix) {
	var n = daform.elements.length;
	for (var i=0;i<n;i++) {
        if (daform.elements[i].type == "checkbox" && daform.elements[i].name.indexOf(daprefix,0) > -1 && daform.elements[i].name.indexOf("all",0) == -1 ) {
			if (daform.elements[i].checked) {
				daform.elements[i].checked = false;
			} else {
				daform.elements[i].checked = true;
			}
		}// if
	} // for
} //function

/*
	checkboxAll( document.formname, 'partOfName', checkbox-object )
	checks or unchecks all checkboxes with "partOfName" in their 
	name in a form of document. 

	has to be used as follows:
	have an extra checkbox for checking/unchecking all wanted checboxes like so
	<input type="checkbox" name="checkall" onclick="javascript:checkboxAll(document.form,"partofname",this);">
	changes the checked state of wanted checkboxes to the same as in this extra 'checkall' checkbox.
*/
function checkboxAll(daform, cName, box ) {
	var n = daform.elements.length;
    for (i=0;i<n;i++) {
        if (daform.elements[i].name.indexOf(cName) != -1) {
            daform.elements[i].checked = box.checked;
		} // if
	} // for
}

/*
	radiobuttonSelectedValue(document.formname,'partOfName')
	returns value of the selected radiobutton in the radiobutton group with 'partOfName' in its name
	Javascript 1.1 needed -> .type property
*/
function radiobuttonSelectedValue(daform,cName) {
	for (var i=0;i<daform.elements.length;i++) {
		// loop through form elements
        if (daform.elements[i].type == "radio" && daform.elements[i].name.indexOf(cName) > -1 ) {
			// is a radiobutton and is has the right name...
			if ( daform.elements[i].checked == true ) {
				// .. and is checked on top of all! wow! return the value!
				return daform.elements[i].value;
				break;
			}
		} // if
	} // for
}

/*
	shows/hides a tooltip-layer
	show: tooltip("layerid",some_integer_or_anything) 
	hide: tooltip("layerid") 
	layer must be absolutely positioned
*/
function toolTip(el,fl){
  elmnt = MM_findObj(el);
  if (fl) { 
    elmnt.parentNode.parentNode.style.zIndex=1000;
    elmnt.parentNode.parentNode.style.borderRight='0px solid #000';
    // ugly , yes .. but neccesary to avoid a small but very annoying bug in IE6
    elmnt.style.visibility='visible';
  }
  else {
    elmnt.parentNode.parentNode.style.zIndex=1;
    elmnt.parentNode.parentNode.style.border='none';
    elmnt.style.visibility='hidden';
  }
}

/*
	To cut the content when length >textLength use this
	<textarea name="_Source" cols="60" rows="3" onkeyup="JavaScript:MM_changeProp( '_Target','','value',changeLength('_Source',160) );" ></textarea>
	<input type="text" name="_Target" size="4" value="0" readonly="readonly" />
*/
function changeLength(objName, textLength) {
  var obj = MM_findObj(objName);
  var objValue = obj.value;
  if ( objValue.length > textLength ) {
  	objNewValue = objValue.substr(0,textLength);
	MM_changeProp( objName,"","value",objNewValue);
	return objNewValue.length;
	// alert("Viesti on liian pitkä!\rSuurin sallittu pituus on "+textLength+".\rTeksti lyhennetään automaattisesti oikean mittaiseksi.");
  } else {
	  return objValue.length;
  }
}

/*
	To calculate the length (can be over 160) use this:
	<textarea name="_Source" cols="60" rows="3" onkeyup="JavaScript:MM_changeProp( '_Target','','value',calculateLength('_Source') );" ></textarea>
	<input type="text" name="_Target" size="4" value="0" readonly="readonly" />
*/
function calculateLength(objName) {
  var obj = MM_findObj(objName);
  var objValue = obj.value;
  if ( objValue.length > 0 ) {
  	objNewValue = objValue;
	return objNewValue.length;
  } else {
	  return objValue.length;
  }
}

/*
	Length checked on submit, returns false and shows an errormessage + messagelength 
	if the message/text is too long
	<input type="submit" name="submit" value="submit" onclick="javascript:submitCheckLength('objecttocheck',maximumlength, 'errormessage')" />
*/
function submitCheckLength( objName, textLength, errorMessage ) {
  var obj = MM_findObj(objName);
  var objValue = obj.value;
  if ( objValue.length > textLength ) {
	alert(errorMessage+textLength);
	return false;
  } else {
	return true;
  }
}

var returnVal = true;

// showHideElement()
// changes the class of an element and hides the other element
//
// classElement is the element the class of which will be changed
// targetElement is the element to be shown/hid.
//
// note:
// doesn't get the right object reference with 'this' in a-tag href, ie.
// href="showHideObject(this,'someElement');" instead, has to be put in the onclick event.
// The targetElement (the one being hidden/shown) has to have style="display:block;"
// or style="display:none;" set it it's parameters for the function to work correctly

function showHideElement(classElement,targetElement) {

	var thaObj = classElement;
	var theObj = MM_findObj(targetElement);

	// if thaObj is set/found change it's class if it is either
	// "plus" or "minus", otherwise do nothing 
	if ( thaObj ) {
		var currentClass = thaObj.className;
		if (currentClass == 'MinusLinkStyle') {
			thaObj.className = 'PlusLinkStyle';
		}
		else if (currentClass == 'PlusLinkStyle') {
			thaObj.className = 'MinusLinkStyle';
		}
	}

	// hide / show the 
	if ( theObj.style ) {
		var currentDisplay = theObj.style.display;
		if ( currentDisplay == 'block' ) {
			theObj.style.display = 'none';
		} 
		else {
			theObj.style.display = 'block';
		}
	}
	returnVal = false;
}

// toggle()
// hides / shows the calendar and resizes the content div to 940px wide (if calendar is being hidden)
// or to 740px wide (if calendar is being shown).
//
// cE is the element the class of which will be changed
// tE is the element to be shown/hid.
// divToResize is the div the width of which will be changed
//
// note:
// for this to work you have to write style="display:block;" or style="display:none;"
// into calendar div's style parameter itself and style="width: 740px;" or style="width: 940px;" 
// into contentArea div's style. This is because javascript doesn't get the styles from the css
// but straight from the tag's style-parameter. Forgetting to write these in the html results
// in having to click twice before the script works or weird / inconsistent functionality,
// depending on the browser.
function toggle(cE,tE,divToResize) {

	// widths
	var x_width = 210; // 200px calendar + 10px margin

	// if opera 6 and up or netscape 4 we have to write 'px' after the width when setting
	var n4 = !!(document.layers && typeof document.classes != "undefined");
  var agt=navigator.userAgent.toLowerCase();
	var is_opera = (agt.indexOf("opera") != -1);
  var is_opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1);
  var is_opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1);
  var is_opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1);
  var is_opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1);
  var is_opera6up = (is_opera && !is_opera2 && !is_opera3 && !is_opera4 && !is_opera5 );
	var px = (n4 || is_opera6up)? '' : 'px';

	// enlarge / reduce
	var enlarge = 0;
	var toolsObj = MM_findObj(tE);
	if ( toolsObj.style ) {
		var currentDisplay = toolsObj.style.display;
		if ( currentDisplay == 'block' ) {
			enlarge = 1;
		} 
	}

	// target div
	var divObj = MM_findObj(divToResize);

	// let's find out which kind of syntax we have to use
	if ( typeof divObj.style.pixelWidth != "undefined" ) {
		dW = divObj.style.pixelWidth ;
		if ( enlarge == 1 ) {
			divObj.style.pixelWidth = dW + x_width;
		}
		else {
			divObj.style.pixelWidth = dW - x_width;
		}
	}
	else {
		dW = divObj.style.width;
		if (dW.indexOf("px") != -1) {
			dW = dW.substring(0, dW.length - 2); 		
		}
		dW = parseInt(dW);
		if ( enlarge == 1 ) {
			divObj.style.width = dW + x_width + px;
		}
		else {
			divObj.style.width = dW - x_width + px;
		}
	}
	
	// and then use the showHideElement for the div...
	showHideElement(cE,tE);
}

function focusFirstInputElementOfType(obj,targetType) {
    var elems = document.getElementsByTagName('input');
    
    for (var i=0; i<elems.length; i++) {
        var e = elems[i];
        if (e.type=='text') {
        	e.focus();
        	break;
        }
	}
	
}


function getAjaxInstance() {
	var xmlHttp;
	if (window.ActiveXObject) {
		xmlHttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE
      try {
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
           xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
      }
    }
}

function ajax_request_get(caller,actionName) {
	var ajaxInstance = getAjaxInstance();
	if (ajaxInstance) {
		if (ajaxInstance.overrideMimeType) {
			ajaxInstance.overrideMimeType('text/html');
		}
		ajaxInstance.onreadystatechange = function() {
			if (ajaxInstance.readyState == 4 && ajaxInstance.status == 200) {
				caller.innerHTML = ajaxInstance.responseText;
			}
		}
		ajaxInstance.open("GET", actionName, true);	
		ajaxInstance.send(null);
	}
}
function ajax_request(caller,actionName) {
	ajax_request_get(caller,actionName);
}

function ajax_request_post(caller,actionName,parameters) {
	var ajaxInstance = getAjaxInstance();
	if (ajaxInstance) {
		if (ajaxInstance.overrideMimeType) {
			ajaxInstance.overrideMimeType('text/html');
		}
		ajaxInstance.onreadystatechange = function() {
			if (ajaxInstance.readyState == 4 && ajaxInstance.status == 200) {
				caller.innerHTML = ajaxInstance.responseText;
			}
		}
      		
      ajaxInstance.open("POST", actionName, true);	
	  ajaxInstance.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	  ajaxInstance.setRequestHeader("Content-length", parameters.length);
	  ajaxInstance.setRequestHeader("Connection", "close");
	  ajaxInstance.send(parameters);
	}
}


function showHideAjaxElement(classElement,targetElement, url) {
	var target = MM_findObj(targetElement);
	showHideElement(classElement,targetElement);
	if (target.style.display=='block') {
		if (target) {
			//Always issue a new request on show
			ajax_request(target,url);
		}
	}
}

function submitAjaxForm_get(ajaxForm, actionName) {
   var queryString = "?";
   for (i=0; i<ajaxForm.childNodes.length; i++) {
      if (ajaxForm.childNodes[i].tagName == "INPUT") {
         if (ajaxForm.childNodes[i].type == "text") {
            queryString += ajaxForm.childNodes[i].name + "=" + escape(ajaxForm.childNodes[i].value) + "&";
         }
         if (ajaxForm.childNodes[i].type == "hidden") {
            queryString += ajaxForm.childNodes[i].name + "=" + escape(ajaxForm.childNodes[i].value) + "&";
         }
         if (ajaxForm.childNodes[i].type == "radio") {
            if (ajaxForm.childNodes[i].checked) {
               queryString += ajaxForm.childNodes[i].name + "=" + escape(ajaxForm.childNodes[i].value) + "&";
            }
         }
         if (ajaxForm.childNodes[i].type == "checkbox") {
            if (ajaxForm.childNodes[i].checked) {
               queryString += ajaxForm.childNodes[i].name + "=" + escape(ajaxForm.childNodes[i].value) + "&";
            } else {
               queryString += ajaxForm.childNodes[i].name + "=&";
            }
         }
      }   
      if (ajaxForm.childNodes[i].tagName == "SELECT") {
         var sel = ajaxForm.childNodes[i];
         queryString += sel.name + "=" + escape(sel.options[sel.selectedIndex].value) + "&";
      }
      if (ajaxForm.childNodes[i].tagName == "TEXTAREA") {
         var textarea = ajaxForm.childNodes[i];
         queryString += textarea.name + "=" + escape(textarea.value) + "&";
      }
      
   }
   ajax_request(ajaxForm,actionName + queryString);
}

function submitAjaxForm_post(ajaxForm, actionName) {
   var queryString = "";
   for (i=0; i<ajaxForm.childNodes.length; i++) {
      if (ajaxForm.childNodes[i].tagName == "INPUT") {
         if (ajaxForm.childNodes[i].type == "text") {
            queryString += ajaxForm.childNodes[i].name + "=" + encodeURI(ajaxForm.childNodes[i].value) + "&";
         }
         if (ajaxForm.childNodes[i].type == "hidden") {
            queryString += ajaxForm.childNodes[i].name + "=" + encodeURI(ajaxForm.childNodes[i].value) + "&";
         }         
         if (ajaxForm.childNodes[i].type == "radio") {
            if (ajaxForm.childNodes[i].checked) {
               queryString += ajaxForm.childNodes[i].name + "=" + encodeURI(ajaxForm.childNodes[i].value) + "&";
            }
         }
         if (ajaxForm.childNodes[i].type == "checkbox") {
            if (ajaxForm.childNodes[i].checked) {
               queryString += ajaxForm.childNodes[i].name + "=" + encodeURI(ajaxForm.childNodes[i].value) + "&";
            } else {
               queryString += ajaxForm.childNodes[i].name + "=&";
            }
         }
      }   
      if (ajaxForm.childNodes[i].tagName == "SELECT") {
         var sel = ajaxForm.childNodes[i];
         queryString += sel.name + "=" + encodeURI(sel.options[sel.selectedIndex].value) + "&";
      }
      if (ajaxForm.childNodes[i].tagName == "TEXTAREA") {
         var textarea = ajaxForm.childNodes[i];
         queryString += textarea.name + "=" + encodeURI(textarea.value) + "&";
      }
      
   }
   ajax_request_post(ajaxForm,actionName,queryString);
}

