// ################## QueryString  #########################
function QueryString(key)
{
	var value = null;
	for (var i=0;i<QueryString.keys.length;i++)
	{
		if (QueryString.keys[i]==key)
		{
			value = QueryString.values[i];
			break;
		}
	}
	return value;
}

// ################## QueryString_Parse  #########################
function QueryString_Parse()
{
	var query = window.location.search.substring(1);
	var pairs = query.split("&");
	
	for (var i=0;i<pairs.length;i++)
	{
		var pos = pairs[i].indexOf('=');
		if (pos >= 0)
		{
			var argname = pairs[i].substring(0,pos);
			var value = pairs[i].substring(pos+1);
			QueryString.keys[QueryString.keys.length] = argname;
			QueryString.values[QueryString.values.length] = value;		
		}
	}

}

// ################## popUp  #########################
function popUp(mUrl,mWname,mWidth,mHeight) {
	var mOptions = "toolbar=no,menubar=yes,locationbar=no,scrollbars=yes,resizable=yes,status=no";
        // ** Internet Explorer can't handle spaces in Window names **
        var name = mWname;
        var spaceIndex = name.indexOf(' ');
        while (spaceIndex > -1) {
            name = name.substring(0, spaceIndex) + name.substring(spaceIndex + 1, name.length); 
            spaceIndex = name.indexOf(' ');
        }
        // ** open the window **
	mWindow = window.open(mUrl,name,mOptions + ",width=" + mWidth + ",height=" + mHeight);
	mWindow.focus();
}


// ################## GetInputValue  #########################
// returns the numeric value of the form-field given in mObject
// if it contains a comma instead of a decimal point the function converts the "," to "."
 function GetInputValue(mObject) {
    
    // ### Get Value of Input Field ###//  
 	if(isNaN(mObject.value) == false){
	    var mValue = parseFloat(mObject.value); 
	    if(isNaN(mValue)){
	    	 var mValue = 0;
	    }
	     mObject.value = mValue;
  		return mValue;
	} else {
	 	// ### Convert , into . of Input Field ###//
	 	 var mZahlenString = "" + mObject.value;
		 var Zahlen = mZahlenString.split(",");
		 if (Zahlen.length > 0) {
		 	var mNewValue = Zahlen[0] + "." + Zahlen[1];
		 	var mNewValue = parseFloat(mNewValue);
		 	
		 		if (isNaN(mNewValue) == true) {
		 			var mValue = 0;
		 			mObject.value = mValue;
		 			return mValue;
		 		} 
		 	mObject.value = mNewValue;
		 	return mNewValue;
		} 
	}
 }
 
 // ** this variable can be overridden by the using JSP, e.g. to "," **
 var decimalSign = ".";
 /** ###############  KonvertFloatToString  ###############
  * receives a float value and converts it to a
  * formatted String with 2 digits after the decimal dot.
  * Uses the variable decimalSign to render a dot or a comma.
  */
 function KonvertFloatToString(mFloat) {
	var mNumber = Math.round(mFloat * 100);
    var mNumber =	mNumber / 100;
	var mString = "" + mNumber;
	
	var mZahlenArray = mString.split(".");
	
	if (mZahlenArray.length > 1) {
			var VorKomma = mZahlenArray[0];
			var NachKomma = mZahlenArray[1];
			
			if (NachKomma.length == 1) {var NachKomma = NachKomma + "0";}
			var mString = VorKomma + decimalSign + NachKomma;
	} else {
		var mString = mString + decimalSign + "00";
	}
	
	return mString;
}

//##### PRINT FUNCTION #######
function printit(){  
    if (window.print) {
        window.print();
    } else {
        var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
        document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
        WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box    
        WebBrowser1.outerHTML = "";  
    }
}

/**
 * moves the selected item from one mutli-select-list to another. 
 * Use this method if you have 2 multi-select-lists, one with the 
 * possible values and one with the selected values.
 */
function MoveItem(fromObj,toObj)
{
   if (!eval(fromObj) || !eval(toObj))
       return;
   for (selIndex = fromObj.length-1; selIndex >=0 ; selIndex-- )
   {
      // Is this current option selected?
       if (fromObj.options[selIndex].selected)
       {
         // get the values from this option
         var newText = fromObj.options[selIndex].text;
         var newValue = fromObj.options[selIndex].value;
         // create the new element for other select box 
         var newOption = new Option(newText,newValue)
         // put the new option at the end of the current list 
         toObj[toObj.length] = newOption;
         // delete the old one.
         fromObj[selIndex] = null;
      }
   }
}

/**
 * auto-selects all entries in a multi-select-list. 
 * Use this method if you have 2 multi-select-lists, one with the 
 * possible values and one with the selected values. 
 * Example: 
 * <input type="submit" onclick="javascript:selectAllForSubmit(wishlist)">
 */
function selectAllForSubmit(selectBox)
{
    for(index = 0;index<selectBox.length;++index)
    {
        selectBox.options[index].selected = true;
    }
}

/**
 * compares the text of 2 options
 * @author Markus Leichter 
 */
function compareOptionsText (option1, option2) {
	return option1.text.toLowerCase() < option2.text.toLowerCase() ? -1 :
    	option1.text.toLowerCase() > option2.text.toLowerCase() ? 1 : 0;
}

/**
 * sorts items in mutli-select-list. 
 * @author Markus Leichter
 */
function SortMultiSelectList(select) 
{
//  if (!compareFunction)
	compareFunction = compareOptionsText;
	var options = new Array (select.options.length);
	for (var i = 0; i < options.length; i++)
	options[i] = 
		new Option (
			select.options[i].text,
			select.options[i].value,
			select.options[i].defaultSelected,
			select.options[i].selected
		);
	options.sort(compareFunction);
	select.options.length = 0;
	for (var i = 0; i < options.length; i++)
		select.options[i] = options[i];
}

/**
 * finds the index of an option by value
 */
function findOptionIndexByValue(optionListObject, mValue) {
    for (var i = 0; i < optionListObject.options.length; i++) {
        if (optionListObject.options[i].value == mValue)
            return i;
    }
    return 0;
} 

/**
 * this function sets the visibility of the dive with the given id to "visible" 
 * and positions it 
 * - horizontally centered
 * - with original top position, but relative to current scrolling position
 * It can be used for a hidden div, e.g. displaying a loading image and a 
 * "please wait" text. In the onclick azttribute of the button that leads to a 
 * time consuming controller action you can call this method. 
 * 
 * The div could be defined e.g. like this: 
 * <div style="position: absolute; top: 100px; left: 300px; width: 200px; height: 100px; z-index: 2; visibility: hidden; text-align: center; vertical-align: middle; background-color: #EFEFEF; border: 1px solid #FFA500; padding: 20px;" id="loadingDiv"><img src="<%= request.getContextPath() %>/images/loading.gif" width="35" height="35" border="0"><br><br><sf:message key="label.pleaseWait" bundle="UserInterfaceMessages"/></div>
 */
function showDivScrollingCentered(divId) {
    var myDiv = document.getElementById(divId);
    if (eval(myDiv)) {
        var mWidth,mHeight;
        if (self.innerHeight) // all except Explorer
        {
                mWidth = self.innerWidth;
                mHeight = self.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientHeight)
                // Explorer 6 Strict Mode
        {
                mWidth = document.documentElement.clientWidth;
                mHeight = document.documentElement.clientHeight;
        }
        else if (document.body) // other Explorers
        {
                mWidth = document.body.clientWidth;
                mHeight = document.body.clientHeight;
        }
        var x = 0;
        var y = 0;
        if (self.pageYOffset) // all except Explorer
        {
                x = self.pageXOffset;
                y = self.pageYOffset;
        }
        else if (document.documentElement && document.documentElement.scrollTop)
                // Explorer 6 Strict
        {
                x = document.documentElement.scrollLeft;
                y = document.documentElement.scrollTop;
        }
        else if (document.body) // all other Explorers
        {
                x = document.body.scrollLeft;
                y = document.body.scrollTop;
        }  
        var posY = parseInt(myDiv.style.top) + y; // ** original top position, but relative to scrolling **
        var posX = (mWidth / 2) - (parseInt(myDiv.style.width) / 2) + x; // ** horizontally centered **
        myDiv.style.top = posY;
        myDiv.style.left = posX;
        myDiv.style.visibility = "visible";
    }
}

function showError(contextPath) {
    window.open(contextPath + '/errorPage.jsp', 'errorWindow');
}


// ###########   attachEventListener #############
function attachEventListener(target, eventType, functionRef, capture){
		// ## cross browser compatible attachEventListener function -- function can be called with a pointer or a string representing a function name
	
      	if (typeof(functionRef)== 'string') {
            functionRef=eval(functionRef);
      	}

  		if (typeof target.addEventListener != "undefined"){
    		target.addEventListener(eventType, functionRef, capture);
		} else if (typeof target.attachEvent != "undefined"){
			target.attachEvent("on" + eventType, functionRef);
  		} else {
    		eventType = "on" + eventType;
		
    		if(typeof target[eventType] == "function"){
        		var oldListener = target[eventType];
        		target[eventType] = function(){
            		oldListener();
            		return functionRef();
        		};

    		} else {
        		target[eventType] = functionRef;
    		}

  		}

}

	
// ###############   createDOMElement    ###############
function createDOMElement(mElementType, mParentElement ,mTextString, mClassName , mElementID ){
		var mNewObject = document.createElement(mElementType);
		var mClassObject = document.createAttribute("class");
	
		if( mClassName  != ""){
			mClassObject.nodeValue = mClassName ;
			mNewObject.setAttributeNode(mClassObject);
		}

		if( mElementID  != "") {
			//alert("mElementID " + mElementID );
			var mIDObject = document.createAttribute("id");
			mIDObject.nodeValue = mElementID ;
			mNewObject.setAttributeNode(mIDObject);
		}
		
		if(mTextString != "") { 
            if (mElementType.toLowerCase() == "div") {
                mNewObject.innerHTML = mTextString;
            } else {
				var mTextNode = document.createTextNode("" + mTextString);
				mNewObject.appendChild(mTextNode);
            }
		}

		mParentElement.appendChild(mNewObject);

		return mNewObject;
}

  
// ### ShowObjectProperties  ###
function ShowObjectProperties(mObject) {
    	var mWindow = window.open("", "DEBUG", "toolbar=0,location=0,directories=0,scrollbars=1,status=0,menubar=1,resizable=1,width=500,height=600");
    	mWindow.document.open();
    
    	for (var i in mObject) {
        	mWindow.document.write('<BR><B>' + i + '</B> = ' + mObject[i] );
    	}
    
    	mWindow.document.close();
    	mWindow.focus();
}