﻿var toddUserAgent = navigator.userAgent.toLowerCase();
var toddUserAgentIsOpera = (toddUserAgent.indexOf('opera') != -1);
var toddUserAgentIsIE = (typeof document.attachEvent != 'undefined') && (!toddUserAgentIsOpera);

// KHTML & Webkit engine based browsers
var toddUserAgentIsWebKit = (toddUserAgent.indexOf('applewebkit') != -1); // Safari or compatible, using WebKit engine

var uaIsGecko = (toddUserAgent.indexOf('gecko') != -1); // Mozilla, Firefox or compatible, using Gecko engine


if (uaIsGecko)
{
  GeckoVersion = toddGetGeckoVersion();

  // if the gecko version was not found, it's very likely the browser lied
  // or the user agent string contains KHTML/Webkit's '(KHTML, like Gecko)'
  if (GeckoVersion == 0)
    uaIsGecko = false;
}

if (uaIsGecko && GeckoVersion < 1.9)
  loadStyle(siteroot+'/design/css/vw_FF2.css');


if(toddUserAgentIsIE)
{
  // make IE6 not keep on requesting if background images are changed every pageview
  try { document.execCommand("BackgroundImageCache", false, true); }
  catch(e) { }
}





function init()
{
  //check_driving_school_login(); // No need to show or check this... driving school holders can only logout from their profile pages
  check_student_login();

  fixup_mainmenu_layout();

}

function toggleLoginForm()
{
  var loginpanel = document.getElementById('loginpanel');

  if (hasClass(loginpanel,'open'))
    removeClass(loginpanel,'open')
  else
    addClass(loginpanel,'open');
}

/* to be removed */
function simulatesubmitbutton(evt, fname, fvalue)
{
  var fnode = this.toddGetEventTarget(evt);

  while(fnode && fnode.tagName.toLowerCase() != 'form')
    fnode = fnode.parentNode;

  if (!fnode || fnode.type != 1 && fnode.tagName.toLowerCase() != 'form')
    return;

  var elem = document.createElement('input');
  elem.type = 'hidden';
  elem.name = fname;
  elem.value = fvalue;
  fnode.appendChild(elem);

  fnode.submit();
}

function submitForm(formId)
{
  var form = document.getElementById(formId);
  if (form)
    form.submit();
}

function fixup_mainmenu_layout()
{
  // fix rounding error by giving the last menuitem all leftover space
  // (in IE/FF3 it might won't be nessecary, but OP and SF need it)
  var mmb = document.getElementById('mmbuttons');
  var mitemlist = document.getElementById('mmbuttons').getElementsByTagName('a');
  lastitem = mitemlist[mitemlist.length-1];

  if (toddUserAgentIsWebKit) // || (uaIsGecko && GeckoVersion < 1.9))
  {
    var elemm = document.getElementById('measure');
    var usewidth = 968 - elemm.clientWidth;

    var bcont = document.getElementById('buttoncontainer');
    bcont.style.cssText = 'width: '+usewidth+'px;';
  }

    if (uaIsGecko && GeckoVersion < 1.9)
    {
      return;
//      bcont.style.cssText = 'display: -moz-inline-box; width: '+usewidth+'px;';
//      lastitem.style.cssText = 'display: -moz-inline-box; top: -30px; -moz-box-orientation: vertical; -moz-box-align: center; width: '+(968-lastitem.offsetLeft)+'px; padding: 0; text-align: center;';
//    lastitem.style.firstChild();
    }
    else
      lastitem.style.cssText = 'width: '+(968-lastitem.offsetLeft)+'px; padding: 0; text-align: center;';
}

function check_student_login()
{
  var cookie = toddReadCookie('vwstudentloginname');

  if(cookie&&cookie.substr(0,1)=='"')
    cookie=cookie.substr(1,cookie.length-2);

  if(cookie)
  {
    document.getElementById('userinfo').innerHTML = 'U bent ingelogd als <a href="'+ studentsProfile + '">' + cookie + '</a>'; // innerText / textContent
    document.getElementById('useranon').style.display = 'none';
    document.getElementById('userloggedin').style.display = '';
  }
  else
  {
    document.getElementById('useranon').style.display = '';

    var panel = document.getElementById('userloggedin');
    if (!panel)
      return;

    panel.style.display = 'none';
  }
}

/* No need yet

function check_driving_school_login()
{
  var cookie = toddReadCookie('vwdrivingschoolloginname');

  if(cookie&&cookie.substr(0,1)=='"')
    cookie=cookie.substr(1,cookie.length-2);

  if(cookie)
  {
    document.getElementById('userinfo').innerHTML = 'U bent ingelogd als '+cookie; // innerText / textContent
    document.getElementById('logintogglebutton').style.display = 'none';
    document.getElementById('logoutbutton').style.display = '';

    //document.getElementById('logindata').firstChild.nodeValue = cookie;
    //document.getElementById('logininfo').style.display='block';
  }
}*/









function toddGetGeckoVersion()
{
  // For references see:
  //   - https://developer.mozilla.org/en/User_Agent_Strings_Reference
  //   - http://www.useragentstring.com/pages/useragentstring.php
  var vStart = toddUserAgent.indexOf(' rv:');
  var vEnd   = vStart>-1 ? toddUserAgent.indexOf(')',vStart+1) : -1;

  // set of numbers separated by periods, possibly followed by a pre-release indicator
  // (parseFloat will pick up till the first non number/dot or second dot)
  if (vStart==-1 || vEnd-vStart<3)
    return 0;
  else
    return parseFloat(toddUserAgent.substring(vStart+4,vEnd));
};

function hasClass(ele,cls) {
        return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addClass(ele,cls) {
        if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

function removeClass(ele,cls) {
//      if (hasClass(ele,cls)) {
                var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
                ele.className=ele.className.replace(reg,' ');
//      }
}

function loadStyle(src) {
        var oStyle=document.createElement('link');
        oStyle.rel='stylesheet';oStyle.href=src;
        document.getElementsByTagName('head')[0].appendChild(oStyle);
}

function toddGetEventTarget(e)
{
  if (!e)
    return null;
  if (e.target)
    return e.target;
  else if (e.srcElement)
    return e.srcElement;
}

// Cookie code based on http://www.quirksmode.org/js/cookies.html
function toddWriteCookie(name, value, days)
{
  var expires = "";
  if (days)
  {
    var date = new Date();
    date.setTime(date.getTime() + (days*24*60*60*1000));
    expires = "; expires=" + date.toGMTString();
  }
  document.cookie = name + "=" + value + expires + "; path=/";
}

function toddReadCookie(name)
{
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i < ca.length; i++)
  {
    var c = ca[i];
    while (c.charAt(0)==' ')
      c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) == 0)
      return c.substring(nameEQ.length, c.length);
  }
  return null;
}

function toddDeleteCookie(name)
{
  toddWriteCookie(name, "", -1);
}


var wfwindowcount=0;
function tolliumWFHook_OpenWindow(data)
{
  wfwindowcount++;

  // add room for window edges and padding
  var windowedgewidth  = 11+11 + 15*2;
  var windowedgeheight = 50+11 + 15*2;

  var dcontainer = document.createElement('div');
  dcontainer.className = 'tollium-custompopupdialog';
  dcontainer.id = 'wfpopup_'+wfwindowcount;

  var skintable = document.createElement('table');
  skintable.className = 'skintable';

  //pTable.style.cssText = "position: absolute;";
  var ptbody = document.createElement('tbody');

  var ptrow  = document.createElement('tr');
  ptrow.style.cssText = 'height: 50px;';
  var ptl    = document.createElement('td');
  ptl.className = 'dialog_tl';
  var ptm    = document.createElement('td');
  ptm.className = 'dialog_tm';
  ptm.id = 'wfpopup_'+wfwindowcount+'_title';
  //ptm.appendChild(document.createTextNode('&nbsp;'));

  var ptr2   = document.createElement('td');
  ptr2.className = 'dialog_tr';

  var pmrow  = document.createElement('tr');
  var pml    = document.createElement('td');
  pml.className = 'dialog_ml';
  var pcontent = document.createElement('td');
  pcontent.className = 'dialog_mm';
  var pmr    = document.createElement('td');
  pmr.className = 'dialog_mr';

  var pbrow  = document.createElement('tr');
  var pbl    = document.createElement('td');
  pbl.className = 'dialog_bl';
  var pbm    = document.createElement('td');
  pbm.className = 'dialog_bm';
  var pbr    = document.createElement('td');
  pbr.className = 'dialog_br';

  dcontainer.appendChild(skintable);
  skintable.appendChild(ptbody);

  ptbody.appendChild(ptrow);
  ptrow.appendChild(ptl);
  ptrow.appendChild(ptm);
  ptrow.appendChild(ptr2);

  ptbody.appendChild(pmrow);
  pmrow.appendChild(pml);
  pmrow.appendChild(pcontent);
  pmrow.appendChild(pmr);

  ptbody.appendChild(pbrow);
  pbrow.appendChild(pbl);
  pbrow.appendChild(pbm);
  pbrow.appendChild(pbr);


  if (data.canclose)
  {
    var btnclose = document.createElement('div');
    var windowid = wfwindowcount;
    btnclose.className = 'dialog_btn_close';
    //btnclose.setAttribute('onclick', "close_VW_window('"+wfwindowcount+"')");
    btnclose.onclick = function() { close_VW_window(windowid); };

    dcontainer.appendChild(btnclose);
  }


  var contentdiv = document.createElement('div');

  if (data.cssclass)
    contentdiv.className = 'dialog_content '+data.cssclass;
  else
    contentdiv.className = 'dialog_content';

  pcontent.appendChild(contentdiv);

//  dcontainer.style.top = data.viewportoffsety + 30 + 'px';//(data.centerposy - 1) + 'px';
  dcontainer.style.top = (data.centerposy - 1)-windowedgeheight/2 + 'px';
  dcontainer.style.left = (data.centerposx - 1)-windowedgewidth/2 + 'px';
  dcontainer.style.zIndex = data.zindex;
  dcontainer.style.overflow = 'hidden';

  // use content div to force size
  // setting size on the table makes IE give our borders more room
  contentdiv.style.width = (data.formsuggestwidth + 2) + 'px';
  contentdiv.style.height = (data.formsuggestheight  + 2) + 'px';

  // fix IE6 bug: without relative the content won't scroll with it's scrollbar
  contentdiv.style.position = 'relative';


  contentdiv.appendChild(data.form);

  document.body.appendChild(dcontainer);

  showGreyoutOverlay();

  return dcontainer;
}

function showGreyoutOverlay()
{
  var viewport;
  if (document.body.clientHeight && document.documentElement.clientHeight)
  {
    if (document.body.clientHeight < document.documentElement.clientHeight)
      viewport = { width: document.body.clientWidth, height: document.body.clientHeight };
    else
      viewport = { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight };
  }
  else
    viewport = { width: document.body.clientWidth, height: document.body.clientHeight };

  var bgwidth = document.body.scrollWidth;
  var bgheight = document.body.scrollHeight;

  if(bgheight < viewport.height)
    bgheight = viewport.height;
  if(bgwidth < viewport.width)
    bgwidth = viewport.width;


  if(!window.tolliumWF_ModalOverlay)
  {
    tolliumWF_ModalOverlay = document.createElement('div');
    tolliumWF_ModalOverlay.className = 'tollium-modaloverlay';
    document.body.appendChild(tolliumWF_ModalOverlay);
  }

  tolliumWF_ModalOverlay.style.height = bgheight + 'px';
  tolliumWF_ModalOverlay.style.width = bgwidth + 'px';
  tolliumWF_ModalOverlay.style.zIndex = '19';
  tolliumWF_ModalOverlay.style.display = 'block';
}

function removeGreyoutOverlay()
{
  if (window.tolliumWF_ModalOverlay)
  {
    if (tolliumWF_ModalOverlay)
      tolliumWF_ModalOverlay.style.display = 'none';
  }
}

function close_VW_window(windowid)
{
  var wndref = document.getElementById('wfpopup_'+windowid);
  wndref.parentNode.removeChild(wndref);

  removeGreyoutOverlay();
}

function VW_window_setTitle(titlecontent)
{
  var titleref = document.getElementById('wfpopup_'+wfwindowcount+'_title');

  if (titleref)
  {
    titleref.innerHTML = titlecontent;
  }
}

/*
 Volkswagen rijbewijs - waardering
*/
var huidige_waardering;
function set_huidige_waardering(waardering)
{
  huidige_waardering = waardering;
  update_display_waardering(huidige_waardering);
}
function update_display_waardering(waardering)
{
  for (var i=1;i<=5;++i)
    document.getElementById('waardering'+i).className = i <= waardering ? 'point_awarded_big' : 'point_faded_big';
}
function on_waardering_over(e)
{
  if(!e)e=window.event;
  var target = toddGetEventTarget(e);

  if(target && target.nodeName.toUpperCase() == 'SPAN' && target.id.substr(0,10) == 'waardering')
  {
    var waardering = parseInt(target.id.substr(10,1));
    update_display_waardering(waardering);
  }
}
function on_waardering_out(e)
{
  if(!e)e=window.event;
  var target = toddGetEventTarget(e);

  if(target && target.nodeName.toUpperCase() == 'DIV' && target.id=='waarderingbox')
    update_display_waardering(huidige_waardering);
}
function on_waardering_click(e)
{
  if(!e)e=window.event;
  var target = toddGetEventTarget(e);

  if(target && target.nodeName.toUpperCase() == 'SPAN' && target.id.substr(0,10) == 'waardering')
  {
    var waardering = parseInt(target.id.substr(10,1));
    location.href += '?waardering=' + waardering;
  }
}

/*
 Open overlay voor verhuur pagina's
*/
function getviewportdimensions()
{
  if (self.innerHeight) // all except Explorer
    return { width: self.innerWidth, height: self.innerHeight };
  if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
    return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight };
  return { width: document.body.clientWidth, height: document.body.clientHeight };
}

function openlinksinpopup(e)
{
  if(!e)e=window.event;
  var target = toddGetEventTarget(e);

  while(target&&target.nodeName.toUpperCase()=='IMG')
    target=target.parentNode;

  if(target && target.nodeName.toUpperCase() == 'A')
  {
    var dim = getviewportdimensions();

    var viewportoffsetx = document.body.scrollLeft+document.documentElement.scrollLeft;
    var viewportoffsety = document.body.scrollTop+document.documentElement.scrollTop;
    //var desiredwidth = parseInt(dim.width*0.8);
    var desiredwidth = 650; /* temp */
    var desiredheight = parseInt(dim.height*0.8);




    var popup = document.createElement('div');
    var frame = document.createElement('iframe');
    frame.style.cssText = 'width: 100%; border: 0; height: '+desiredheight+'px;';
    frame.setAttribute('frameBorder', '0');

    popup.className = 'linkpopup';
    popup.appendChild(frame);
    frame.src = target.href;


    tolliumWFHook_OpenWindow( { form: popup
                              , centerposx: parseInt(viewportoffsetx + (dim.width - desiredwidth) / 2)
                              , centerposy: parseInt(viewportoffsety + (dim.height - desiredheight) / 2)
                              , formsuggestwidth: desiredwidth
                              , formsuggestheight: desiredheight
                              , zindex: 20 /* so we can use 1-9 for website styling */
                              , cssclass: 'linkpopupcontent'
                              , canclose: true
                              });
    return false;
  }
}



/* Controle telefoonnr,
   we laten alleen geldige 06 nummers toe */
function mobielnropschonen(str)
{
  var returnString = "";

  for (var col = 0; col < str.length; col++)
  {
    var char = str.charAt(col);

    if (char != ' ' && char != '-')
      returnString += char;
  }

  return returnString;
}

function isInteger(str)
{
  for (var col = 0; col < str.length; col++)
  {
    var char = str.charAt(col);
    if ((char < "0") || (char > "9"))
      return false;
  }
  return true;
}

/* Controle email adressen */

function isEmailValid(email)
{
  email = email.replace( /^\s*/, "" ).replace( /\s*$/, "" );

  // an email address can have a space within
  if (email.indexOf(' ') != -1)
    return false;

  var parts = email.split('@');

  // should only be one @
  if (parts.length > 2)
    return false;

  // check if there's a name in the email
  if (parts[0].length == 0)
    return false;

  // check if there's a domain in the email
  if (parts[1].length == 0)
    return false;

  var domainparts = parts[1].split('.');

  // check if at least 2 parts (topdomain and domain)
  if (domainparts.length < 2)
    return false;

  // topdomain needs to be at least 2 chars
  if (domainparts[domainparts.length-1].length < 2)
    return false;

  // domain needs to be at least 1 char
  if (domainparts[domainparts.length-2].length < 1)
    return false;

  return true;
}

function scirocco_submit()
{
  var errors = [];
  if(!document.getElementById('foto').value)
    errors.push("- Je hebt geen foto geupload");
  if(!document.getElementById('quote').value)
    errors.push("- Je hebt niet ingevuld wat je met je rijbewijs gaat doen");
  if(!document.getElementById('accoord').checked)
    errors.push("- Om mee te doen, moet je met de actievoorwaarden acoord gaan");
  if(errors.length)
  {
    alert("Je hebt het formulier nog niet helemaal ingevuld:\n" + errors.join("\n"));
    return;
  }
  document.getElementById('scirocco_form').submit();
}

function showsplash()
{
  if(typeof document.attachEvent != 'undefined')
    document.body.attachEvent('onload',showsplash2);
  else
    showsplash2();
}

function showsplash2()
{
  // TODO: check if either never shown the splash page or last time was over a week ago

  // When cookies are disabled, don't display splashpage
  // because we otherwise would get a splashpage on every pageview.
  toddWriteCookie("cookiesenabled", "yep", 1);
  if (toddReadCookie("cookiesenabled") != "yep")
    return;

  if (toddReadCookie("seensplash_hyvestheorybattle") == "seen")
    return;

  // make the splash screen not reappear for about two months
  toddWriteCookie("seensplash_hyvestheorybattle", "seen", 7*8);

  var splash = document.getElementById("splash");

  // force browser to calculate layout and size of the splash
  splash.style.position = "absolute";
  splash.style.zIndex = "999";
  splash.style.visibility = "hidden";
  splash.style.display = "block";

  var dim = getviewportdimensions();

  var viewportoffsetx = document.body.scrollLeft+document.documentElement.scrollLeft;
  var viewportoffsety = document.body.scrollTop+document.documentElement.scrollTop;

  var centerposx = parseInt(viewportoffsetx + (dim.width - splash.offsetWidth) / 2)
  var centerposy = parseInt(viewportoffsety + (dim.height - splash.offsetHeight) / 2)

  splash.style.left = centerposx+"px";
  splash.style.top = centerposy+"px";

  showGreyoutOverlay();

  splash.style.visibility = "visible";
}

function closesplash()
{
  var splash = document.getElementById("splash");

  splash.parentNode.removeChild(splash);

  removeGreyoutOverlay();
}

/*
- FireFox 1+
- Opera 8+ (not tested in 7)
- Safari 2+ (not tested in 1)
- KDE 3.4 or greater
- Internet Explorer 5+ (not tested in IE 5.2 for Mac)
*/
function onDOMContentLoaded(f){//(C)webreflection.blogspot.com
var a,b=navigator.userAgent,d=document,w=window,
c="__onContent__",e="addEventListener",o="opera",r="readyState",
s="<scr".concat("ipt defer src='//:' on",r,"change='if(this.",r,"==\"complete\"){this.parentNode.removeChild(this);",c,"()}'></scr","ipt>");
w[c]=(function(o){return function(){w[c]=function(){};for(a=arguments.callee;!a.done;a.done=1)f(o?o():o)}})(w[c]);
if(d[e])d[e]("DOMContentLoaded",w[c],false);
if(/WebKit|Khtml/i.test(b)||(w[o]&&parseInt(w[o].version())<9))
(function(){/loaded|complete/.test(d[r])?w[c]():setTimeout(arguments.callee,1)})();
else if(/MSIE/i.test(b))d.write(s);
}