/**
 * Some common JS-functions for the digitalworkroom
 * @version $Revison$
 */
/*********************************
	dc_HTTPrequest		
	dc_PrepareQuery
	dc_ExecuteHttpRequest
	dc_PrepareResult
	dc_ReplaceResult
	dc_ReturnResult
	dc_DWXrequest
********************************/

var init_AJAX_print = false;
var init_AJAX_mail = true;

var tmp1 = false;
var tmp2 = false;
var evalTO = false;

function dc_HTTPrequest(page,params,fm,fmAll,requestMode,targetObj)
{
	this.http_request = false;
	this.r_query = '';
	this.r_page = (page != '' ? page : 'parse.php');
	this.r_params = params;
	this.r_form = (fm != '' ? document.forms[fm] : false);
	this.r_form_send = fmAll;
	this.r_mode = requestMode;
	this.r_object = (targetObj != '' ? targetObj : false);
	this.r_objectMulti = new Array();
	this.r_result = false;
	this.r_resultMulti = new Array();
	this.prepareQuery = dc_PrepareQuery;
	this.executeRequest = dc_ExecuteHttpRequest;
	this.prepareResult = dc_PrepareResult;
	this.replaceResult = dc_ReplaceResult;
	this.returnResult = dc_ReturnResult;
	this.executeJS = dc_ExecuteJS;
	
	if(this.r_form_send == '') this.r_form_send = false;
	if(this.r_mode != 'GET' && this.r_mode != 'POST') this.r_mode = 'GET';
	if(this.r_object)
	{
		if(this.r_object != '')
		{
			this.r_params = (this.r_params != '' ? this.r_params+'&AJAX_TMPL='+this.r_object : 'AJAX_TMPL='+this.r_object);
		}
	}
}

function dc_PrepareQuery()
{
	var a,aa,el,elType,elName,retFirst,retLast,fLength;
	
	if(this.r_form && this.r_form_send)
	{
		fLength = this.r_form.elements.length;
		for(a=0; a<fLength; a++)
		{
			el = this.r_form.elements[a];
			if(el.type)
			{
				elType = el.type.toLowerCase();
				elName = el.nodeName.toLowerCase();
				switch(elType)
				{
					case 'select':
					case 'select-one':
						for(aa=0; aa<el.length; aa++)
						{
							if(el.options[aa].selected)
							{
								if(this.r_query != '') this.r_query += '&';
								this.r_query += el.name+'='+escape(el.options[aa].value);
							}
						}
					break;
					
					case 'radio':
					case 'checkbox':
						for(aa=0; aa<el.length; aa++)
						{
							if(el[aa].checked)
							{
								if(this.r_query != '') this.r_query += '&';
								this.r_query += el.name+'='+escape(el[aa].value);
							}
						}
					break;
					
					case 'text':
					case 'hidden':
						if(this.r_query != '') this.r_query += '&';
						this.r_query += el.name+'='+escape(el.value);
					break;
				}
			}
			if(elName == 'textarea')
			{
				if(this.r_query != '') this.r_query += '&';
				this.r_query += el.name+'='+escape(el.value);
			}
		}
		if(this.r_form.action != '')
		{
			var fa = this.r_form.action.split('?');
			if(fa[1])
			{
				if(this.r_query != '') this.r_query += '&';
				this.r_query += fa[1];
			}
		}
	}
	
	if(this.r_params != '')
	{
		var splitParams = this.r_params.split('&');
		var splitParamsSub;
		for(a=0; a<splitParams.length; a++)
		{
			splitParamsSub = splitParams[a].split('=');
			if(this.r_query != '') this.r_query += '&';
			this.r_query += splitParamsSub[0]+'='+escape(splitParamsSub[1]);
		}
	}
}

function dc_ExecuteHttpRequest() 
{
	if (window.XMLHttpRequest) 
	{ // Mozilla
		this.http_request = new XMLHttpRequest();
		if (this.http_request.overrideMimeType) 
		{
			this.http_request.overrideMimeType('text/xml');
		}
	}
	else if (window.ActiveXObject) 
	{ // IE
		try 
		{
			this.http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			try 
			{
				this.http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) 
			{}
		}
	}
	if (this.http_request) 
	{
		// m = 'GET';
		if(this.r_mode == 'POST')
		{
			// this.http_request.onreadystatechange = this.prepareResult;
			this.http_request.open("POST", this.r_page, false);
			this.http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			this.http_request.setRequestHeader("Content-Length", this.r_query.length);
			this.http_request.setRequestHeader("Connection", "close");
			this.http_request.send(this.r_query);
		}
		else if(this.r_mode == 'GET')
		{
			// this.http_request.onreadystatechange = this.prepareResult;
			this.http_request.open("GET", this.r_page+'?'+this.r_query, false);
			this.http_request.send(null);
		}
	}
}

function dc_PrepareResult()
{
	var retIdStart,retIdEnd,retFirst,retLast;
	var a;

	if(this.http_request.readyState)
	{
	    if (this.http_request.readyState == 4)
	    {
	        if (this.http_request.status == 200)
	        {
	        	this.r_result = this.http_request.responseText;
	        }
	    }
	}
	
	if(this.r_result)
	{
		if(window.dc_ConvertSpecialChars)
		{
			this.r_result = dc_ConvertSpecialChars(this.r_result);
		}
	}
	
	if(this.r_result && this.r_object)
	{
		this.r_objectMulti = this.r_object.split(',');
		for(a=0; a<this.r_objectMulti.length; a++)
		{
			retIdStart = '<!-- AJAX_TMPL:'+this.r_objectMulti[a]+':start -->';
			retIdEnd = '<!-- AJAX_TMPL:'+this.r_objectMulti[a]+':end -->';
			
			retFirst = this.r_result.indexOf(retIdStart);
			retLast = this.r_result.indexOf(retIdEnd,retFirst);
			
			if(retFirst >= 0 && retLast > retFirst)
			{
				this.r_resultMulti[a] = this.r_result.substring(retFirst+retIdStart.length,retLast-1);
			}
		}
	}
}

function dc_ReplaceResult()
{
	var a;
	if(this.r_objectMulti.length > 0)
	{
		for(a=0; a<this.r_objectMulti.length; a++)
		{
			if(this.r_resultMulti[a])
			{
				if(document.getElementById(this.r_objectMulti[a]))
				{
					tmp1 = this.r_objectMulti[a];
					tmp2 = this.r_resultMulti[a];
					if(window.dc_ConvertSpecialChars)
					{
						tmp2 = dc_ConvertSpecialChars(tmp2);
					}
					setTimeout("document.getElementById(tmp1).innerHTML=tmp2;",100);
					//alert('replace multi '+this.r_objectMulti[a]);
				}
			}
		}
	}
	else if(this.r_result && this.r_object)
	{
		if(document.getElementById(this.r_object))
		{
			tmp1 = this.r_object;
			tmp2 = this.r_result;
			if(window.dc_ConvertSpecialChars)
			{
				tmp2 = dc_ConvertSpecialChars(tmp2);
			}
			setTimeout("document.getElementById(tmp1).innerHTML=tmp2;",100);
			//alert('replace single '+this.r_object);
		}
	}
}

function dc_ExecuteJS(goAlert)
{
	var a,aa,jsString,jsSubstring;
	var jsStart = '<!-- AJAX_JS:start:';
	var jsEnd = ':end:AJAX_JS -->';
	jsEval = '';
	if(this.r_result.indexOf(jsStart) >= 0 && this.r_result.indexOf(jsEnd) >= 0)
	{
		jsString = this.r_result.split(jsStart);
	for(a=0; a<jsString.length; a++)
	{
			if(jsString[a].indexOf(jsEnd) > 0)
		{
				jsSubstring = jsString[a].split(jsEnd);
			jsEval += jsSubstring[0];
		}
	}
	}
	if(jsEval != '')
	{
		if(window.dc_ConvertSpecialChars)
		{
			jsEval = dc_ConvertSpecialChars(jsEval);
		}
		// if(goAlert) alert(jsEval);
		evalTO = setTimeout("eval(jsEval)",500);
	}
}

function dc_ReturnResult()
{
	if(this.r_result)
	{
		if(window.dc_ConvertSpecialChars)
		{
			this.r_result = dc_ConvertSpecialChars(this.r_result);
		}
		return this.r_result;
	}
}

function dc_DWXrequest(page,params,fm,fmAll,requestMode,targetObj,m,goJS,goAlert)
{
	if(!m) var m = true;
	dc_DWX = new dc_HTTPrequest(page,params,fm,fmAll,requestMode,targetObj);
	dc_DWX.prepareQuery();
	dc_DWX.executeRequest();
	dc_DWX.prepareResult();
	if(m != 'return_only') dc_DWX.replaceResult();
	if(goAlert) alert(dc_DWX.r_result);
	if(goJS) dc_DWX.executeJS(goAlert);
	return dc_DWX.r_result;
}

/* Print */

function dw_print_mode(m)
{
	if(document.forms['fm_print_text_add'])
	{
		document.forms['fm_print_text_add'].elements['xmlval_PRINT_MODE[0]'].value = m;
		if(init_AJAX_print && window.dc_DWXrequest)
		{
			dc_DWXrequest('parse.php','','fm_print_text_add',true,'GET','content','');
			window.print();
		}
		else
		{
			setTimeout("document.forms['fm_print_text_add'].submit()",100);
		}
	}
}

/* Mail */
function dw_sendmail(alertText,mlayId)
{
	if(
		document.forms['arcticleMailForm'].elements['xmlval_SENDER_MAIL[0]'].value.length <= 0  ||
		document.forms['arcticleMailForm'].elements['xmlval_RECEPIENT_MAIL[0]'].value.length <= 0
	)
	{
		alert(dc_ConvertSpecialChars(alertText));
	}
	else
	{
		var f = document.forms['arcticleMailForm'];
		var retMsgId = '<!-- AJAX_MAIL_MESSAGE:';
		var retMsg = '';
		var retFirst = -1;
		var retLast = -1;
		
		f.elements['mlay_id'].value=mlayId;
		f.elements['send_email'].value='yes';
		if(init_AJAX_mail && window.dc_DWXrequest)
		{
			retMsg = dc_DWXrequest('parse.php','','arcticleMailForm',true,'GET','content','return_only');
			retFirst = retMsg.indexOf(retMsgId);
			if(retFirst > -1)
			{
				retLast = retMsg.indexOf(' -->',retFirst);
				if(retLast > -1)
				{
					retMsg = retMsg.substring(retFirst+retMsgId.length,retLast);
					alert(retMsg);
				}
			}
		}
		else
		{
			setTimeout("document.getElementById('arcticleMailForm').submit();",100);
		}
	}
}

/* Swap visibility */
function dc_toggleVisibility(divID)
{
	var x = ( dc_divIsVisible(divID) ? dc_hideDiv( divID ) : dc_showDiv( divID ) );
}
/* Check if the DIV is visible or not  */
function dc_divIsVisible(divID){
	var e = document.getElementById(divID);
	if (!e) return false;
	return ( e.style.visibility == 'visible') ;
}
/* Show the DIV */
function dc_showDiv(divID)
{
	var e = document.getElementById(divID);
	if (!e) return false;
	e.style.visibility	='visible';
	e.style.display		='block';											
}

/* Hide the DIV */
function dc_hideDiv(divID)
{
	var e = document.getElementById(divID);
	if (!e) return false;
	e.style.visibility	='hidden';
	e.style.display		='none';											
}

function dc_fillFieldsFromSelection(valueSource,fieldName){
	var fieldValue	= valueSource.options[ valueSource.selectedIndex ].value;

	var argv	= dc_fillFieldsFromSelection.arguments;
	var argc	= dc_fillFieldsFromSelection.arguments.length;
	
	for (var i=1;i < argc; i++ )
	{
		var p = fieldValue.indexOf('|');
		if ( !p || p ==-1 || i == (argc - 1) ) p = fieldValue.length
		var f = document.forms[0].elements['xmlval_'+argv[ i ]+'[0]'];
		var v = fieldValue.substring(0,p);
		fieldValue = fieldValue.substring(p+1);
		f.value = v;
	}
}

var onlinePopUp = false;
function rwaShowOnlineCatalog(popUpLink)
{
	if (onlinePopUp && typeof onlinePopUp.close != "undefined")
	 onlinePopUp.close();

	onlinePopUp = false;
	var popUpTop = 0;
	var popUpLeft = 0;	
	var popUpWidth = 640;
	var popUpHeight = 480;
	if (typeof screen != "undefined")
	{
		if (screen.width) popUpWidth = screen.width;	
		if (screen.height) popUpHeight = screen.height;	
		if (screen.availWidth) popUpWidth = screen.availWidth;
		if (screen.availHeight) popUpHeight = screen.availHeight;
	}

	onlinePopUp = window.open(popUpLink,"ONLINE_PREVIEW","width="+popUpWidth+",height="+popUpHeight+",top="+popUpTop+",left="+popUpLeft+",menubar=no,scrollbars=no,location=0,resizable=1,directories=0,toolbar=0");
	if (onlinePopUp == false)
	 alert('Um unsere Kataloge durchblättern zu können, müssen Sie eventuell vorhandene PopUpBlocker in Ihrem Browser für die Seite http://'+document.location.hostname+' deaktivieren.');
}

/**
 * Auf diesem Server mitloggen
 */
var dwStatistikServer = 'www.lagerhaus.at';

/**
 * Installiert Tracker-Scripts
 */
function installTracker(){
	var linkList = document.links;

	if (typeof linkList.length == "undefined" || linkList.length == 0)
	 return void(0);

	var i = 0;
	var link = false;
	var hRef = false;
	var mySelf = document.location.host;
	for(i=0;i<linkList.length;i++)
	{
		hRef = linkList[i].href.toString();
		// Ist ein ein Download?
		if (hRef.indexOf("/mmedia/") >0 || hRef.indexOf("/media.php?")  >0 ){
			if (hRef.indexOf("?id="))
			{	// Diverse %-Notatione wegnehmen
				while ( (p = hRef.indexOf("%2C")) >=0 )
				 hRef = hRef.substr(p+3);
				// Der Rest muss BASE64-Codiert sein

				hRef = decodeBase64(unescape(hRef)).toString();
				if ( (p = hRef.match(/rn=([^&]+)/i))){
					hRef = unescape(p[1]);				
				}
				else if ( (p = hRef.match(/fn=([^&]+)/i)) ){
					hRef = unescape(p[1]);
					if ( (p= hRef.indexOf("=")) >0)
					 hRef = hRef.substr(p+1);
				}
				// Das wollen wir doch mitschreiben ...
				linkList[i].trackerTopic = '/download/'+hRef;
				linkList[i].targetEntry = hRef;
				linkList[i].setAttribute("onclick",(document.all ? function(){trackIt(this);} : "javascript:trackIt('"+linkList[i].trackerTopic+"','"+linkList[i].trackerTopic+"');" ) );				
			}
			continue;
		}

		// Diverse Link-Variationen auf den Server selbst
		if (hRef.toLowerCase().indexOf(mySelf.toLowerCase()) == 0 || hRef.indexOf("/") == 0 || hRef.indexOf("?") == 0 || hRef.indexOf("parse.php?") == 0 || hRef.indexOf("id?") == 0 || hRef.indexOf("/parse.php?") == 0 || hRef.indexOf("/id?") == 0)
		{
			// Das wollen wir doch mitschreiben ...
			linkList[i].trackerTopic = '';
			linkList[i].targetEntry = hRef;
			linkList[i].setAttribute("onclick",(document.all ? function(){traceRoute(this);} : "javascript:traceRoute('"+linkList[i].trackerTopic+"','"+linkList[i].trackerTopic+"');" ) );

			continue;
		}

		if (hRef.search(/(http|https|ftp)\:\/\//i) ==0 )
		{
			// Link auf sich selbst?
			if (hRef.toLowerCase().indexOf("://"+mySelf.toLowerCase()) >=0)
			{
				linkList[i].trackerTopic = '';
				linkList[i].targetEntry = hRef;
				linkList[i].setAttribute("onclick",(document.all ? function(){traceRoute(this);} : "javascript:traceRoute('"+linkList[i].trackerTopic+"','"+linkList[i].trackerTopic+"');" ) );
			}
			else
			{
				linkList[i].trackerTopic = '/outbound/'+hRef;
				linkList[i].targetEntry = hRef;
				linkList[i].setAttribute("onclick",(document.all ? function(){trackIt(this);} : "javascript:trackIt('"+linkList[i].trackerTopic+"','"+linkList[i].trackerTopic+"');" ) );
			}
		}
	}
	return void(0);	
}

function trackIt(topic,targetEntry){
	var ref   = escape(document.referrer || "" )+"";
	var entry = escape(unescape(document.location.href));
	var loc = escape((typeof topic == "string" ? topic : topic.trackerTopic));
	var time = new Date().getTime();
	
	var URL = "/track/view.php?ref="+ref+"&entry="+entry+"&loc="+loc+"&time="+time;
	if (typeof dwStatistikServer != "undefined" && dwStatistikServer != "")
	 URL = "http://"+dwStatistikServer+URL;
	var jsCode = "var i = new Image(); i.src ='"+URL+"';";	
	window.setTimeout(jsCode,10);	
}

function traceRoute(topic,targetEntry){
	var ref   = escape(document.referrer || "" )+"";
	var entry = escape(unescape(document.location.href));
	var loc = escape((typeof topic == "string" && topic != "undefined" ? topic : topic.trackerTopic));
	var entry2 = escape((typeof targetEntry == "string"  && targetEntry != "undefined" ? targetEntry : topic.targetEntry));
	var time = new Date().getTime();

	var URL = "/statistik/trace.php?ref="+ref+"&entry="+entry+"&entry2="+entry2+"&loc="+loc+"&time="+time;
	if (typeof dwStatistikServer != "undefined" && dwStatistikServer != "")
	 URL = "http://"+dwStatistikServer+URL;
	var jsCode = "var i = new Image(); i.src ='"+URL+"';";
	window.setTimeout(jsCode,10);	
}



function decodeBase64(input){
	if (typeof input != "string" || input.length ==0 )
	 return input;
//	if (window.atob) return window.atob(input);

	var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var output = [];
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;

   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output[output.length] = String.fromCharCode(chr1);

      if (enc3 != 64) output[output.length] = String.fromCharCode(chr2);
      if (enc4 != 64) output[output.length] = String.fromCharCode(chr3);
   } while (i < input.length);
   return output.join("");
}

window.setTimeout("installTracker()",1000);
