
// global xmlhttprequest object
var xmlHttp =  new Array();
var xmlHttpFields =  new Array();

/** AJAX functions **/

// constants
var REQUEST_GET        = 0;
var REQUEST_POST       = 2;
var REQUEST_HEAD       = 1;
var REQUEST_XML        = 3;



/**
 * instantiates a new xmlhttprequest object
 *
 * @return xmlhttprequest object or false
 */
function getXMLRequester()
{

    var xmlHttpObj = false;
           
    // try to create a new instance of the xmlhttprequest object       
    try
    {
        // Internet Explorer
        if( window.ActiveXObject )
        {
            for( var i = 5; i; i-- )
            {
                try
                {
                    // loading of a newer version of msxml dll (msxml3 -msxml5) failed
                    // use fallback solution
                    // old style msxml version independent, deprecated
                    if( i == 2 )
                    {
                        xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP" );
                    }
                    // try to use the latest msxml dll
                    else
                    {

                        xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP." + i + ".0" );
                    }
                    break;
                }
                catch( excNotLoadable )
                {                       
                    xmlHttpObj = false;
                }
            }
        }
        // Mozilla, Opera und Safari
        else if( window.XMLHttpRequest )
        {
            xmlHttpObj = new XMLHttpRequest();
        }
    }
    // loading of xmlhttp object failed
    catch( excNotLoadable )
    {
        xmlHttpObj = false;
    }
    return xmlHttpObj;
}


/**
 * sends a http request to server
 * @param strSource, String, datasource on server, e.g. data.php
 * @param strData, String, data to send to server, optionally
 * @param intType, Integer,request type, possible values: REQUEST_GET,
REQUEST_POST, REQUEST_XML, REQUEST_HEAD default REQUEST_GET
 * @param strData, Integer, ID of this request, will be given to
registered event handler onreadystatechange', optionally
 * @return String, request data or data source
 */
function sendRequest(strSource, strData, intType, returnToofunction, clipboard)
{
    if( !strData )
        strData = '';

    // default type (0 = GET, 1 = xml, 2 = POST )
    if( isNaN( intType ) )
        intType = 0; // GET
       
    requestId = xmlHttp.length;

    // previous request not finished yet, abort it before sending a new request
    if( xmlHttp[requestId] && xmlHttp[requestId].readyState )
    {
        xmlHttp[requestId].abort( );
        xmlHttp[requestId] = false;
    }
       
    // create a new instance of xmlhttprequest object
    // if it fails, return
    if( !xmlHttp[requestId] )
    {
        xmlHttp[requestId] = getXMLRequester( );
        if( !xmlHttp[requestId] )
            return;
    }
   
    // parse query string
    if( intType != 1 && ( strData && strData.substr( 0, 1 ) == '&' || strData.substr( 0, 1 ) == '?' ) )
        strData = strData.substring( 1, strData.length );

    // data to send using POST
    var dataReturn = strData ? strData : strSource;
   
    xmlHttpFields[requestId] = new Object();
    xmlHttpFields[requestId].returnToofunction = returnToofunction;
    xmlHttpFields[requestId].clipboard = clipboard;
   
    switch( intType )
    {
        case 1:    // xml
            strData = "xml=" + strData;
        case 2: // POST
            // open the connection
            xmlHttp[requestId].open( "POST", strSource, true );
            xmlHttp[requestId].setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
            xmlHttp[requestId].setRequestHeader( 'Content-length', strData.length );
            break;
        case 3: // HEAD
            // open the connection
            xmlHttp[requestId].open( "HEAD", strSource, true );
            strData[requestId] = null;
            break;
        default: // GET
            // open the connection
            var strDataFile = strSource + (strData ? '?' + strData : '' );
            xmlHttp[requestId].open( "GET", strDataFile, true );
            strData = null;
    }
   
    // set onload data event-handler
    xmlHttp[requestId].onreadystatechange = new Function( "", "processResponse(" + requestId + ")" ); ;

    // send request to server
    xmlHttp[requestId].send( strData );    // param = POST data
   
    return dataReturn;
}

function call_user_func(cb, parameters) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)
    // *     example 1: call_user_func('isNaN', 'a');
    // *     returns 1: true
 
    var func;
 
    if (typeof cb == 'string') {
        if (typeof this[cb] == 'function') {
            func = this[cb];
        } else {
            func = (new Function(null, 'return ' + cb))();
        }
    } else if (cb instanceof Array) {
        func = eval(cb[0]+"['"+cb[1]+"']");
    }
   
    if (typeof func != 'function') {
        throw new Error(func + ' is not a valid function');
    }

  //  return func.apply(null, Array.prototype.slice.call(parameters, 1));
    if (typeof(parameters)=='string')
     return func.apply(null, new Array(parameters) );
    else
     return func.apply(null, parameters);
}
   

function processResponse( requestId )
{
    // status 0 UNINITIALIZED open() has not been called yet.
    // status 1 LOADING send() has not been called yet.
    // status 2 LOADED send() has been called, headers and status are available.
    // status 3 INTERACTIVE Downloading, responseText holds the partial data.
    // status 4 COMPLETED Finished with all operations.

    switch( xmlHttp[requestId].readyState )
    {
        // uninitialized
        case 0:
        // loading
        case 1:
        // loaded
        case 2:
        // interactive
        case 3:
            break;
        // complete
        case 4:   
            // check http status
            if( xmlHttp[requestId].status == 200 )    // success
            {
                //eval(xmlHttp[requestId].returnToofunction+'("'+xmlHttp[requestId].responseText+'");');

                if (xmlHttpFields[requestId].returnToofunction.length>0)
                 call_user_func(xmlHttpFields[requestId].returnToofunction, new Array(xmlHttp[requestId], xmlHttpFields[requestId].clipboard) );
            }
            // loading not successfull, e.g. page not available
            else
            {
                if( window.handleAJAXError )
                    handleAJAXError( xmlHttp[requestId], intID );
                else
                    alert( "ERROR\n HTTP status = " + xmlHttp[requestId].status + "\n" + xmlHttp[requestId].statusText ) ;
            }
    }
}

var hiddenEls = new Array();

function hideElements(type, thisWindow) {
	if (!thisWindow) {
		hideElements(type, self);
	} else {
		var tagName, tagNames = type === 'flash' ? ['object', 'embed'] : [type];
		try {
			while ((tagName = tagNames.pop())) {
				var els = thisWindow.document.getElementsByTagName(tagName),
					i = els.length;
				while (i--) {
					var el = els[i];
					if (el.style.visibility !== 'hidden' && (tagName !== 'object' ||
					(el.getAttribute('type') && el.getAttribute('type').toLowerCase() === 'application/x-shockwave-flash') ||
					(el.getAttribute('classid') && el.getAttribute('classid').toLowerCase() === 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000') ||
					/data\s*=\s*"?[^>"]+\.swf\b/i.test(el.innerHTML) ||
					/param\s+name\s*=\s*"?(movie|src)("|\s)[^>]+\.swf\b/i.test(el.innerHTML))) {
						hiddenEls.push(el);
						el.style.visibility = 'hidden';
					}
				}
			}
		} catch(e) {}
		var iframes = thisWindow.frames, i = iframes.length;
		while (i--) {
			try {
				if (typeof iframes[i].window === 'object') hideElements(type, iframes[i].window);
			} catch(e) {}
		}
	}
}

function showHidenElements()
{
 while(hiddenEls.length) 
 {
  var el = hiddenEls.pop();
  el.style.visibility = 'visible';
  //el.focus();
  //el.blur();
 }
}

function number_format(number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands
    //
    // version: 906.1806
    // discuss at: http://phpjs.org/functions/number_format
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +     input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +     improved by: davook
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     input by: Jay Klehr
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // *     example 2: number_format(1234.56, 2, ',', ' ');

    var n = number, prec = decimals;
                                         
    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };
 
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
 
    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

function $(id) { return document.getElementById(id); }

function selectWert(sObj) { with (sObj) return options[selectedIndex].value; }

function setSelectWert(sObj, wert)
{
 for(i in sObj.options)
  if (sObj.options[i].value==wert)
   sObj.selectedIndex = i;
}

function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

