// JavaScript Document
// GrooveCMS
// Functions for rendering the right content in the right div
var times = "tijd:";
var xmlHttp;
var dispItem;
var defElement = "content";    //Content is de standaard div
var defTitle   = "bodyheader"  //Standaard div voor title.
var uriName = unescape(location.href);
var hostPath;
var defaultContent;
var hashVars = "";
var internHeader = 0;
// Zoek eventuele hash-vars
var hashVars = splitHash();
var hostName = uriName.replace(hashVars,"");
var hostName = hostName.replace("#","").replace("index.html","");
// Als er een afwijkend pad is gebruik die dan.
if (hostPath) {
    hostName = unescape(hostPath); 
}

if(hostName.lastIndexOf("/") == hostName.length) {hostName = hostName.substring(0,hostName.length -1);}
if(!scripts) {
   var scripts = "scripts";	
}
var xmlFile = hostName + "/" + scripts + "/content.php";
var xmlMail = hostName + "/" + scripts + "/contact.php";
var aItems    = new Array; // Hier komen de contentitems in
var aElements = new Array; // Hier komen de display elements in
var aTitles   = new Array; // Hier komen de titles in.
var aAllDivs  = new Array; // Hier houden we alle ooit gevulde divs in bij.

function splitHash() {
  // Splits de Hash variablen
  if (location.hash.length >= 2) {
     var data = unescape(location.hash.substring(1));
     return data;  
  }
}

 
function createXMLHttpRequest() {
      // Create XMLHttp request
      if (window.ActiveXObject) {
          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      else if (window.XMLHttpRequest) {
          xmlHttp = new XMLHttpRequest();
      }
  }

function sendMail (){
    // Versturen van een mail n.a.v. de in de mailform ingevulde velden
    var aElements = document.forms[1].elements;
    var cErrors   = ""; 
    var aLabels   = document.getElementById("labels").value.split(",");
 
    for (var i=0; i < aElements.length; i++) {
      if(aElements[i].className.indexOf("mandatory") > -1) {
         var element = aElements[i];
         switch(element.tagName) {
            case 'INPUT':
                if(element.value == "") {
                   cErrors += aLabels[i - 2] + "\n";  
                }
            break;
            case 'SELECT':
                if(element.value.length == 0) {
                   cErrors += aLabels[i - 2] + "\n";  
                } 
            break;                 
      }
    }
    }
    if(cErrors != "") {
      alert("De volgende velden zijn niet goed ingevuld:\n" + cErrors);
       return false;
    } 
   
    var fieldtype = ""; 
    labels = document.getElementById('labels').value;
    labels = labels.substring(1);
    labels = labels.substring(0,labels.length -1);
    aLabels = labels.split("','");
    numFields = document.getElementById('numfields').value;
    var suffix = 'id='+document.getElementById('id').value+"&";    
    for (a=1; a<=numFields; a++){
        // Vul de suffix variabele met de invoer van de velden        
        thisField = document.getElementById("field"+a);
        if (thisField) {
        fieldtype = thisField.type;        
        switch(fieldtype) {
        case "select":
           value = thisField.selectedIndex;           
           break;
        case "checkbox": 
           value = thisField.checked;
           break;
        default: 
           value = document.getElementById("field"+a).value;
        }        
			suffix = suffix + aLabels[a - 1] + "=" + value + "&";
		}
    }
    createXMLHttpRequest();
    //Voer het php script uit. Handel response af met handleStateChangeMail 
    xmlHttp.onreadystatechange = handleStateChangeMail;
    xmlHttp.open("GET", xmlMail+"?"+suffix, true);
    xmlHttp.send(null);
}

function fillContent(choice, element, title) {
    // Functie voor het vullen van de content in de website n.a.v. door
    // webserver aangeleverde contentitem(s).
        
    dispItem = choice;       
    if(element) {dispElement = element;} else {dispElement = defElement;}
    if(title) {dispTitle = title} else {dispTitle = defTitle;}
    
    /* Roep de multiFillContent aan.*/
    multiFillContent(choice+","+dispElement+","+dispTitle);
    }

function multiFillContent(elements) {
    // Functie voor in een call verversen van meerdere 
    // content-items. Deze functie pakt een parameter op en 
    // pakt deze uit, controleert of de inhoud goed te verwerken 
    // is en start dan een aantal maal fillcontent op.
    // elements moet een ,-gescheiden string zijn met daarin 
    // de verschillende individuele aanroepen, die ;-gescheiden 
    // zijn.
         
    var curChar = "";
    var curVeld = "";
    var curElement = new Array;
    
    // Array met items leegmaken
    aItems.splice(0,aItems.length);
    aElements.splice(0,aElements.length);
    aTitles.splice(0,aTitles.length);
    
    // input parameter opknappen.
    elements = elements+';';
    elements = elements.replace(";;",";");

    var j = 1;
    // Loop de string door en vul de drie bovenstaande arrays
    for (var i = 0; i < elements.length; i++){
        curChar = elements.substring(i,i+1);
        switch(curChar)
        { 
          case ";":
            // Einde element
            aTitles.push(curVeld.replace(")",""));
            curElement.push(curVeld);
            curVeld = "";
            j = 1;
            //aElements.push(curElement);
            curElement = Array();
            break
          case ",":
            // Einde veld
            switch(j) { 
            case 1:
              aItems.push(curVeld);
              break;
            case 2: 
              aElements.push(curVeld);
              lFound = "no";
              for (x in aAllDivs) {
                if (aAllDivs[x] == curVeld) {
                   lFound = 'yes';
                }
              }
              if (lFound=="no") { 
                  aAllDivs.push(curVeld);
              }
              break;
             }
            curElement.push(curVeld);
            curVeld = "";
            j++;
          break
          default:
            curVeld = curVeld+curChar;           
        }     
        var list = aItems.join();
    }
                   
  /* Doe de call!*/
    var suffix = "&ms=" + new Date().getTime();   
    times = times + suffix;
    var cItems = aItems.join(); 
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open("GET", xmlFile+"?id="+cItems+suffix, true);
    xmlHttp.send(null);
}

function handleStateChange() {
    // Afhandeling na xmlHTTP-verzoek van een content item 
    if(xmlHttp.readyState == 4) {
           // Response is binnen
           var items;
           var xml = xmlHttp.responseXML;
           items = xml.getElementsByTagName("contentItem");
           var title, content, titleimage, item, itemnum, className, sideImage, value;
           var aContent = new Array;
           var aValue   = new Array;
           // Handel de nodes van het xml response af 
           for(var i=0; i<items.length; i++) {
             item = items[i];
             itemnum = item.getAttribute("id");
             className = "";
			 titleimage = "";
			 sideImage = "";
             for (var j=0;j<item.childNodes.length;j++) {
			 
			   	value = "";
			   	if (item.childNodes[j].firstChild) {
			   		if (item.childNodes[j].firstChild.nodeValue && dispItem != 900000) {
			   			for (var k = 0; k < item.childNodes[j].childNodes.length; k++) {
			   				value += item.childNodes[j].childNodes[k].nodeValue;
			   			}
			   		}
			   		else {
			   			value = "<p></p>";
			   		}
			   		
			   		if (item.childNodes[j].nodeName == "title") {
			   			title = value;
			   		}
			   		else 
			   			if (item.childNodes[j].nodeName == "contents") {
			   				content = value;
			   			}
			   			else 
			   				if (item.childNodes[j].nodeName == "titleImage") {
			   					titleimage = value;
			   				}
			   				else 
			   					if (item.childNodes[j].nodeName == "className") {
			   						className = value;
			   					}
			   					else 
			   						if (item.childNodes[j].nodeName == "sideImage") {
			   							sideImage = value;
			   						}
			   	}
			   	else {
			   		continue;
			   	}
			   }
          // Als er een title is gedefinieerd deze afhandelen.
          var dispTitle   = aTitles[i];
          var dispElement = aElements[i]; 
          if(dispTitle != "notitle"){
            if(titleimage && document.getElementById(dispTitle)){
              // Image gestuurd. Dus image in title header zetten
              if(className){
                document.getElementById(dispTitle).innerHTML = "<div class=" + className + ">" + "<img src=" + titleimage + "></div>";
              }
              else {
                document.getElementById(dispTitle).innerHTML = "<img src=" + titleimage + ">";              
              }
            }
            else {
              if(className){          
                // Geen image dus dan text in title zetten.
                if(document.getElementById(dispTitle)) {
                   document.getElementById(dispTitle).innerHTML = "<div class=" + className + ">" + title + "</div>";
                }
              }
              else {
                // Geen image dus dan text in title zetten.
                if(document.getElementById(dispTitle)) {
                   document.getElementById(dispTitle).innerHTML = title;              
                }
              }
                
            }
          }
          if(className){
            // ClassName meegeven
            document.getElementById(dispElement).innerHTML = "<div class=" + className + ">" + content + "</div>";
          }
          else {
            if( document.getElementById(dispElement)) {
            document.getElementById(dispElement).innerHTML = content;    }
          }

          if(document.getElementById("sideimage")){
            if(sideImage){
              // Er is een sideimage aangegeven deze vullen.
              document.getElementById("sideimage").innerHTML = "<img src=" + sideImage + ">";    
            }
            else {
              //Geen side image dus div leegmaken 
              document.getElementById("sideimage").innerHTML = "";    
            }
          }
      }
    
    // Loop alle A elementen af om er voor te zorgen dat 
    // ze een onmousedown event krijgen waarin een entry
    // de historylist wordt gemaakt.
    aHrefs = document.getElementsByTagName("A");       
    
    for (var i = 0; i < aHrefs.length; i++) {
       if(aHrefs[i].href.indexOf("Content") != -1) {
           aHrefs[i].onmousedown = function() {
               // Eerst de aanroep in de history zetten
                dhtmlHistory.add(this.href.substring(11),
                                 this.href.substring(11));
           }
       }
    }
   // Als er een headerbannerimage is gedefinieerd dan deze afhandelen.
   var xml = xmlHttp.responseXML;
   headerbanners = xml.getElementsByTagName("headerBannerImage");
   if(headerbanners[0] && headerbanners[0].childNodes[0].textContent != "") {
   	  headerbannerImg = document.getElementById("headerbanner_image");
      if(headerbannerImg) {
	  	headerbannerImg.src = headerbanners[0].childNodes[0].textContent;
	  }
   }
  }
  javascript:scroll(0,0);  
}


function handleStateChangeMail() {
    // Afhandelen van xmlHttp response van contact.php
    if(xmlHttp.readyState == 4) {
           var items;
           var txt = xmlHttp.responseText;
           if(txt.substring(0,5) == "Error") {
             // Response geeft een error. Error melding geven, formulier 
             // niet veranderen.
             // alert(txt.substring(6));
           }
           else {
             // Response geeft geen error. Succes melding geven in content div (parent van het formulier)
             // Formulier leegmaken.
             
            document.getElementById('contactform').parentNode.innerHTML = txt;
           }
    }
}

function displayPicture(image) {
    // Geef de foto van de geselecteerde thumbnail weer. 
    var pd;
    var newimage = image;
    
    var img = document.getElementById("picframe");
    img.src = newimage;
    
    var cap = document.getElementById("caption");
    cap.innerHTML = desc;
    
    /* for (a=1; a<=total; a++){
        ca = a.toString();
        pd = '';
        for(b=1; b<=(4-ca.length); b++) {
            pd+= '0';            
        }
        cCurrentSeq = "seqno"+pd+ca;
        if(iDispPicture === a){ 
         document.getElementById(cCurrentSeq).style.display = '';
         }
         else{ 
         document.getElementById(cCurrentSeq).style.display = 'none';
         }
    }
    */
}

function popupme() {
    var img = document.getElementById("picframe");
    image = img.src;
    
    window.open(image, 'popup'); 
    return false;
}



function displayList(list,total) {
    // Geef de lijst weer. 
    var pd;
    cDispList = list;
    iDispList = Number(cDispList.substring(4));    
    for (a=1; a<=total; a++){
        ca = a.toString();
        pd = '';
        for(b=1; b<=(1-ca.length); b++) {
            pd+= '0';            
        }
        cCurrentList = "list"+pd+ca;
        if(iDispList === a){ 
         document.getElementById(cCurrentList).style.display = '';
         }
         else{ 
         document.getElementById(cCurrentList).style.display = 'none';
         }
    }
}

function clearInput(cfield,text,type) {
  // Legen en vullen van de invul velden  
  field = document.getElementById(cfield);
  if (type == 'focus' && field.value == text)
    { 
      field.value = '';
    }
  if (type == 'blur' && field.value == '')
    {
      field.value = text;
    }
  }

function clearAll() {
   // Legen van alle Divs die ooit in deze sessie
   // gevuld zijn vanuit een fillContent of een 
   // multiFillContent
   if(aAllDivs.length > 0) {
       for (x in aAllDivs) {
          if(document.getElementById(aAllDivs[x])) {
             document.getElementById(aAllDivs[x]).innerHTML = "";
             }
       }
   }
}

function hideDiv (cField,cSwitch){
   // Display of hide een div
   var field = document.getElementById(cField);
   var cOnOff;
   
   if(cSwitch == 'on') {
      cOnOff = '';
   }
   else {
      cOnOff = 'none';
   }
   if(field) { 
   field.style.display = cOnOff;}
}

function intern(div) {
   //Simuleer een interne link
   if(!internHeader) {
       internHeader = 0;
   }
   adressDiv = document.getElementById(div);
   var top;
   top = adressDiv.offsetTop + internHeader;   
   window.scrollTo(0,top);
}

// Als er een hash of de variable defaultItem is gezet, dan deze gebruiken voor het vullen van 
// document. De hash gaat voor de defaultItem variable zodat niet altijd het de default voorgaat.
function fillDefault(){
  if (hashVars || defaultContent) {
    if(hashVars) {
      aHashVars = hashVars.split(");");}
    else {      
      aHashVars = defaultContent.split(");");
      dhtmlHistory.add(defaultContent,
                       defaultContent);}
    
    //Loop door de elementen van de hash door en 
    //voor de bijbehorende functies uit.
    for(var i = 0; i < aHashVars.length; i++) {
        cHashVar = aHashVars[i];
        // Voeg zonodig een ) toe
        if(cHashVar.substring(cHashVar.length - 1) != ")") { 
            cHashVar = cHashVar+")";
            }
        
        // Splits het element van de hash op in de functie naam 
        // en de bijbehorende elementen
        if (cHashVar) {
            var callType = cHashVar.substring(0,cHashVar.indexOf("("));
            var param = cHashVar.substring(cHashVar.indexOf("(")+1,cHashVar.indexOf(")") - 1);
        }
    
        // Voer de functie uit.
        // Huidige functies:
        // - fillContent
        // - MultiFillContent
        // - hideDiv 
        // - ClearAll
        switch (callType) {
          case "fillContent":
             // Pak de parameters uit
             params = param.split(",");
             fillContent(params[0].replace(/'/g,""),params[1].replace(/'/g,""),params[2].replace(/'/g,""));
             break;
          case "multiFillContent":
             multiFillContent(param.replace(/'/g,""));
             multiFillContent(param.replace(/'/g,""));
             break;
          case "hideDiv":
             params = param.split(",");
             hideDiv(params[0].replace(/'/g,""),params[1].replace(/'/g,""));
             break;
          case "clearAll":
             clearAll();  
             break;
          case "resizeLeft":
             params = param.split(",");
             resizeLeft(params[0].replace(/'/g,""));
             break;
          case "dispDivs":
             params = param.split(",");
             dispDivs(params[0].replace(/'/g,""));
             break;
          default:
             break;
         }
       }
   }
}
// RSH is een systeem om de backbutton van de 
// browsers goed te laten werken bij Ajax driven systemen.

/** RSH must be initialized after the
    page is finished loading. */
window.onload = initialize;

function initialize() {
  // initialize RSH
  dhtmlHistory.initialize();
  
  // add ourselves as a listener for history
  // change events
  dhtmlHistory.addListener(handleHistoryChange);
  
  // determine our current location so we can
  // initialize ourselves at startup
  var initialLocation = 
                dhtmlHistory.getCurrentLocation();
  
  // if no location specified, use the default
  if (initialLocation == null)
    initialLocation = "";
  
  // now initialize our starting UI
  //updateUI(initialLocation);
}

/** A function that is called whenever the user
    presses the back or forward buttons. This
    function will be passed the newLocation,
    as well as any history data we associated
    with the location. */
function handleHistoryChange(newLocations) {
  // use the history data to update our UI
    aNewLocations = newLocations.split(");");

    // De aNewlocations bestaat uit verschillende elementen 
    // met calls.
    for (var i = 0; i < aNewLocations.length;i++) {
      newLocation  = aNewLocations[i]; 
      var callType = newLocation.substring(0,newLocation.indexOf("("));
      var param    = newLocation.substring(newLocation.indexOf("(")+1);

      // Verwerk de functies met de bijbehorende parameters.
      switch (callType) {
        case "fillContent":
          // Pak de parameters uit
          params = param.split(",");
          fillContent(params[0].replace(/'/g,""),params[1].replace(/'/g,""),params[2].replace(/'/g,""));
          break;
        case "multiFillContent":
          param = param.substring(0,param.length -1);
          multiFillContent(param.replace(/'/g,""));
          break;
        case "hideDiv":
          params = param.split(",");
          hideDiv(params[0].replace(/'/g,""),params[1].replace(/'/g,""));
          break;
        case "clearAll":
          clearAll();  
          break;
        case "resizeLeft":
          params = param.split(",");
          resizeLeft(params[0].replace(/'/g,""));
          break;
        case "dispDivs":
          params = param.split(",");
          dispDivs(params[0].replace(/'/g,""));
          break;
       default:
          break;
      }
   }
} 
    
function preloadImages (images) {
  alert(images);
  var imgNames = images.split(",");
  var imgObjects = [];
  
  for (var i = 1; i < imgNames.length; i++)
  {
    alert(imgNames[i]);
    imgObjects[i] = new Image();
    imgObjects[i].src = imgNames[i];
  }
}
            
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(fillDefault);
