// global xmlhttprequest object
var xmlHttp = false;
/** 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
 */
var msProgIDs = ["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];

function getXMLRequester (){
	var req = null;
	try
	{
		if (window.XMLHttpRequest)
			req = new XMLHttpRequest();
		else if (window.ActiveXObject)
		{
			while (!req && msProgIDs.length)
			{
				try { req = new ActiveXObject(msProgIDs[0]); } catch (e) { req = null; }
				if (!req)
					msProgIDs.splice(0, 1);
			}
		}
	}
	catch (e) { req = null;	}

	if (!req)
		alert("Der Inhalt konnte nicht geladen werden!" );

	return req;
};

/**
 * 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, intID , FctID){
   
    if( !strData )
        strData = '';

    // default type (0 = GET, 1 = xml, 2 = POST )
    if( isNaN( intType ) )
        intType = 0; // GET

    //default id
    if (isNaN(intID))
      intID = 0;
      
    // 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( '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 + ", " + FctID + ")" ); ;

    // send request to server
    xmlHttp.send(strData);    // param = POST data    
    return dataReturn;
}
    

/**
 * process the response data from server
 *
 * @param intID, Integer, ID of this response
 */
function processResponse(intID, FctID){
    // 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
            // success
          try {
            if (xmlHttp.status == 200) {
              processData(xmlHttp, intID, FctID);
            }
            // 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);
            }
          } catch (e) { }
    }
}

/** End AJAX functions **/

function handleAJAXError(xmlHttp, intID) {
  try{}
  catch(e){}
}

/** real application functions **/

// process data from server
function processData( xmlHttp, intID, FctID ){  
  
// process text data
  if (intID == 1) {
    SetCatEintraege(xmlHttp.responseText);
    GetRubrikSubMenu(FctID);
  }
  if (intID == 2) {
    SetArtikelDetails(xmlHttp.responseText);
  }
  if (intID == 3) {
    FotoBoxID = 'InhaltFotostreckeBereich';
    TMP = xmlHttp.responseText;
    document.getElementById(FotoBoxID).innerHTML = TMP;
    centerAll(FotoBoxID);
  }
  if (intID == 4) {
    SetSubMenu(xmlHttp.responseText);
  }
  if (intID == 5) {
    SetFotostrecken(xmlHttp.responseText);
  }
  if (intID == 6) {
    htmldata = xmlHttp.responseText;
    htmldata = htmldata.substring(htmldata.indexOf('##BeginContent##') + 16, htmldata.indexOf('##EndContent##'));    
    SetTouchCatEintraege(htmldata);    
    GetRubrikSubMenu(FctID);
  }
  if (intID == 7) {
    showInfoBox(xmlHttp.responseText);
  }
  if (intID == 8) {
    location.href = location.href;
  }
  if (intID == 9) {
    AnzeigeBoxID = 'InhaltFamilienanzeigeBereich';
    TMP = xmlHttp.responseText;
    document.getElementById(AnzeigeBoxID).innerHTML = TMP;
    setTimeout("centerAll('"+AnzeigeBoxID+"');", 500);
  }
  if (intID == 10) {
    PRTextBildBoxID = 'InhaltPRTextBildBereich';
    TMP = xmlHttp.responseText;
    document.getElementById(PRTextBildBoxID).innerHTML = TMP;
    centerAll(PRTextBildBoxID);
  }
  if (intID == 11) {
    htmldata = xmlHttp.responseText;
    htmldata = htmldata.substring(htmldata.indexOf('##BeginContent##') + 16, htmldata.indexOf('##EndContent##'));
    if (htmldata != '') {
      year = htmldata.substring(htmldata.indexOf('##BeginYear##') + 13, htmldata.indexOf('##EndYear##'));
      month = htmldata.substring(htmldata.indexOf('##BeginMonth##') + 14, htmldata.indexOf('##EndMonth##'))-1;
      day = htmldata.substring(htmldata.indexOf('##BeginDay##') + 12, htmldata.indexOf('##EndDay##'));
      min = htmldata.substring(htmldata.indexOf('##BeginMin##') + 12, htmldata.indexOf('##EndMin##'));
      hour = htmldata.substring(htmldata.indexOf('##BeginHour##') + 13, htmldata.indexOf('##EndHour##'));
      sec = htmldata.substring(htmldata.indexOf('##BeginSec##') + 12, htmldata.indexOf('##EndSec##'));
      setSpielzeit(new Date(year,month,day,hour,min,sec));
    }
  }
      
}

var TouchMode;

// process data from server
function GetArtikelVorschau(RubrikID) {
  sendRequest("/ArtikelLoad.aspx?aj=1&rid=" + RubrikID, '', REQUEST_POST, 1, RubrikID);
}

function GetTouchArtikelVorschau(RubrikID, mode) {  
  TouchMode = mode;
  if (TouchMode == 1) 
    document.getElementById('TouchFlowBox').style.left = "500px";  
  if (TouchMode == -1)
    document.getElementById('TouchFlowBox').style.left = "-500px";  
  sendRequest("/ArtikelLoad.aspx?aj=1&rid=" + RubrikID, '', REQUEST_POST, 6, RubrikID);
}

function GetArtikelDetails(ArtikelID) {
  sendRequest("/ArtikelLoad.aspx?aj=1&aid=" + ArtikelID, '', REQUEST_POST, 2, -1);
}

function AJAXGetFotostreckenContent(GID, OID, Mode, OverviewPage) {
  sendRequest('/ArtikelBild.aspx?gid=' + GID + '&o=' + OID + '&mode=' + Mode + '&pg=' + OverviewPage, '', REQUEST_POST, 3, -1);
}

function AJAXGetArtikelBilderContent(AID, OID) {
  sendRequest("/ArtikelBild.aspx?aid=" + AID + "&o=" + OID, '', REQUEST_POST, 3, -1);
}

function AJAXGetPRTextBilderContent(AID, OID) {
  sendRequest("/PRTextBild.aspx?aid=" + AID + "&o=" + OID, '', REQUEST_POST, 10, -1);
}

function AJAXGetTickerZeit() {
  sendRequest("/includes/AJAXTickerZeit.aspx", '', REQUEST_POST, 11, -1);
}

function AJAXGetLifestyleBilderContent(AID, OID) {
  sendRequest("/ArtikelLifestyleBild.aspx?laid=" + AID + "&o=" + OID, '', REQUEST_POST, 3, -1);
}

function GetRubrikSubMenu(RubrikID) {
  sendRequest("/ArtikelSubMenu.aspx?rid=" + RubrikID, 'page=' + location.href, REQUEST_POST, 4, -1);
}

function movfotostrecke(PageID) {
  sendRequest("/BildergalerieUebersicht.aspx?galpage=" + PageID, '', REQUEST_POST, 5, -1);
}

function setmerkzettel(ModulID,DataID,DataGUID) {
  sendRequest("/includes/SetMerkzettel.aspx", 'modID=' + ModulID + '&dataID=' + DataID + '&dataGUID=' + DataGUID, REQUEST_POST, 7, -1);
}

function setKommentarInfo(Mode, ArtikelID, KommentarID) {
  sendRequest("/includes/SetKommentar.aspx", 'mode=' + Mode + '&aID=' + ArtikelID + '&kID=' + KommentarID, REQUEST_POST, 8, -1);
}

function AJAXGetFamilienanzeigenBildContent(FID) {
  sendRequest("/anzeigen/FamilienanzeigenBild.aspx?mode=gross&fid=" + FID, '', REQUEST_POST, 9, -1);
}

// process data for client
function SetCatEintraege(data) 
{
  if (document.getElementById('artikeluebersicht') != null) {
    document.getElementById('artikeluebersicht').innerHTML = data;
    document.getElementById('artikeluebersicht').style.display = 'block';
  }
  else
    document.getElementById('content_spalte').innerHTML = data;
  if(document.getElementById('artikeldetails') != null)
    document.getElementById('artikeldetails').style.display = 'none';
}

var TouchPos, touchinterval;

function SetTouchCatEintraege(data) {
  if (document.getElementById('artikeluebersicht') != null) {    
    document.getElementById('content_spalte').style.height = document.getElementById('artikeluebersicht').offsetHeight + 50 + "px";    
    document.getElementById('content_spalte').style.position = "relative";
    var TouchDiv = document.getElementById('TouchFlowBox');
    TouchDiv.style.position = "absolute";
    TouchDiv.style.top = "0px";
    document.getElementById('TouchFlowBox').innerHTML = data;
    document.getElementById('artikeluebersicht').style.webkitTransition = "all 0.2s linear";
    document.getElementById('TouchFlowBox').style.webkitTransition = "all 0.2s linear";
    if (TouchMode == 1) {
      document.getElementById('TouchFlowBox').style.webkitTransform = "translate(-500px,0)";
      document.getElementById('artikeluebersicht').style.webkitTransform = "translate(-500px,0)";}
    if (TouchMode == -1) {
      document.getElementById('TouchFlowBox').style.webkitTransform = "translate(500px,0)";
      document.getElementById('artikeluebersicht').style.webkitTransform = "translate(500px,0)";}
    document.getElementById('TouchFlowBox').addEventListener('webkitTransitionEnd', onTransitionEnd, false);
  }
  else
    document.getElementById('content_spalte').innerHTML = data;
    
  if (document.getElementById('artikeldetails') != null)
    document.getElementById('artikeldetails').style.display = 'none';
}

function onTransitionEnd() {
  document.getElementById('artikeluebersicht').style.webkitTransition = "";
  document.getElementById('TouchFlowBox').style.webkitTransition = "";
  document.getElementById('artikeluebersicht').innerHTML = document.getElementById('TouchFlowBox').innerHTML;
  setTimeout("ShowTouchContent();", 200);
}

function ShowTouchContent() {
  document.getElementById('TouchFlowBox').innerHTML = '';
  document.getElementById('artikeluebersicht').style.webkitTransform = "";
  document.getElementById('TouchFlowBox').style.webkitTransform = "";
}

function SetSubMenu(data) {
  document.getElementById('platzhalterSubMenu').innerHTML = data;
}

function SetArtikelDetails(data) {
  BoxID = "content_spalte";  
  if (document.getElementById(BoxID) != null)
    var DivInhalt = document.getElementById(BoxID);
  else {    
    var DivInhalt = document.createElement("div");
    DivInhalt.setAttribute("id", BoxID);
    document.getElementById('content_spalte').appendChild(DivInhalt);
  }
  DivInhalt.innerHTML = data;
  /*document.getElementById('artikeldetails').style.display = 'block';
  document.getElementById('artikeluebersicht').style.display = 'none';*/
  window.scrollTo(0, 350);
}

function SetFotostrecken(data) 
{
  if (document.getElementById('fotostrecke') != null) {
    data = data.toString().substr(data.indexOf('<div id="fotostrecke_inhalt">'), (data.toString().lastIndexOf('</div>') - data.indexOf('<div id="fotostrecke_inhalt">')));
    document.getElementById('fotostrecke').innerHTML = data;
  }
}

function CloseArtikelDetails(artikelID, rubrikID) {  
  if (document.getElementById('artikeluebersicht') != null)
    document.getElementById('artikeluebersicht').style.display = 'block';  
  else
    GetArtikelVorschau(rubrikID);

  if (document.getElementById('artikeldetails') != null)
    document.getElementById('artikeldetails').style.display = 'none';

  //focus();  
}

function showInfoBox(data) 
{
  var InfoDiv
  if (document.getElementById('UserInfoBox') == null) {
    InfoDiv = document.createElement("div");
    InfoDiv.setAttribute("id", "UserInfoBox");
  }
  else
    InfoDiv = document.getElementById('UserInfoBox');
  InfoDiv.className = "usrpopupInfoBox";
  InfoDiv.style.position = "absolute";
  InfoDiv.style.zIndex = "500";
  InfoDiv.style.width = "250px";
  InfoDiv.style.backgroundColor = '#fff';
  InfoDiv.style.display = 'block';
  InfoDiv.style.padding = "10px";
  InfoDiv.innerHTML = "<div class=\"senden_x\" style=\"margin-bottom:25px;\"><a href=\"javascript:closeUserInfoBoxBox();\"><span>Fenster schliessen</span></a></div>" + data;
  document.body.appendChild(InfoDiv);
  centerAll('UserInfoBox');
  InfoDiv.style.top = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + 450 + "px";
}

function closeUserInfoBoxBox()
{
  document.getElementById('UserInfoBox').style.display='none';
  document.getElementById('UserInfoBox').style.zIndex="-500";
}

function centerAll(objID) {
  var pageX = (document.all) ? document.body.offsetWidth : window.innerWidth;
  //var pageY = (document.all)?document.body.offsetHeight:window.innerHeight;
  
  var objRef = document.getElementById(objID);
  var objW = objRef.offsetWidth;
  //var objH = objRef.offsetHeight;
  objRef.style.left = ((pageX / 2) - (objW / 2)) + "px";
  //objRef.style.top = ((pageY/2)-(objH/2))+"px";  
  objRef.style.top = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + 25 + "px";
  
  //objRef.focus();
  //window.scrollTo(((pageX/2)-(objW/2)),0)
}

function GetPageSize() {
  var xScroll, yScroll;

  if (window.innerHeight && window.scrollMaxY) {
    xScroll = window.innerWidth + window.scrollMaxX;
    yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = document.body.offsetWidth;
    yScroll = document.body.offsetHeight;
  }

  var windowWidth, windowHeight;

  if (self.innerHeight) {	// all except Explorer
    if (document.documentElement.clientWidth) {
      windowWidth = document.documentElement.clientWidth;
    } else {
      windowWidth = self.innerWidth;
    }
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }

  // for small pages with total height less then height of the viewport
  if (yScroll < windowHeight) {
    pageHeight = windowHeight;
  } else {
    pageHeight = yScroll;
  }

  // for small pages with total width less then width of the viewport
  if (xScroll < windowWidth) {
    pageWidth = xScroll;
  } else {
    pageWidth = windowWidth;
  }

  return [pageWidth, pageHeight];
}
