/****************************************************************
	PROGNOS JAVASCRIPT FRAMEWORK
	code by CATsoft Development GmbH - http://www.catsoft.ch

	Created:		12.05.2006 - MRO
	Last Changes:	17.05.2006 - MRO
****************************************************************/
	

// pf is a simulated namespace, to call a function use: pf.MyFunction();
var pf = {
	
	xmlhttp:null,
	helpInit:0,
	
	getXMLHttp: function( )
	{
	    var xmlHTTP;
		try
        	{
		        xmlHTTP = new XMLHttpRequest();
	        }
	        catch(err)
	        {
		        xmlHTTP = new ActiveXObject("MSXML2.XMLHTTP.3.0");	        
	        }
	    return xmlHTTP;
	},
	
	// Initialise function: is called on every page, loaded in the onload attribut of the <body> tag. 
	Init: function()
	{
		// Sets the WebDatawindow background-color transparent
		if(document.getElementById("objWebDW_datawindow") != null) 
		{
			document.getElementById("objWebDW_datawindow").style.backgroundColor = "transparent";
		}
		// DIV Tag around the datawindow visible/invisible -> workaround for opera browser
		if(pf.Step() == null || pf.Step() == 0 )
		{
			document.getElementById("dwcase").className = 'dwhidden';
		}
		pf.InitHandler();
		
		if (pf.xmlhttp==null)
        {
            pf.xmlhttp = pf.getXMLHttp();
        }
        
        Form1 = document.forms['Form1'];
        if(!Form1)
            Form1 = document.Form1;
        		
		// Custom alerts
		   // over-ride the alert method only if this a newer browser.
        // Older browser will see standard alerts
     /*   if(document.getElementById) {
	        window.alert = function(txt) {
		        pf.createCustomAlert(txt);
	        }
        }*/
	},
	
	
	
	// Determines the current step: on which page the user is.
	Step: function()
	{
		/*if(document.getElementById("objWebDW_datawindow") != null) 
		{*/
			return objWebDW.GetItem(1,"page");
		/*}
		else
		{
			return -1;
		}*/
			
	},
	
   callToServer: function ( URL ) {
      if (!document.createElement) 
        return false;
      var IFrameDoc;
      if (!IFrameObj && document.createElement) {
        // create the IFrame and assign a reference to the
        // object to our global variable IFrameObj.
        // this will only happen the first time 
        // callToServer() is called
       try {
          var tempIFrame=document.createElement('iframe');
          tempIFrame.setAttribute('id','RSIFrame');
          tempIFrame.style.border='0px';
          tempIFrame.style.width='0px';
          tempIFrame.style.height='0px';
          IFrameObj = document.body.appendChild(tempIFrame);
          
          if (document.frames) {
            // this is for IE5 Mac, because it will only
            // allow access to the document object
            // of the IFrame if we access it through
            // the document.frames array
            IFrameObj = document.frames['RSIFrame'];
          }
        } catch(exception) {
          // This is for IE5 PC, which does not allow dynamic creation
          // and manipulation of an iframe object. Instead, we'll fake
          // it up by creating our own objects.
          iframeHTML='\<iframe id="RSIFrame" style="';
          iframeHTML+='border:0px;';
          iframeHTML+='width:0px;';
          iframeHTML+='height:0px;';
          iframeHTML+='"><\/iframe>';
          document.body.innerHTML+=iframeHTML;
          IFrameObj = new Object();
          IFrameObj.document = new Object();
          IFrameObj.document.location = new Object();
          IFrameObj.document.location.iframe = document.getElementById('RSIFrame');
          IFrameObj.document.location.replace = function(location) {
            this.iframe.src = location;
          }
        }
      }
      
      if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
        // we have to give NS6 a fraction of a second
        // to recognize the new IFrame
        setTimeout('callToServer()',10);
        return true;
      }
      
      if (IFrameObj.contentDocument) {
        // For NS6
        IFrameDoc = IFrameObj.contentDocument; 
      } else if (IFrameObj.contentWindow) {
        // For IE5.5 and IE6
        IFrameDoc = IFrameObj.contentWindow.document;
      } else if (IFrameObj.document) {
        // For IE5
        IFrameDoc = IFrameObj.document;
      } else {
        return false;
      }
      
      IFrameDoc.location.replace(URL);
      return true;
    },
        
	// Eigener Event Handler für Mozilla
	myChange: function( event )
	{
		this.bChanged = false;
	}
	,
	// Initialisiert Event Handler
	InitHandler: function()
	{
		var inputs,i;
		
		inputs=document.getElementsByTagName('input');
		for (i = 0; i < inputs.length; i++ )
		{
			try		// Nicht notwendig für ie
			{
				inputs[i].addEventListener("change", pf.myChange, false);
			}
			catch( e ){}
			
		}
	},
	
	
	// Switchs from step to step, forward and backward
	GoToNextPage: function(Direction)
	{
		var i = pf.Step();
		var ValOK = true;
		switch(Direction)
		{
			case "forward":
				ValOK = validate_step(i);
				i += 1;
				break;
			case "backward":
				i -= 1;
				break;
			default :
				alert("only forward and backward allowed as parameters in function pf.GoToNextPage");
				ValOK = false;
				break;
		}
		if(ValOK)
		{
			objWebDW.SetItem( 1, "page", i ); 
			objWebDW.submit();
		}
	},
	
	
	InputAlertBorder: function(FieldName, HasErrors)
	{
	    var el = document.getElementById(FieldName);
	    var clname = ''
	    
	    if( el == null)
	        return;
	        
		if(HasErrors)
		    clname = 'inputalert';

		el.className = clname;

	},
	
	// loopt durch alle IMG elemente in der Seite und sucht anhand des onclick events 
	// des IMG tags den Infobutton aus dem Datawindow.
	setInfoVisibility: function(varButtonname, varVisibility)
	{
		// IE 58 GECKO 35
		var oIMG = document.getElementsByTagName("IMG");
		var crossFix = 0;
		for (LC = 0; LC < oIMG.length; LC++ )
		{
			if(String(oIMG[LC].getAttribute("onclick")).substr(0,4) == "func") {
				crossFix = 58;
			} else {
				crossFix = 35;
			}
			if(String(oIMG[LC].getAttribute("onclick")).substr(crossFix,varButtonname.length) == varButtonname)
			{
				if(varVisibility == true)
				{
					oIMG[LC].style.visibility = 'visible';
				} else {
					oIMG[LC].style.visibility = 'hidden';
				}
			}
		}
	},
	
	
	// FRAMEWORK Input Control disable Script (Step2)
	setFieldStatus: function(rowNumber, dwField, disable)
	{
	    var el = Form1[dwField + '_' + (rowNumber-1)];
	    
	    if (el!=null)
	    {
		    // Disable / Enable a control
		    el.disabled = disable;
		    if(disable == true)
		    {
			    el.style.visibility = "hidden";
			    objWebDW.SetItem(rowNumber,dwField,0);
		    }
		    if(disable == false)
		    {
			    el.style.visibility = "visible";
		    }
		    if(disable == "disable")
		    {
			    el.disabled = true; 
		    }
		    if(disable == "enable")
		    {
			    el.disabled = false; 
		    }
        }
        else
            alert( "Field missing: " + dwField);		
	},
	
	// FRAMEWORK
	setFieldValue: function(rowNumber, dwField, NewVal )
	{
		// Sets a value to a control
		Form1[dwField + '_' + (rowNumber-1)].value = NewVal;
		objWebDW.SetItem(rowNumber,dwField,NewVal);
	},
	
	
	//FRAMEWORK
	setFieldText: function(strField, strText)
	{
	    var el = document.getElementById(strField);
	    if(el!=null)
	    {
		    document.getElementById(strField).innerText = strText; // IE Version
		    document.getElementById(strField).textContent = strText; // Mozilla Version
		}
		else
		    alert( "Missing Textfield: " + strField);
	},
	
	// FRAMEWORK
    createCustomAlertMessage: function (header,txt) {
        pf.createCustomAlertEx( header, txt, null);
    },
    createCustomAlert: function (txt) {
        pf.createCustomAlertEx( ALERT_TITLE, txt, null);
    },
    
    createCustomAlertMsg: function (msg) {
        pf.createCustomAlertEx( ALERT_TITLE, null, msg);
    },
    
    createCustomAlertEx: function (header,txt, msg) {
	    // shortcut reference to the document object
	    d = document;

	    // if the modalContainer object already exists in the DOM, bail out.
	    if(d.getElementById("modalContainer")) return;

        // create the modalContainer div as a child of the BODY element
	    mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
	    mObj.id = "modalContainer";
	     // make sure its as tall as it needs to be to overlay all the content on the page
	    mObj.style.height = document.documentElement.scrollHeight + "px";

        iFrame = mObj.appendChild(d.createElement("iFrame"));
        iFrame.id = "alertFrame";

	    // create the DIV that will be the alert 
	    alertObj = mObj.appendChild(d.createElement("div"));
	    alertObj.id = "alertBox";
	    // MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
	    //if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
	    alertObj.style.top = "100px"; 
	    // center the alert box
	    alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
	    
        iFrame.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
        
	    // create an H1 element as the title bar
	    h1 = alertObj.appendChild(d.createElement("h1"));
	    h1.appendChild(d.createTextNode(header));

	    // create a paragraph element to contain the txt argument
	    if( msg == null )
	    {
	        msg = alertObj.appendChild(d.createElement("p"));
	        msg.appendChild(d.createTextNode(txt));
	    }
	    else
	        alertObj.appendChild( msg );

	    // create an anchor element to use as the confirmation button.
	    btn = alertObj.appendChild(d.createElement("a"));
	    btn.id = "closeBtn";
	    btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
	    btn.href = "#";
	    // set up the onclick event to remove the alert when the anchor is clicked
	    btn.onclick = function() { pf.removeCustomAlert();return false; }

    	
    },

    // removes the custom alert from the DOM
    removeCustomAlert: function () {
	    document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
    },
    
    showBrowsers: function()
    {
       var os = new Array();
       var osName = new Array();
       
       osName = ["Windows","MacOS X", "Linux"];
       
       os[0] = new Array();     // Windows
       os[1] = new Array();     // MacOS X
       os[2] = new Array();     // Linux
       
       os[0] = ["IE 6","IE 7","Firefox 2.0","Firefox 3.0", "Opera 9 (identify as Firefox)","Netscape 8.1","Mozilla Navigator 1.7.13"];
       os[1] = ["Firefox 2.0","Safari"];
       os[2] = ["Firefox 2.0","Mozilla Navigator 1.7","Opera 9 (identify as Mozilla)","SeaMonkey 1.0.4"];

       var msg = document.createElement( "div" );
//       var ositem = msg.appendChild(document.createElement( "ul" ) ); 
       for(var j=0;j<os.length;j++)
       {
           var entry = msg.appendChild(document.createElement( "h2" ));
           entry.appendChild(document.createTextNode( osName[j] ) );           
            
           var items = entry.appendChild(document.createElement( "ul" ) ); 
           for(var i=0;i<os[j].length;i++)
           {
               var entry = items.appendChild(document.createElement( "li" ));
               entry.appendChild(document.createTextNode( os[j][i] ) );     
           }
        }
        pf.createCustomAlertEx( 'Info',null, msg);
    },
	
	// FRAMEWORK
    openHelp: function (txt) {
	    // shortcut reference to the document object
	    d = document;

	    // if the modalContainer object already exists in the DOM, bail out.
	    if(d.getElementById("helpContainer")) return;

	    // create the modalContainer div as a child of the BODY element
	    temp = d.createElement("div")
	    temp.id = "helpContainer";
	    temp.style.height = document.documentElement.scrollHeight + "px";
	    
        iFrame = temp.appendChild(d.createElement("iFrame"));
        iFrame.id = "helpFrame";

	    // create the DIV that will be the alert 
	    alertObj = temp.appendChild(d.createElement("div"));
	    alertObj.id = "helpBox";
	    // MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
	    //if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
	    alertObj.style.top = "100px"; 
	    // center the alert box	    
	    alertObj.style.left = 100; //(d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";

	    // create an H1 element as the title bar
	    h1 = alertObj.appendChild(d.createElement("h1"));
	    h1.appendChild(d.createTextNode(HELP_TITLE));

	    // create a paragraph element to contain the txt argument
	    msg = alertObj.appendChild(d.createElement("p"));
	    msg.appendChild(d.createTextNode(txt));

	    // create an anchor element to use as the confirmation button.
	    btn = alertObj.appendChild(d.createElement("a"));
	    btn.id = "closeBtn";
	    btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
	    btn.href = "#";
	    // set up the onclick event to remove the alert when the anchor is clicked
	    btn.onclick = function() { pf.closeHelp();return false; }
	    
	    d.getElementsByTagName("body")[0].appendChild(temp);
    	return true;
    },

    // removes the custom alert from the DOM
    closeHelp: function () {
	    document.getElementsByTagName("body")[0].removeChild(document.getElementById("helpContainer"));
    },
    
    initHelp: function()
    {
        if( pf.xmlhttp != null)
        {
            pf.helpInit = 1;
            pf.help('init',kanton, language);
        }
    },
        
    help: function ( id, user, language )
    {   	
        var ok = false;
        if (pf.xmlhttp!=null)
        {
            if ((pf.xmlhttp.readyState > 0 ) && (pf.xmlhttp.readyState < 4 ))
              return;

            var req = "as_user=" + user + "&as_lang=" + language + "&as_id=" + id;
            try
            {
                ok = true;
                pf.xmlhttp.open("POST",wslocation + "/help",true);
                pf.xmlhttp.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
                pf.xmlhttp.setRequestHeader( 'Content-Length', req.length );
                pf.xmlhttp.onreadystatechange = pf.helpResponse; 
                pf.xmlhttp.send( req );
             }
             catch(e)
             {
                // XML HTTP open blockiert;
                ok = false;
             }
        }
        if (!ok)
        {
            if (pf.callToServer( "help.aspx?id=" + id ))
            {
              var doc = IFrameObj.contentWindow.document;
              if(doc!=null)
              {
                var el = doc.getElementById("helptext");
                if(el!=null)
                    ok = (pf.openHelp(el.innerHTML));
              }
            }
         }
        if(!ok)
            open( 'help.aspx?id=' + id, 'Info', 'left=20,top=20,width=520,height=400,toolbar=no,resizable=no,scrollbars=yes');
   },
   
    checkElko: function ( verh, zivv, zivm, user, language )
    {   	
        var res = -1;
        var req = "as_user=" + user + "&as_language=" + language + "&ai_verh=" + verh + "&ai_v=" + zivv + "&ai_m=" + zivm;
        var ok = false;
        
        if (pf.xmlhttp!=null)
        {

            if ((pf.xmlhttp.readyState > 0 ) && (pf.xmlhttp.readyState < 4 ))
              return;
            try
            {
                pf.xmlhttp.open("POST",wslocation + "/checkelko",false);
                pf.xmlhttp.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
                pf.xmlhttp.setRequestHeader( 'Content-Length', req.length );
                pf.xmlhttp.send( req);
                if (pf.xmlhttp.status == 200) 
                {
                    if (pf.xmlhttp.responseXML!=null)
                    {
                        var s = pf.xmlhttp.responseText
                        try
                        {
                            i = s.indexOf( '<string' );
                            i = s.indexOf( '>', i );
                            j = s.indexOf( '<', i );
                            s = s.slice( i+1, j );
                        }
                        catch(e)
                        {
                            //
                        }   
                    res = parseInt(s);
                    }                    
                    else
                        alert( pf.xmlhttp.responseText);
                 }
                 ok = true;
            }
            catch(e)
            {
                // XML HTTP open blockiert;
            }
        }
        if(!ok) 
        {
            if (pf.callToServer( "checkelko.aspx?" + req ))
            {
              var doc = IFrameObj.contentWindow.document;
              if(doc!=null)
              {
                var el = doc.getElementById("result");
                if(el!=null)
                    res = parseInt(el.innerHTML);
              }
            }
            else
                res = 1;        // Check on server side
        }
        return res;
   },
    	
    helpResponse: function()
    {
        switch( pf.xmlhttp.readyState )
        {
            case 0:
            // loading
            case 1:
            // loaded
            case 2:
            // interactive
            case 3:
                break;
            // complete
            case 4:    
                // check http status
                if( pf.xmlhttp.status == 200 )    // success
                {
                    if (pf.helpInit == 1)
                    {
                        pf.helpInit = 0;
                        return;
                    }
                    var s = pf.xmlhttp.responseText
                    try
                    {
                        i = s.indexOf( '<string' );
                        i = s.indexOf( '>', i );
                        j = s.indexOf( '<', i );
                        s = s.slice( i+1, j );
                    }
                    catch(e)
                    {
                        alert( pf.xmlhttp.responseText );
                    }   
                    pf.openHelp( s );
                }
                // loading not successfull, e.g. page not available
                else
                {
			        alert( pf.xmlhttp.responseText );
                }
        }
    }
}

