// global xmlhttprequest object
var xmlHttp = false;
var Showdates;

/** von prototype **/

function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }
  return elements;
}


/** 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 xmlHttpReq = 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 )
                    {
                        xmlHttpReq = new ActiveXObject( "Microsoft.XMLHTTP" );    
                    }
                    // try to use the latest msxml dll
                    else
                    {
                        
                        xmlHttpReq = new ActiveXObject( "Msxml2.XMLHTTP." + i + ".0" );
                    }
                    break;
                }
                catch( excNotLoadable )
                {
                    xmlHttpReq = false;
                }
            }
        }
        // Mozilla, Opera und Safari
        else if( window.XMLHttpRequest )
        {
            xmlHttpReq = new XMLHttpRequest();
        }
    }
    // loading of xmlhttp object failed
    catch( excNotLoadable )
    {
        xmlHttpReq = false;
    }
    return xmlHttpReq ;
}


/**
 * sends a http request to server
 *
 * @param strSource, String, datasource on server, e.g. data.php
 *  @param fnProv, String, with function name which wil be called
 * @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, fnProc )
{

    var strData = null;
    var dataReturn = strData
    var 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;
    }
    
    // open the connection 
    var strDataFile = strSource + (strData ? '?' + strData : '' );
    xmlHttp.onreadystatechange = new Function("", "processResponse(" + fnProc + ");" );
    xmlHttp.open( "GET", strDataFile, true );

    // send request to server
    xmlHttp.send( strData );    // param = POST data
    
    return dataReturn;
}
    

/**
 * process the response data from server
 *
 * @param fnProc Function, which processes the result
 */
function processResponse( fnProc )
{
    switch( xmlHttp.readyState )
    {
        // uninitialized
        case 0:
        // loading
        case 1:
        // loaded
        case 2:
        // interactive
        case 3:
            break;
        // complete
        case 4:    
            // check http status
            try 
            {
              if( xmlHttp.status == 200 )    // success
              {
//alert("Test, Function:"+fnProc);
                fnProc( xmlHttp );
              }
              // loading not successfull, e.g. page not available
              else
              {
                if( window.handleAJAXError )
                  handleAJAXError( xmlHttp );
                else
                  alert( "ERROR\n HTTP status = " + xmlHttp.status + "\n" + xmlHttp.statusText ) ;
              }
            }
            catch (E)
            {
            }
    }
}

/** End AJAX functions **/



/** real application functions **/

function showError(errtext)
{
  $("error").innerHTML = errtext;
  $( "error" ).style.visibility = "visible";
  $( "error" ).style.height = "1.5em";
  $( "redzusatz" ).style.visibility = "hidden";

}
//============================================================================
function PerformCheck()
{
	
	if ($("Vorname" ).value <= " ")
	{
		showError("Bitte geben Sie Ihren Namen ein!");
		return false;
	}
	if ($("Nachname" ).value <= " ")
	{
		showError("Bitte geben Sie Ihren Nachnamen ein!");
		return false;
	}
	if ($("Strasse" ).value <= " ")
	{
		showError("Bitte geben Sie Ihre Strasse ein!");
		return false;
	}
	if ($( "PLZ" ).value <= " ")
	{
		showError("Bitte geben Sie Ihre PLZ ein!");
		return false;
	}
	if ($( "Ort" ).value <= " ")
	{
		showError("Bitte geben Sie Ihre Ort ein!");
		return false;
	}
	if ($( "Telefon" ).value <= " ")
	{
		showError("Bitte geben Sie Ihre Telefonnummer ein!");
		return false;
	}
	if ($( "EMail" ).value <= " ")
	{
		showError("Bitte geben Sie Ihre EMail-Adresse ein!");
		return false;
	}
	return true;
	
}

function calenderUpdateDate()
{
	var i;
	var month = Number($( "month" ).value);
	var day = Number($( "day" ).value);
	var year = Number($( "year" ).value);
  // Nach der Schleife steht in i der Index auf den gewünschten Tag oder die nächste Vorstellung
  for (i = 0; i < Showdates.length; i++) 
  {
  	if (Number(Showdates[i]["Year"]) > year)
  	  break
  	else
  	{
    	if (Number(Showdates[i]["Year"]) < year)
    	  continue;
    	else
    	{
        if (Number(Showdates[i]["Month"]) > month)
          break;
        else
        {
          if (Number(Showdates[i]["Month"]) < month)
            continue;
          else
          {
            if (Number(Showdates[i]["Day"]) >= day)
              break;
          }
        }
      }
    }
  }
  if (i < Showdates.length)
  {
  	try 
  	{
      $( "selshow" ).options.selectedIndex = i+1;
      getPriceData($( "selshow" ));
    }
    catch (E)
    {
    }
  }
  return false;
}

function getShowData( objSelect )
{
    showElement('loading');
    var strURL = "getshows.jsp?event=" + objSelect.options[ objSelect.options.selectedIndex ].value;
    sysev = objSelect.options[ objSelect.options.selectedIndex ].value.split(";");
 
    $( "SysID" ).value = sysev[0];
    $( "EventNumber" ).value = sysev[1];
    $( "EventName" ).value = objSelect.options[ objSelect.options.selectedIndex ].text;
    if (sysev[1] != 0)
      sendRequest( strURL, "processShowData" );
    else
     clearData(1);
}

function clearData(level)
{
	switch (level)
	{
		// alles 
		case 1:
        $( "selshow" ).options.length = 0;
    case 2:
        $( "selprice" ).options.length = 0;
    case 3:
        $( "selreduct1" ).options.length = 0;
        $( "selreduct2" ).options.length = 0;
        $( "selreduct3" ).options.length = 0;
        $( "selticket1" ).options.selectedIndex = 0;
        $( "selticket2" ).options.selectedIndex = 0;
        $( "selticket3" ).options.selectedIndex = 0;
        $("Abh_VS").disabled = false;

  }
}

function getPriceData( objSelect )
{
    showElement('loading');
    var sysID = $( "SysID" ).value;
    var eventID = $( "EventNumber" ).value;
    showdatas = objSelect.options[ objSelect.options.selectedIndex ].value.split(";");
    $( "ShowNumber").value = showdatas[ 0 ];
    $( "ShowDate").value = showdatas[ 1 ];
    $( "ShowTime").value = showdatas[ 2 ];

    var strURL = "getprices.jsp?system="+sysID+"&event="+eventID+"&show="+ showdatas[ 0 ];
    if (showdatas[ 0 ] != 0)
      sendRequest( strURL, "processPriceData" );
    else
    	clearData(2);
}

function getReductionData( objSelect )
{
    showElement('loading');
    var sysID = $( "SysID" ).value;
    var eventID = $( "EventNumber" ).value;
    var shownumber = $( "ShowNumber").value;
    pgdatas =  objSelect.options[ objSelect.options.selectedIndex ].value.split(";");
    $( "PriceGroup").value =  pgdatas[0];
    $( "PriceGroupName").value =  pgdatas[1];

    var strURL = "getreductions.jsp?system="+sysID+"&event="+eventID+"&show="+ shownumber+"&pg="+pgdatas[0];
    if (pgdatas != 0)
      sendRequest( strURL, "processReductionData" );
    else
    	clearData(3);
}

// process data from server
function processShowData( xmlHttp )
{
    updateShowResult( );
}

// process data from server
function processPriceData( xmlHttp )
{
    updatePriceResult( );
}

// process data from server
function processReductionData( xmlHttp )
{
    updateReductionResult( );
}

// handle response errors
function handleAJAXError( xmlHttp )
{
    // hide image that indicates search processing
    hideElement( "loading" );
    alert( "Leider ist ein Fehler aufgetreten."+xmlHttp.status ) ;
}


// füllt Selectbox mit Vorstellungen
function updateShowResult( )
{
    response  = xmlHttp.responseXML.documentElement;
    
    var objSelect = $( "selshow" );
    clearData(1);
    
    var nShowCount = response.getElementsByTagName('show').length
    objSelect.options[ 0 ] = new Option( 'Bitte Vorstellung auswählen', 0, false, false );
    Showdates = new Array();
    for (i = 0; i < nShowCount; i++)
    {

        show = response.getElementsByTagName('show');
        itemShowNumber = response.getElementsByTagName('ShowNumber')[i].firstChild.data;
        itemShowDate = response.getElementsByTagName('ShowDate')[i].firstChild.data;
        itemShowTime = response.getElementsByTagName('ShowTime')[i].firstChild.data;
        objSelect.options[ i+1 ] = new Option( itemShowDate+'  '+itemShowTime, itemShowNumber+';'+itemShowDate+';'+itemShowTime, false, false );
        Showdates[i] = new Object;
        showdate = itemShowDate.split(".")
        Showdates[i]["Year"] = showdate[2];
        Showdates[i]["Month"] = showdate[1];
        Showdates[i]["Day"] = showdate[0];
    }

//    $( "selshowdiv" ).style.visibility = "visible";
    var objLogo = $( "logo" );
    var eventID = $( "EventNumber" ).value;
    objLogo.src="logo_"+eventID+".jpg";

}

// füllt Selectbox mit Preisgruppen
function updatePriceResult( )
{
    response  = xmlHttp.responseXML.documentElement;
    
    var objSelect = $( "selprice" );
    clearData(2);
    
    var nPriceCount = response.getElementsByTagName('PG').length
    objSelect.options[ 0 ] = new Option( 'Preisgruppenauswahl', 0, false, false );
    for (i = 0; i < nPriceCount; i++)
    {

        itemPGName = response.getElementsByTagName('PGName')[i].firstChild.data;
        itemPGNumber = response.getElementsByTagName('PGNumber')[i].firstChild.data;
        itemPGPrice = response.getElementsByTagName('PGPrice')[i].firstChild.data;
        itemPGFree = response.getElementsByTagName('PGFree')[i].firstChild.data;
        objSelect.options[ i+1 ] = new Option( itemPGName+'  '+itemPGPrice+' EUR', itemPGNumber+";"+itemPGName+";"+itemPGPrice.replace(",","."), false, false );
    }

//    $( "selpricediv" ).style.visibility = "visible";
    
}

// füllt Selectbox mit Ermäßigungen
function updateReductionResult( )
{
    response  = xmlHttp.responseXML.documentElement;
    
    var objPriceSel = $( "selprice" );
    var pricedata = objPriceSel.options[objPriceSel.options.selectedIndex ].value.split(";");
    
    var objSelect1 = $( "selreduct1" );
    var objSelect2 = $( "selreduct2" );
    var objSelect3 = $( "selreduct3" );
    objSelect1.options.length = 0;
    objSelect2.options.length = 0;
    objSelect3.options.length = 0;
    
    var nRedCount = response.getElementsByTagName('Reduction').length
    objSelect1.options[ 0 ] = new Option( 'Normalpreis', "0;"+pricedata[2].replace(",",".")+";Normalpreis", false, false );
  	$( "ReductionName_1" ).value = "Normalpreis";
  	$( "ReductionName_2" ).value = "";
  	$( "ReductionName_3" ).value = "";
  	$( "TicketPrice_1" ).value = pricedata[2].replace(",",".");
  	$( "TicketPrice_2" ).value = "0.00";
  	$( "TicketPrice_3" ).value = "0.00";
  	$( "Tickets_2" ).value = "0";
  	$( "Tickets_3" ).value = "0";

    if (nRedCount >0)
    {
      objSelect2.options[ 0 ] = new Option( 'Ermäßigungsauswahl', "0;"+pricedata[2].replace(",","."), false, false );
      for ( nCount = 1; nCount <= 16; nCount++)
      {
        $( "selticket2" ).options[nCount] = new Option( nCount, nCount, false, false);
      }
      objSelect3.options[ 0 ] = new Option( 'Ermäßigungsauswahl', "0;"+pricedata[2].replace(",","."), false, false );
      for ( nCount = 1; nCount <= 16; nCount++)
      {
        $( "selticket3" ).options[nCount] = new Option( nCount, nCount, false, false);
      }
    }
    else
    {
      objSelect2.options[ 0 ] = new Option( 'keine Ermäßigung vorhanden', 0, false, false );
    	$( "selticket2" ).options.length = 1;
      objSelect3.options[ 0 ] = new Option( 'keine Ermäßigung vorhanden', 0, false, false );
    	$( "selticket3" ).options.length = 1;
    }
    for (i = 0; i < nRedCount; i++)
    {
        itemRedName = response.getElementsByTagName('RedName')[i].firstChild.data;
        itemRedNumber = response.getElementsByTagName('RedNumber')[i].firstChild.data;
        if (itemRedPrice = response.getElementsByTagName('RedPrice')[i].firstChild)
          itemRedPrice = response.getElementsByTagName('RedPrice')[i].firstChild.data;
        else
          itemRedPrice = "--";
        objSelect1.options[ i+1 ] = new Option( itemRedName+'  '+itemRedPrice+' EUR', itemRedNumber+";"+itemRedPrice.replace(",",".")+";"+itemRedName.replace(";",","), false, false );
        objSelect2.options[ i+1 ] = new Option( itemRedName+'  '+itemRedPrice+' EUR', itemRedNumber+";"+itemRedPrice.replace(",",".")+";"+itemRedName.replace(";",","), false, false );
        objSelect3.options[ i+1 ] = new Option( itemRedName+'  '+itemRedPrice+' EUR', itemRedNumber+";"+itemRedPrice.replace(",",".")+";"+itemRedName.replace(";",","), false, false );
    }
}

function calcPrice(field, objSelect)
{
  field.value = objSelect.options[ objSelect.options.selectedIndex ].value;
  SetVersand();
}

//============================================================================
function MakeFullName() 
{
  var sep = "|";
  $("Name").value = $("Titel").value+sep+$("Vorname").value+sep+$("Nachname").value;
  return;
}

function SetVersand() 
{
  reductid1 = $("selreduct1").value.split(";")[0];
  reductcnt1 = $("selticket1").value;
  reductid2 = $("selreduct2").value.split(";")[0];
  reductcnt2 = $("selticket2").value;
  reductid3 = $("selreduct3").value.split(";")[0];
  reductcnt3 = $("selticket3").value;
  if ( (Number(reductcnt1)>0 ) && (reductid1 > 0) ||
       (Number(reductcnt2)>0 ) && (reductid2 > 0) ||
       (Number(reductcnt3)>0 ) && (reductid3 > 0))
  {
    $("Abh_VS").disabled = true;
    $("Abh_AK").checked = true;
  }
  else
  {
    $("Abh_VS").disabled = false;
  }
}

function GetReduction(field, pricefield, reductfield, objSelect) 
{

  var datas;
  if (objSelect.options[ objSelect.selectedIndex ].value.length > 1)
    datas = objSelect.options[ objSelect.selectedIndex ].value.split(";");
  else
    datas = objSelect.options[ objSelect.selectedIndex ].value;
    
  reductfield.value = datas[0];
  pricefield.value = datas[1];
  field.value = datas[2];

  SetVersand();
  
  return;
}
/* some common helper functions */


// retrieve data from dom tree
function getValues( xmlDocument, strTagName )
{
    var xmlTags;
    if( strTagName )
        xmlTags =  xmlDocument.getElementsByTagName( strTagName );
    else
        xmlTags =  xmlDocument.childNodes;
        
    var intLen = xmlTags.length;
    if( !intLen )
        return null;
    else if( intLen == 1 )
    {
        return xmlTags[ 0 ].firstChild.nodeValue;
    }
    else
    {
        var arrValues = new Array( );
        for( var i = 0; i < intLen; i++ )
        {
            arrValues[ i ] = xmlTags[ i ].firstChild.nodeValue;
        }            
        return arrValues;
    }
}    


// hide an element
function hideElement( strID, blnUseDisplay )
{
    var xmlNode = $( strID );
    if( xmlNode )
        blnUseDisplay ? xmlNode.style.display = "none" : xmlNode.style.visibility = "hidden"; 
}
// makes an element visible
function showElement( strID, blnUseDisplay )
{
    var xmlNode = $( strID );
    if( xmlNode )
        blnUseDisplay ? xmlNode.style.display = "block" : xmlNode.style.visibility = "visible"; 
}


