/* framework helper functions */
var xmlHttp;
var isAjaxDebug = false;

function pAjaxCallMethod(pObj, pMethod, pParams, cbMethod, cbContainerID, SID, lang){
	if(lang==undefined){
		lang="";
	}
	xmlHttp = getXMLRequester();
	sendRequest("ajaxHandler.php", "ajaxReq=true&pObject="+pObj+
	                               "&pMethod="+pMethod+
	                               "&pParams[]="+pParams+
	                               "&cbMethod="+cbMethod+
	                               "&cbContainerID="+cbContainerID+
	                               "&lang="+lang+
	                               "&SID="+SID
	                               , 2);
	debugAjax("##REQUEST##\n"+
	          "ajaxHandler.php?ajaxReq=true&pObject="+pObj+
	          "&pMethod="+pMethod+"&pParams[]="+pParams+"&cbMethod="+cbMethod+"&cbContainerID="+cbContainerID+"&SID="+SID+"&lang="+lang );
	var tmp = pParams.split(",");
	
	if(tmp.length >= 3 )	{
		var tmplink = "ws-article-fun,article,"+tmp[0]+","+tmp[1]+","+tmp[2];
		//if(tmp.length >= 4 )
		//	tmplink = tmplink+","+tmp[3];
		tmplink = tmplink+".html";
		
		var tmp_elm = document.getElementById("ln_detailimg_"+cbContainerID);
		if(tmp_elm !=null )	{
			tmp_elm.href=tmplink;
		}
		tmp_elm = document.getElementById("ln_detailtxt_"+cbContainerID);
		if(tmp_elm !=null )	{
			tmp_elm.href=tmplink;
		}
	}
}

/**
 * checks if element exist and value is not empty.
 * if value not set, the element will have no content.
 */
function ax_checkIfContentAndSet(elmname,value)
{
	var d = document.getElementById(elmname);
	if(d!=null){
		if(value!=null){
			if(trim(value)!=""){
				d.innerHTML=value;
			}else{
				d.innerHTML="";
			}
		}else{
			d.innerHTML="";
		}
	}
}

function ax_setVariantPullDown(cbResult){
	try{
		var d=null;
		var dOff = null;
		//set variant box
		ax_checkIfContentAndSet("variantBox_"+cbResult[0],cbResult[1]);
		debugAjax("....param 0..1 [variantBox_"+cbResult[0]+"] set to "+cbResult[1]);
		//var d = document.getElementById("variantBox_"+cbResult[0]);
		//d.innerHTML = cbResult[1];
	
		
	
		//price scale box
		ax_checkIfContentAndSet("scaleBox_"+cbResult[0],cbResult[4]);
		debugAjax("....param 0..4 [scaleBox_"+cbResult[0]+"] set to "+cbResult[4]);
		//d = document.getElementById("scaleBox_"+cbResult[0]);
		//d.innerHTML = cbResult[4];
	
		//price per page box
		ax_checkIfContentAndSet("pricePerPageBox_"+cbResult[0],cbResult[5]);
		debugAjax("....param 0..5 [pricePerPageBox_"+cbResult[0]+"] set to "+cbResult[5]);
		//d = document.getElementById("pricePerPageBox_"+cbResult[0]);
		//d.innerHTML = cbResult[5];

		//alert(cbResult[6]);
		if(cbResult[6] != ""){
			d = document.getElementById("groupItemImage_"+cbResult[0]);
			debugAjax("....param 0..6 [groupItemImage_"+cbResult[0]+"] set to "+cbResult[6]);
			if(d!=null) d.src = cbResult[6];
		}
		
		//star action
		if(cbResult[7] != ""){
			d = document.getElementById("groupItemImageTip_"+cbResult[0]);
			debugAjax("....param 0..7 [groupItemImageTip_"+cbResult[0]+"] set to "+cbResult[7]);
			if(d!=null) d.src = cbResult[7];
		}
		//language select
		if(cbResult[8] != ""){
			ax_checkIfContentAndSet("languageBox_"+cbResult[0],cbResult[8]);
			debugAjax("....param 0..8 [languageBox_"+cbResult[0]+"] set to "+cbResult[8]);
		}
		if(cbResult[10] != ""){
			d = document.getElementById("ln_detailimg_"+cbResult[0]);
			debugAjax("....param 0..10 [ln_detailimg_"+cbResult[0]+"] set to "+cbResult[10]);
			if(d!=null) d.href = cbResult[10];
		}
		//set editoropener
		d 		= document.getElementById("editOnlineButton_"+cbResult[0]);
		dOff 	= document.getElementById("editOfflineButton_"+cbResult[0]);
		if(dOff != null && dOff != undefined){
			//language select
			if(cbResult[9] == "" || cbResult[9] == undefined || cbResult[9] == "visible"){
				dOff.style.visibility = 'visible';
			}else{
				dOff.style.visibility = 'hidden';
			}
		}
		
		var hasEditorLink = false;
		
		if(cbResult[3]!=null) {
			switch(trim(cbResult[3])){
				//editoropener not set
				case "":
				case null:
				case " ":
					var foo = unescape(btn_select_variants);

					if(d!=null && d != undefined) {
						d.href = "javascript:alert('"+foo+"')";
						d.className = "disabled";
					}
					debugAjax("....param 3 [function not found]");
				break;
		
				//editoropener not visible for onlineediting
				case "false":
					if(d!=null && d != undefined) {
						var foo = unescape(btn_select_variants);
						d.href = "javascript:alert('"+foo+"')";
						d.className = "hide";
					}
					debugAjax("....param 3 [function hidden]");
				break;
		
				//default set editoropener
				default:
					if(d!=null && d != undefined) {
						d.href =  encodeURI(cbResult[3]);
						d.className = "enabled";
						hasEditorLink=true;
					}
					debugAjax("....param 3 [function enabled]");
					if(dOff != null && dOff != undefined){
						dOff.href = "ws-download-offline-software-static.download,dpleasy.html";
						dOff.className = "enabled";
					}
				break;
			}
		}else{
			
			if(d!=null && d != undefined) {
				var foo = unescape(btn_select_variants);
				d.href = "javascript:alert('"+foo+"')";
				d.className = "disabled";
			}
			debugAjax("....param 3 [function not found]");
		}
		/*var priceContainer = document.getElementById("priceBox_"+cbResult[0]);
		//set price box
		if(hasEditorLink==true){
			
			ax_checkIfContentAndSet("priceBox_"+cbResult[0],cbResult[2]);
			//priceContainer.className = "priceBox";
			priceContainer.style.color = null;
		}else{
			ax_checkIfContentAndSet("priceBox_"+cbResult[0],btn_select_variants);
			priceContainer.style.color = "#CC0000";
		}*/
		ax_checkIfContentAndSet("priceBox_"+cbResult[0],cbResult[2]);
		debugAjax("....param 0..2 [priceBox_"+cbResult[0]+"] set to "+cbResult[2]);
		//d = document.getElementById("priceBox_"+cbResult[0]);
		//d.innerHTML = cbResult[2];
		
	}
	catch(e)  {
      debugAjax("##DROPDOWN ERR##\n msg:"+e+" ID="+d.innerHTML);
    }

}






/* ajax framework start */
var IE = false;
/**
 * instantiates a new xmlhttprequest object
 *
 * @return xmlhttprequest object or false
 */
function getXMLRequester( )
{
    var xmlHttp = false;

    // try to create a new instance of the xmlhttprequest object
    try
    {
        // Internet Explorer
        if( document.all )
        {
            IE = true;
        	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 )
                    {
                        xmlHttp = new ActiveXObject( "Microsoft.XMLHTTP" );
                    }
                    // try to use the latest msxml dll
                    else
                    {

                        xmlHttp = new ActiveXObject( "Msxml2.XMLHTTP." + i + ".0" );
                    }
                    break;
                }
                catch( excNotLoadable )
                {
                    xmlHttp = false;
                }
            }
        }
        // Mozilla, Opera und Safari
        else if( window.XMLHttpRequest )
        {
            xmlHttp = new XMLHttpRequest();
        }
    }
    // loading of xmlhttp object failed
    catch( excNotLoadable )
    {
        xmlHttp = false;
    }
    return xmlHttp ;
}



// constants
var REQUEST_GET        	= 0;
var REQUEST_POST        = 2;
var REQUEST_HEAD    	= 1;
var REQUEST_XML        	= 3;

/**
 * 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 intID, 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, intID )
{
    if( !strData )
        strData = '';

    // default type (0 = GET, 1 = xml, 2 = POST )
    if( isNaN( intType ) )
        intType = 0; // GET

    // previous request not finished yet, abort it before sending a new request
    if( xmlHttp && xmlHttp.readyState )
    {
        xmlHttp.abort( );
        xmlHttp = false;
    }

    // create a new instance of xmlhttprequest object
    // if it fails, return
    if( !xmlHttp )
    {
        xmlHttp = getXMLRequester( );
        if( !xmlHttp )
            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;

    switch( intType )
    {
        case 1:    // xml
            strData = "xml=" + strData;
        case 2: // POST
            // open the connection
            xmlHttp.open( "POST", strSource, true );
            xmlHttp.setRequestHeader("Method", "POST " + strSource + " HTTP/1.1");
            xmlHttp.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
            xmlHttp.setRequestHeader( 'Content-length', strData.length );
            break;
        case 3: // HEAD
            // open the connection
            xmlHttp.open( "HEAD", strSource, true );
            strData = null;
            break;
        default: // GET
            // open the connection
            var strDataFile = strSource + (strData ? '?' + strData : '' );
            xmlHttp.open( "GET", strDataFile, true );
            strData = null;
    }

    // set onload data event-handler
    xmlHttp.onreadystatechange = new Function( "", "processResponse(" + intID + ")" );

    // send request to server
    xmlHttp.send( strData );    // param = POST data
}

/**
 * process the response data from server
 *
 * @param intID, Integer, ID of this response
 */
function processResponse( intID )
{
    // 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.readyState )
    {
        // uninitialized
        case 0:
        // loading
        case 1:
        // loaded
        case 2:
        // interactive
        case 3:
            break;
        // complete
        case 4:
            // check http status
            if( xmlHttp.status == 200 )    // success
            {
            	return processData( xmlHttp, intID );
            }
            // loading not successfull, e.g. page not available
            else
            {

                if( window.handleAJAXError )
                    handleAJAXError( xmlHttp, intID );
                else
                    alert( "ERROR\n HTTP status = " + xmlHttp.status + "\n" + xmlHttp.statusText ) ;
            }
    }

    return false;
}


// process data from server
function processData( xmlHttp, intID )
{
    var r = xmlHttp.responseText.replace(/^\s*|\s*$/g,"");
    var xmlDoc = null;
	debugAjax("##RESPONSE##\n"+r);
	
    if(IE == false){
    	var parser = new DOMParser();
    	xmlDoc = parser.parseFromString(r, "text/xml");
    }else{
    	xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
       	xmlDoc.loadXML(r);
    }
	
	var axFunction  = xmlDoc.getElementsByTagName("cbMethod")[0].firstChild.nodeValue;
	var axParams	= new Array();

	var tmp = xmlDoc.getElementsByTagName("result");
	debugAjax("##PARAMETERS ("+tmp.length+" elements) ##\n");
	for(i=0; i < tmp.length; i++){
		try {
			axParams[i] = tmp[i].firstChild.nodeValue;
			debugAjax("...param ("+ axParams[i].length +" chars)");
		} catch (e) {
			debugAjax("...param aborted");
		}	
	}

	try {
			debugAjax("##CALL FCT##\n call: "+axFunction);
			var callback = eval(axFunction);
			callback(eval(axParams));

		} catch (e) {
			alert("Caught error " + e + ": Could not eval " + axParams );
			debugAjax("Caught error " + e + ": Could not eval " + axParams);
		}
	return true;
}


// handle response errors
function handleAJAXError( xmlHttp, intID )
{
	debugAjax("##AJAX-ERROR##\nOBJ="+xmlHttp+" ID="+intID+" STATE="+xmlHttp.status+"\n text:"+xmlHttp.responseText);
}


/**
 * appends an ajax-output message in the textfield.
 */
function debugAjax(message)
{
	if(isAjaxDebug==false){
		return;
	}
	var tmp = document.getElementById("ax_console");
	if(tmp!=null){	
		tmp.innerHTML=tmp.innerHTML+ getTimestamp()+"-&gt;"+ message+"\n\n";
	}
}

/**
 * returns the current timestamp of the user.
 */
function getTimestamp()
{
	var d   = new Date();
	
	return (d.getYear() + (d.getYear() < 2000 ? 1900 : 0 ))+"-"+
		   ((d.getMonth() < 10 ? "0" : "" )+d.getMonth())+"-"+
		   ((d.getDate() < 10 ? "0" : "" )+d.getDate())+" "+
		   ((d.getHours() < 10 ? "0" : "" )+d.getHours())+":"+
		   ((d.getMinutes() < 10 ? "0" : "" )+d.getMinutes())+":"+
		   ((d.getSeconds() < 10 ? "0" : "" )+d.getSeconds());
}

