// 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
}

function clearCheckboxes(daform, cName) {
	var n = daform.elements.length;
    for (i=0;i<n;i++) {
        if (daform.elements[i].name.indexOf(cName) != -1) {
            daform.elements[i].checked = false;
		} // 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;

Date.ONE_SECOND = 1000
Date.ONE_MINUTE = Date.ONE_SECOND * 60
Date.ONE_HOUR = Date.ONE_MINUTE * 60
Date.ONE_DAY = Date.ONE_HOUR * 24

function sleep (m) {var then = new Date(new Date().getTime() + m); while (new Date() < then) {}}

// 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';
		}
		else if (currentClass == 'SmallMinusLinkStyle') {
			thaObj.className = 'SmallPlusLinkStyle';
		}
		else if (currentClass == 'SmallPlusLinkStyle') {
			thaObj.className = 'SmallMinusLinkStyle';
		}
	}

	// 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) {


	// 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);
	var temp = MM_findObj('dynamiccontent');
	if ( toolsObj.style ) {
		var currentDisplay = toolsObj.style.display;
		if ( currentDisplay == 'block' ) {
			enlarge = 1;
		}
	}

	// target div
	var divObj = MM_findObj(divToResize);
	if ( enlarge == 1 ) {
		// and then use the showHideElement for the div...
		showHideElement(cE,tE);
		temp.setAttribute('width',temp.style.width);
		temp.setAttribute('pixelWidth',temp.style.pixelWidth);
		if (divObj.style.width) {
			temp.style.width = "100%";
		} else 	if (divObj.style.pixelWidth) {
			temp.style.pixelWidth = divObj.style.pixelWidth;
		}
	} else {
		// and then use the showHideElement for the div...
		showHideElement(cE,tE);
		temp.style.pixelWidth = temp.getAttribute('pixelWidth');
		temp.style.width = temp.getAttribute('width');
	}

}

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 = null;
   if (window.XMLHttpRequest) {
      xmlHttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP")
    }
    return xmlHttp;
}

function ajax_request_get(caller,actionName,sync) {
	var ajaxInstance = getAjaxInstance();
	if (ajaxInstance) {
		if (ajaxInstance.overrideMimeType) {
			ajaxInstance.overrideMimeType('text/html');
		}
		if (sync==false) {
			alert('async');
			ajaxInstance.onreadystatechange = function() {
				if (ajaxInstance.readyState == 4 && ajaxInstance.status == 200) {
					caller.innerHTML = ajaxInstance.responseText;
				}
			}
		}
		ajaxInstance.open("GET", 'GenericFormAction.np?'+actionName+'&ajax=true', !sync);
		ajaxInstance.send(null);
		//sleep(0.1 * Date.ONE_SECOND)		
		if (sync==true) {
			if (ajaxInstance.readyState != 4 || ajaxInstance.status != 200 || !ajax_hasResponse(ajaxInstance)) {
				sleep(0.1 * Date.ONE_SECOND);
			}
			var xx = ajaxInstance.responseText;
			return xx;
		}
		
	}
}

function ajax_hasResponse(request) {
    var responseText = request.responseText;
    if (responseText) {
        return true;
    }
    return false;
}

function ajax_request(caller,actionName) {
	ajax_request_get(caller,actionName,false);
}

function ajax_sync_request(caller,actionName) {
	 var response = ajax_request_get(caller,actionName,true);
	 caller.innerHTML = response;
}

function ajax_request_post(target,caller,actionName,parameters) {
	var ajaxInstance = getAjaxInstance();
	if (ajaxInstance) {
		if (ajaxInstance.overrideMimeType) {
			ajaxInstance.overrideMimeType('text/html');
		}
		ajaxInstance.onreadystatechange = function() {
			if (ajaxInstance.readyState == 4 ) {
				// caller.innerHTML = ajaxInstance.responseText;
				var x = document.createElement("div");
				var temp = ajaxInstance.responseText;
				x.innerHTML=temp;
				target.parentNode.replaceChild(x, target);
			}
		}
 
      ajaxInstance.open("POST", caller.action+"&ajax=true&"+actionName+"=12345", 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 parsePostDataFromChildElements(someElement) {
   var queryString = "";
   if (someElement!=null && (someElement.tagName == "INPUT" || someElement.tagName == "input" || someElement.tagName == "SELECT" || someElement.tagName == "select" || someElement.tagName == "TEXTAREA" || someElement.tagName == "textarea") ) {
      if (someElement.tagName == "INPUT" || someElement.tagName == "input") {
         if (someElement.type == "text" || someElement.type == "TEXT") {
            queryString = someElement.name + "=" + encodeURI(someElement.value.toLowerCase()) + "&";
         }
         if (someElement.type == "hidden" || someElement.type == "HIDDEN") {
            queryString = someElement.name + "=" + encodeURI(someElement.value) + "&";
         }
         if (someElement.type == "radio" || someElement.type == "RADIO") {
            if (someElement.checked) {
               queryString = someElement.name + "=" + encodeURI(someElement.value) + "&";
            }
         }
         if (someElement.type == "checkbox" || someElement.type == "CHECKBOX") {
            if (someElement.checked) {
               queryString = someElement.name + "=" + encodeURI(someElement.value) + "&";
            } else {
               queryString = someElement.name + "=&";
            }
         }
      }else if (someElement.tagName == "SELECT" || someElement.tagName == "select") {
         var sel = someElement;
         queryString = sel.name + "=" + encodeURI(sel.options[sel.selectedIndex].value) + "&";
      }else if (someElement.tagName == "TEXTAREA" || someElement.tagName == "textarea") {
         var textarea = someElement;
         queryString = textarea.name + "=" + encodeURI(textarea.value) + "&";
      }
   } else {
     	//Recurse children
     	var length = someElement.childNodes.length;
     	var i = 0;
	if (length != 0) {
   		for (i=0; i<length; i++) {
   			//if (someElement.childNodes[i].nodeName!='#text') {
   				queryString+=parsePostDataFromChildElements(someElement.childNodes[i]);
   			//}
  		}
	}
   }
   return queryString;
}

function submitAjaxForm_post(target, ajaxForm, actionName) {
   var postData = parsePostDataFromChildElements(ajaxForm);
   ajax_request_post(target, ajaxForm,actionName,postData);
}


function button_submitAjaxForm_post(submitButton) {
	var parentForm = nexstaff_findParentForm(submitButton);
	var target = nexstaff_findAjaxParentContainer(submitButton);
	if (parentForm!=null && target!=null) {
		submitAjaxForm_post(target, parentForm,submitButton.name);
	}
}

function nexstaff_findAjaxParentContainer(element) {

	var formFound = null;
	while (element!=null && formFound==null) {
	
		if (element.attributes && element.attributes["name"]) {
			if (element.attributes["name"].value=="ajaxContainer") {
				formFound = element;
			}
		}
		element = element.parentNode;
	}
	return formFound;
}

function nexstaff_findParentForm(element) {

	var formFound = null;
	while (element!=null && formFound==null) {
		if (element.tagName && element.tagName=="FORM") {
			formFound = element;
		}
		element = element.parentNode;
	}
	return formFound;
}


function getCurrentTime() {
	var d = new Date();
	return d.getTime();
}

var delCounter = 0;

function addDynamicDiv(id, rowId, maxCustomers) {
  var rowCount = $('tbody:first', $("#"+id)).children().length -1;
  var tb = $("#"+rowId).clone();
  tb.removeAttr('id');
  delCounter = delCounter + 1;
  if (delCounter == 1000) {
    delCounter = 0;
  }
  var html = tb.html();
  html = html.replace(/_dyn/g, "_dyn_" + delCounter);
  tb.html(html);
  tb.children('tbody').children('tr').attr('delId', delCounter);
  tb.removeAttr('style');
  $('tbody:first', $("#"+id)).append(tb.children('tbody').children());
  
  checkIfHideAddButton(id, maxCustomers);
}

function removeDynamicDiv(id, element, maxCustomers) {
  var delIdValue = $(element).parent().parent('tr').attr('delId');
  $("tr[delId='" + delIdValue +"']").remove();
  checkIfHideAddButton(id, maxCustomers);
}

function checkIfHideAddButton(id, maxCustomers) {
  var dynRows = $('tbody:first', $("#"+id)).children().children().children('label[del]').length;
    if ((dynRows + 1) >= maxCustomers) {
   $("[add_dyn]").attr("style", "height:14px;width:65px;display:none;");
  } else {
   $("[add_dyn]").attr("style", "height:14px;width:65px;");  
  }
}
