// ------------------------------------------------ AJAX maillist subscription ---------------------------------------------------
send_maillist_subscription = function () {
  intraxxion.submitform('newsletter.htm/action',getElement('digibrief'), maillist_subscription);
};
maillist_subscription = function (data) {
  resp = JSON.parse(data.responseText);
  maillistMessage(resp.message);
};
maillistMessage = function(msg) {         
  cmnew = DIV({'id':'digibrief_message','style':'padding-bottom:4px;display:block'}, SPAN(null, msg));
  swapDOM('digibrief_message', cmnew);
  callLater(7, hideMaillistMessage );
};
hideMaillistMessage = function() {
  getElement('digibrief_message').style.display = 'none';
};
// ------------------------------------------------ AJAX spotlight search --------------------------------------------------------
var old = '';

dolivesearch = function () {
  res = $('spotlightresults');
  qry = $('spotlightquery').value;
  if (qry != old) {
    if (qry == '' || qry == 'SNEL ZOEKEN . . .') {
      res.innerHTML = '';
      res.style.display = 'none';
    } else
      intraxxion.submitform('DesignerTemplates/spotlightresults.html', $('livesearch'), displayresults);
  }
  old = qry;
  setTimeout('dolivesearch()', 700) ;
};
initsearch =function () {
  dolivesearch();
};

displayresults = function (data) {
  $('spotlightresults').style.display = 'block';
  $('spotlightresults').innerHTML = data.responseText;
};


// ------------------------------------------------ IE Setup for dropdownmenu -----------------------------------------
function showList() {
  nav = $('pdnav').childNodes;
  for(x=0; x < nav.length; x++) {                   
    connect(nav[x], 'onmouseover', nav[x],
      function(evt) {
        this.className = 'over';
      }
    );
    connect(nav[x], 'onmouseout', nav[x],
      function(evt) {
        this.className = '';
      }
    );
  }
}

// ------------------------------------------------ IE Setup for hoverbuttons -----------------------------------------
function hoverButtons() {
  buts = getElementsByTagAndClassName('div','projectbutton',$('projectcontrols'));
  for(x=0; x < buts.length; x++) {                   
    connect(buts[x], 'onmouseover', buts[x],
      function(evt) {
        addElementClass(evt.target(),'over')
      }
    );
    connect(buts[x], 'onmouseout', buts[x],
      function(evt) {
        addElementClass(evt.target(),'over')
      }
    );
  }
}
// ------------------------------------------------ Preload project Images --------------------------------------------

var project_images = null; 
var imageindex = 0;
var lastimage = 0;

preloadProjectImages = function(url) {
  bindMethods(this);
  this.images = [];
  this.hires = [];
  this.url = url;       
  this.init();                               
  this.loadcounter = 0;
  this.hirescounter = 0
  this.data = null;
};

preloadProjectImages.prototype = {
  init: function() {
    this.load();
  },
  load: function(optionsurl) {    
    signal(currentDocument(),'beforeimagepreload');
    d = MochiKit.Async.loadJSONDoc(this.url+'/json_fetch_project_images');
    d.addCallbacks(this.loadReady, this.loadFailed);    
  },
  loadReady: function(data) {                
    //log('er zijn '+data.length+' afbeeldingen');
    this.loadcounter = 0;                             
    this.hirescounter = 0
    this.data = data;
    lastimage = data.length-1;
    imageindex = 0;

    if (this.data.length == 0) {
      swapDOM($('teller'), DIV({'class':'teller','id':'teller'},'Geen afbeeldingen gevonden'),DIV({'style':'clear:both'}));
      $('mainimage').style.background = 'none';
      this.images = [];
      callLater(2.0, hideElement, $('teller'));
    }
    
    this.images = map(this.fetch_image, this.data);
    this.hires = map(this.fetch_hires,this.data);
  },
  
  fetch_image: function(url) {
    my_img = new Image()
    if (document.all)
       my_img.src= url+'/thumbnail?ie_sucks='+Math.floor(1000 * (Math.random() % 1));
    else
      my_img.src = url+'/thumbnail';

    if (document.all) {
      connect(my_img, 'onreadystatechange', this,
        function(e) {
          if (e.src().readyState == "complete") {
            this.loadcounter = this.loadcounter + 1;
        
            swapDOM($('teller'),
              DIV({'class':'teller','id':'teller'},'. . . Bezig met laden lage resolutie afbeelding '+this.loadcounter+' van '+(parseInt(lastimage)+1)),
                DIV({'style':'clear:both'}));
        
            if (this.loadcounter == parseInt(lastimage)+1) {          
              signal(currentDocument(), 'afterimagepreload');
            }
          }
        }
      );
    } else {
      connect(my_img, 'onload', this,
          function(e) {
            this.loadcounter = this.loadcounter + 1;
      
            swapDOM($('teller'),
              DIV({'class':'teller','id':'teller'},'. . . Bezig met laden lage resolutie afbeelding '+this.loadcounter+' van '+(parseInt(lastimage)+1)),
                DIV({'style':'clear:both'}));
      
            if (this.loadcounter == parseInt(lastimage)+1) {          
              signal(currentDocument(), 'afterimagepreload');
            }
          }
        );
    }
    
    return my_img;
  },
  fetch_hires: function(url) {
    my_img = new Image()
    if (document.all)
       my_img.src= url+'/img?ie_sucks='+Math.floor(1000 * (Math.random() % 1));
    else
      my_img.src = url+'/img';

    if (document.all) {
      connect(my_img, 'onreadystatechange', this,
        function(e) {
          if (e.src().readyState == "complete") {
            this.hirescounter = this.hirescounter + 1;

            swapDOM($('teller'), 
              DIV({'class':'teller','id':'teller'},'. . . Bezig met laden hoge resolutie afbeelding '+this.hirescounter+' van '+(parseInt(lastimage)+1)),
                DIV({'style':'clear:both'}));          

            if (this.hirescounter == parseInt(lastimage)+1) {          
              signal(currentDocument(), 'afterimagepreload');
            }
          }
        }
      );
    } else {
      connect(my_img, 'onload', this,
        function(e) {
          this.hirescounter = this.hirescounter + 1;
        
          swapDOM($('teller'), 
            DIV({'class':'teller','id':'teller'},'. . . Bezig met laden hoge resolutie afbeelding '+this.hirescounter+' van '+(parseInt(lastimage)+1)),
              DIV({'style':'clear:both'}));          
        
          if (this.hirescounter == parseInt(lastimage)+1) {          
            signal(currentDocument(), 'afterimagepreload');
          }
        }
      );
    }

    return my_img;
  },
  loadFailed: function(err) {
    log(err);
  }
};
// ------------------------------------------------ Load projects in portfolio --------------------------------------------

var myProjectLoader = null;
projectLoader = function() {
  bindMethods(this);
  this.data = null;       
  this.events_set = false;
  this.aipl = 0;
};

projectLoader.prototype = {
  load: function(url) {
    if (!this.events_set) {
      this.setEvents();
    }
    this.url = url;
    if (this.url == 'http://www.litscherveld.nl/'){
      this.url =  'http://www.litscherveld.nl/Litscherveld-Heerlen.htm'
    }
    else if (this.url == 'http://www.vijverparc.nl/'){
      this.url =  'http://www.vijverparc.nl/Leijenbroek-Sittard.htm'
    }
    else if (this.url == 'http://www.eschberg-noord.nl/'){
      this.url =  'http://www.eschberg-noord.nl/Eschberg-Noord-Vaals.htm'
    }
    else if (this.url == 'http://www.overheekklimmen.nl/'){
      this.url =  'http://www.overheekklimmen.nl/KlimmenOverheek.htm'
    }
    d = MochiKit.Async.loadJSONDoc(this.url+'/json_fetch_project_data');
    d.addCallbacks(this.loadReady, this.loadFailed);    
  },
  loadReady: function(data) {
    this.data = data;           
    this.render();
  },
  loadFailed: function(err) {
    log(err);
  },
  render: function() {
    // Preload the images
    project_images = null;
    project_images  = new preloadProjectImages(this.url);
  },
  setEvents: function() {  
    this.events_set = true;
    if ($('mainimage')) {         
      $('mainimage').style.cursor = 'pointer';
      
      
      connect($('mainimage'), 'onclick',
        function(e) {
          if (e.target().id == 'elm_1' || e.target().id == 'elm_2') {
            swapDOM($('lbLoadMessage'), DIV({'id':'lbLoadMessage','style':'display:none'}, 'Klik op de afbeelding om deze te sluiten.'));                                    
            //makeVisible('lbLoadMessage');
            appear($('lbLoadMessage'),{'duration':1.0, 'from':0.0, 'to': 0.9});
            makeVisible('overlay');
            if (document.all) {
              eld = getElementDimensions(document.getElementsByTagName('html')[0]);
              eld.h = eld.h - 4;
              eld.w = eld.w - 22;
              setElementDimensions($('overlay'), eld);
            }
            makeVisible('lightbox');
          }
        }
      );
      connect($('mainimage'), 'onmouseover',
        function(e) {
          if (e.target().id == 'elm_1' || e.target().id == 'elm_2' ) {                                         
            swapDOM($('teller'), DIV({'class':'teller','id':'teller','style':'display:none'},'Klik op de afbeelding voor een vergroting!'),DIV({'style':'clear:both'}));
            showElement($('teller'));
//            appear($('teller'), {'duration':1.0, 'from':0.0, 'to': 0.9});
          }
        }
      );
      connect($('mainimage'), 'onmouseout',
        function(e) {
          if (e.target().id == 'elm_1' || e.target().id == 'elm_2' ) {                                         
            //hideElement($('teller'));
            callLater(0.5, fade, $('teller'), {'duration':1.0});
          }
        }
      );
      /*
      connect($('teller'), 'onmouseout',
        function(e) {                                      
          hideElement($('teller'));
        }
      );
      */
      /*
      connect(currentDocument(), 'beforeimagepreload', this, function(e) {
        // Before starting the imagepreload start the ajax-loader indicator
        // log('BIPL '+this.data);
      });
      */
            
      connect(currentDocument(), 'afterimagepreload', this,  
        function(e) {
          // After the imagepreload completes stop the ajax-loader indicator and show first image
          //log('AIPL');
          this.aipl = this.aipl + 1;
          
          if (this.aipl == 2) {
            hideElement($('teller'));
            disp_ix = imageindex+1;
            disp_cnt = lastimage+1;
            this.bufferComplete();
          }
        }
      );
      
    }   
  },
  bufferComplete: function() {
    this.active = 'elm_2';
    height = $('mainimage').offsetHeight;
    width = $('mainimage').offsetWidth;
    this.elm_1 = DIV({'id':'elm_1','style':'width:'+width+'px;height:'+height+'px;display:none;position:absolute;z-index:0'});
    this.elm_2 = DIV({'id':'elm_2','style':'width:'+width+'px;height:'+height+'px;display:block;position:absolute;z-index:0'});
    appendChildNodes($('mainimage'), this.elm_1, this.elm_2);
    $('mainimage').style.background='none';
    $('elm_2').style.background = 'url('+project_images.images[0].src+') no-repeat';
    $('lightboximage').src = project_images.hires[0].src;
    // prevent first flash
    setOpacity($('elm_2'), 1.0);
    setOpacity($('elm_1'), 0.0);
    this.active = 'elm_2'
    imageindex=1;
    callLater(5.0, this.animate); 
//    this.animate()
  },
  animate: function() {
    this.swap_image();
    if (imageindex == project_images.images.length-1) {
      imageindex = 0;
    } else {
      imageindex = imageindex + 1;
    }
    callLater(5.0, this.animate); 
  },
  swap_image: function() {
    img = project_images.images[imageindex];
    $('lightboximage').src = project_images.hires[imageindex].src;
    if (document.all)
      fade($(this.active),{'duration':0.5});
    else
      fade($(this.active),{'duration':2.0});
    if (this.active == 'elm_1') {
      this.active = 'elm_2';
    } else {
      this.active = 'elm_1';
    }
    $(this.active).style.background = 'url('+img.src+') no-repeat';
    if (document.all)
      appear($(this.active),{'duration':0.5});
    else
      appear($(this.active),{'duration':2.0});    
  }
}; 

connect(document, 'ready', function(e) {
  // Setup the lightbox imgs
  lbi = IMG({'id':'lightboximage','src':'empty'});
  $('lightbox').appendChild(lbi);    
  connect($('lightboximage'), 'onclick', function(e){                                         
    makeInvisible('overlay');
    makeInvisible('lightbox');
  });   
});


// ------------------------------------------------ Initialize the page -----------------------------------------------
connect(window,'onload',
  function(e) {
    body = document.getElementsByTagName('body')[0];
    
    if (document.all) {      
      // if there is a form set the width of radiobuttons and checkboxes
      // this is a fix for the missing of [type=...] css selectors
      rbandcb = filter(function(ob) { if (ob.type=='radio') {ob.style.width='auto'; ob.style.background='transparent'; return ob }}, document.getElementsByTagName('input'));
      
      // Now show the inputs
      ff = map(function(ob) {showElement(ob);return ob}, getElementsByTagAndClassName(null,'formfield'));
      
      // IE only supports :hover on li elements
      showList();
      hoverButtons();
    }

    if ($('projectcontrols')) {
      myProjectLoader = new projectLoader();        
      
      lhrs = location.href.split('/');
      if(lhrs[lhrs.length-1] != 'portfolio-pp-company.htm') {
        myProjectLoader.load(location.href);
      }
      
      setupProjectControls();
    }
    
    if ($('scrollcontainer')) {
      try {
        // Attach mousewheel eventlisteners to firstOuter
        scrollspeed = 15;
        if (document.all) {
          connect($('firstOuter'), 'onmousewheel', this,
            function(e) {
              if (e.event().wheelDelta>=0) {//wheel-up
                $('firstOuter').scrollTop -= scrollspeed;
              } else {
                $('firstOuter').scrollTop += scrollspeed;
              }
            }
          );
        } else {
          connect($('firstOuter'), 'onDOMMouseScroll', this, 
            function(e) {
               if (e.event().detail < 0)  { //wheel-up
                  $('firstOuter').scrollTop -= scrollspeed; 
                } else {
                  $('firstOuter').scrollTop += scrollspeed;
                }
            }
          );
        }      
        connect($('contentup'),'onmouseover',
          function(e) {
            e.target().src = 'DesignerImages/scroll-up_f2.gif';
            fScroller_up(e,'contentscroller');
          }
        );
        connect($('contentup'),'onmouseout',
          function(e) {
            e.target().src = 'DesignerImages/scroll-up.gif';
            fScroller_stop('contentscroller');
          }
        );
        connect($('contentdown'),'onmouseover',
          function(e) {
            e.target().src = 'DesignerImages/scroll-dn_f2.gif';
            fScroller_dn(e,'contentscroller');
          }
        );
        connect($('contentdown'),'onmouseout',
          function(e) {
            e.target().src = 'DesignerImages/scroll-dn.gif';
            fScroller_stop('contentscroller');
          }
        );
      } catch(e) {}
    }
  
    if ($('scrollcontainerMenu')) {
      // Attach mousewheel eventlisteners to firstOuter
      scrollspeed = 15;
      if (document.all) {
        connect($('firstOuterMenu'), 'onmousewheel', this,
          function(e) {
            if (e.event().wheelDelta>=0) {//wheel-up
              $('firstOuterMenu').scrollTop -= scrollspeed;
            } else {
              $('firstOuterMenu').scrollTop += scrollspeed;
            }
          }
        );
      } else {
        connect($('firstOuterMenu'), 'onDOMMouseScroll', this, 
          function(e) {
             if (e.event().detail < 0)  { //wheel-up
                $('firstOuterMenu').scrollTop -= scrollspeed; 
              } else {
                $('firstOuterMenu').scrollTop += scrollspeed;
              }
          }
        );
      }      
      connect($('contentmenuup'),'onmouseover',
        function(e) {
          e.target().src = 'DesignerImages/scroll-up_f2-m.gif';
          fScroller_up(e,'contentscrollerMenu');
        }
      );
      connect($('contentmenuup'),'onmouseout',
        function(e) {
          e.target().src = 'DesignerImages/scroll-up-m.gif';
          fScroller_stop('contentscrollerMenu');
        }
      );
      connect($('contentmenudown'),'onmouseover',
        function(e) {
          e.target().src = 'DesignerImages/scroll-dn_f2-m.gif';
          fScroller_dn(e,'contentscrollerMenu');
        }
      );
      connect($('contentmenudown'),'onmouseout',
        function(e) {
          e.target().src = 'DesignerImages/scroll-dn-m.gif';
          fScroller_stop('contentscrollerMenu');
        }
      );
    }
  }
); 

setupProjectControls = function() {
  connect($('slideshow'), 'onclick', 
    function(e) {
      if ($('meerinfoform')) {
        hideElement('meerinfoform');
        hideElement('objectcontent');
      }
      hideElement('scrollcontainer');
      $('moreinfo').className = 'projectbutton';
      $('contactform').className = 'projectbutton';
      $('slideshow').className = 'projectbutton selected';
    }
  );

  connect($('moreinfo'), 'onclick', 
    function(e) {
      if ($('meerinfoform')) {
        hideElement('meerinfoform');
      }
      showElement('scrollcontainer');
      showElement('objectcontent')
      $('slideshow').className = 'projectbutton';
      $('contactform').className = 'projectbutton';
      $('moreinfo').className = 'projectbutton selected';
    }
  );
  
  if ($('meerinfoform')) {
    patch_form(location.href);
    
    connect($('contactform'), 'onclick', 
      function(e) {
        showElement('scrollcontainer');
        hideElement('objectcontent')
        showElement('meerinfoform');
        $('slideshow').className = 'projectbutton';
        $('moreinfo').className = 'projectbutton';
        $('contactform').className = 'projectbutton selected';
      }
    );
  } else {
    hideElement($('contactform'));
  }

  addElementClass($('slideshow'), 'selected');
  
  // Make the selected menuitem visible
  sel = getElementsByTagAndClassName('a','selected', $('menu'))
  map(scrollToVisible, sel);
}                                               

scrollToVisible = function(ob) {
  pos = getElementPosition(ob);
  if (pos.y > 430) {
    $('firstOuterMenu').scrollTop = 230;
  }
}
project = function(id) {
  $('mainimage').style.background = 'url(DesignerImages/ajax-loader.gif) no-repeat center';
  hideElement($('teller'));
  showElement($('projectcontrols'));
  
  myProjectLoader = new projectLoader();        
  
  lhrs = id.split('/');
  if(lhrs[lhrs.length-1] != 'portfolio-pp-company.htm') {
    myProjectLoader.load(id);
  }

}


// Projectformulier

function patch_form(url) {
  // Patch the form so it uses "DesignerScripts/projectform_action" thru AJAX
  frms = getElementsByTagAndClassName('form',null,$('meerinfoform'));
  if (frms.length == 0) {
    return;
  }
  my_form = frms[0];
  my_form.id = 'patched_form'
  my_form.action="DesignerScripts/projectform_action";
  fm = DIV({'id':'foutmelding','style':'display:none'},null);
  $('hiddenform').insertBefore(fm, my_form);
  connect(my_form, 'onsubmit', 
    function(e) {
      return false;
    }
  );

  submitbtnlayer  = getElementsByTagAndClassName('div','formsubmit',$('meerinfoform'))[0]
  submitbtn = null;
  for (x=0;x < submitbtnlayer.childNodes.length;x++) {
    if (submitbtnlayer.childNodes[x].nodeType == "1") {
      submitbtn = submitbtnlayer.childNodes[x];
    }
  }
  newbtn = IMG({'border':'0','alt':'','src':'DesignerImages/verstuur_f1.gif'});
  swapDOM(submitbtn,newbtn);
  connect(newbtn, 'onclick', 
    function(e) {
      e.target().src='DesignerImages/verstuur_f1.gif';
      projectform_submit()
    }
  );
  connect(newbtn, 'onmouseout', 
    function(e) {
      e.target().src='DesignerImages/verstuur_f1.gif';
    }
  );
  connect(newbtn, 'onmouseover', 
    function(e) {
      e.target().src='DesignerImages/verstuur_f2.gif';
    }
  );
  // Add some fields
  if (! $('extra_form_fields')) {
    extra_form_fields = SPAN({'id':'extra_form_fields'}, 
        INPUT({'type':'hidden','value':url,'name':'formurl','id':'formurl'})
        );
    appendChildNodes(my_form, extra_form_fields);
  }
}

function projectform_submit() {
  frm =  $('patched_form');
  req = getXMLHttpRequest();       
  req.open('POST', frm.action, true);
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
  postBody = queryString(frm);
  d = sendXMLHttpRequest(req, postBody); 
  $('firstOuter').scrollTop = 0;   
  melding = DIV({'id':'foutmelding','class':'error','style':'display:block;margin-top:10px'}, 'Bezig met het verzenden van uw formulier.');
  swapDOM($('foutmelding'), melding);
  d.addCallbacks(projectFormReady,projectFormFailed);
}
function contactform_submit() {
  frm =  $('reactionform');
  req = getXMLHttpRequest();       
  req.open('POST', frm.action, true);
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
  postBody = queryString(frm);
  d = sendXMLHttpRequest(req, postBody); 
  $('firstOuter').scrollTop = 0;   
  melding = DIV({'id':'foutmelding','class':'error','style':'display:block;margin-top:10px'}, 'Bezig met het verzenden van uw formulier.');
  swapDOM($('foutmelding'), melding);
  d.addCallbacks(projectFormReady,projectFormFailed);
}

function show_info() {
  showElement('scrollcontainer');
  showElement('objectcontent')
  $('slideshow').className = 'projectbutton';
  $('contactform').className = 'projectbutton';
  $('moreinfo').className = 'projectbutton selected';  
}

function projectFormReady(data) {
  mydata = evalJSONRequest(data);
  if (mydata.status == 'OK') {
    melding = DIV({'id':'foutmelding','class':'error','style':'display:block;margin-top:10px'}, 'Formulier is succesvol verzonden naar Grouwels Daelmans.');
    swapDOM($('foutmelding'), melding);
    callLater(8.0, hideElement, $('foutmelding'));
    callLater(10.0, show_info);
  } else {
    melding = DIV({'id':'foutmelding','class':'error','style':'display:block;margin-top:10px'}, 'U heeft het formulier onvolledig of incorrect ingevuld, invoervelden met een * zijn verplicht. Na correctie kan het formulier opnieuw verzonden worden.');
    swapDOM($('foutmelding'), melding); 
  }
}

function projectFormFailed(err) {
  log(err);
}