var xhr, slides, cmd = {};

var isBrochure;

document.onclick = function(ev) {
  ev = ev || window.event;
  var e = ev.target || ev.srcElement;
  if (e.tagName == 'IMG') e = e.parentNode;
  var f;
  if (f = cmd[e.getAttribute('cmd')])
    return f(e);
  if (e.type == 'checkbox')
    e.parentNode.parentNode.className = e.checked ? 'checked' : '';
  else if (e = getThumb(e)) {
    doShow(e.parentNode.parentNode, getIndex(e));
    return false;
  }
}


window.onload = function() {
  doLoad();
  var e, i = 0;
  while (e = document.forms[i++])
    switch (e.className) {
      case 'login quote':
        e.onsubmit = doLogin;
        break;
      case 'brochure':
        isBrochure = true;
      default:
        e.onsubmit = doEnq;
    }
}

function doLoad() {
  var e, id;
  if (e = document.getElementById('slides')) {
    var button = document.getElementById('button');
    slides = new Slides(e);
    if (slides.images.length > 1) {
      id = setInterval('slides.doInterval()', 6000);
      cmd.togg = function() {
        if (id) {
          clearInterval(id);
          id = false;
          button.className = 'play';
        } else {
          id = setInterval('slides.doInterval()', 6000);
          button.className = '';
        }
      }      
    }
  }  
}

function doEnq() {
  var e = this;
  if (e.className != 'busy') {
    if (!validate(e))
      e.className = 'invalid';
    else {
      var o = getData(e);
      if (isBrochure)
        o.Subject = 'Brochure Request';
      e.className = 'busy';
      xhr(e.action, o, function(r) {
        window.location = '/pages/thankyou';
      })
    }
  }
  return false;
}

function doLogin() {
  var e = this;
  if (e.className != 'login quote busy') {
    e.className = 'login quote busy';
    xhr('/session/login', getData(e), function(r) {
      if (r.ok) window.location = window.location.href;
      else e.className = 'login quote invalid';
    })
  }   
  return false;
}

function doShow(g, b) {
  return;
  var a = parseInt(g.getAttribute('i')) || 0;
  if (a != b) {
    g.setAttribute('i', b);
    a = g.firstChild.childNodes[a];
    b = g.firstChild.childNodes[b];
    a.style.zIndex = '0';
    b.style.zIndex = '1';
    a.style.display = b.style.display = 'block';
    doOpacityTransition(a, 1, 0);
    doOpacityTransition(b, 0, 1);
  }
}

function doOpacityTransition(node, a, b) {
  doTransition(a, b, function(i) {
    if (document.expando)
      node.style.filter = 'alpha(opacity=' + (i * 100) + ')';
    else
      node.style.opacity = i;
  })
}

function doTransition(a, b, f) {
  var i = a, id = setInterval(function() {
    i += (a < b ? 1 : -1) * 0.05;
    f(Math.round(-100 * (Math.cos(Math.PI * i) - 1) / 2) / 100);
    if ((b > a && i >= b) || (b < a && i <= b))
      clearInterval(id);
  }, 20);
  f(i);
}

function validate(form) {
  var e, i = 0;
  while (e = form.elements[i++])
    if (/req/.test(e.parentNode.className))
      if (e.type == 'text' && e.value === '')
        return false;
  return true;
}

function getThumb(e) {
  if (e.tagName == 'IMG') e = e.parentNode;
  if (/thumbs/.test(e.parentNode.className)) return e;
}

function getIndex(node) {
  var i = 0;
  while (node = node.previousSibling) i++;
  return i;
}

function getData(form) {
  var h = {}, e, i = 0;
  while (e = form.elements[i++])
    if (e.name)
      switch (e.type) {
        case 'select-one':
        case 'select':
          h[e.name] = e.options[e.selectedIndex].value || 
                      e.options[e.selectedIndex].text ; break;
        case 'checkbox':
          h[e.name] = e.checked && (e.value || true); break;
        default:
          h[e.name] = e.value;
      }
  return h;
}

function Slides(e) {
  this.images = e.getElementsByTagName('a');
  this.i = 0;
  this.n = this.images.length; 
  this.g = e;
}
Slides.prototype.doInterval = function() {
  if (this.n == 0)
    return;
  this.i++;
  if (this.i == this.n)
    this.i = 0;
  doShow(this.g, this.i);
}

// xhr:
new function() {
  var n = 0, h = {
    'custom-header':'true', 'Accept': 'application/json', 'Content-type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest', 'If-Modified-Since': 'Thu, 1 Jan 1970 00:00:00 GMT' // Stop IE7 caching
  };
  // object means post
  // no object means get
  // url is optional in posts, default is /api/
  xhr = function() {
    var o, m, path, body = '', f;

    for (var v, i = 0; i < arguments.length; i++)
      switch (typeof (v = arguments[i])) {
        case 'string':
          m = m || 'GET'; path = v; break;
        case 'object':
          m = 'POST'; path = path || '/api/'; body = JSON.stringify(v); break;
        case 'function':
          f = v; break;
      }

    try {
      o = new ActiveXObject('Msxml2.XMLHTTP')
    } catch(e) {
      try {
        o = new ActiveXObject('Microsoft.XMLHTTP')
      } catch(e) {
        o = new XMLHttpRequest()
      }
    }
    o.open(m, path, true);
    for (var id in h)
      o.setRequestHeader(id, h[id]);

    o.onreadystatechange = function() {
      switch (o.readyState) {
        case 4: {
          var s;
          if (f)
            try {
              f(!(s = o.getResponseHeader('Content-Type') || '') || /json/.test(s) || /api|schemas/.test(url) ?
                JSON.parse(o.responseText) : o.responseText, o);              
            } catch(e) {
              try {
                console.log(e)
              } catch(e) {}
            }
          o.onreadystatechange = function() {};
        }
      }
    }
    o.send(body);
    return o;
  }  
}

// http://www.JSON.org/json2.js
new function() {
if(!this.JSON){JSON={}}(function(){function f(n){return n<10?'0'+n:n}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z'};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,subs={'\\b':'\\\\b','\\t':'\\\\t','\\n':'\\\\n','\\f':'\\\\f','\\r':'\\\\r','"':'\\"','\\\\':'\\\\\\\\'},rep;function quote(string){if(/["\\\x00-\x1f]/.test(string)){string=string.replace(/([\x00-\x1f\\"])/g,function(a,b){var c=subs[b];if(c)return c;c=b.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16)})}return'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key)}if(typeof rep==='function'){value=rep.call(holder,key,value)}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null'}gap+=indent;partial=[];if(typeof value.length==='number'&&!value.propertyIsEnumerable('length')){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null'}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v}if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v)}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v)}}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v}}if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' '}}else if(typeof space==='string'){indent=space}rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}return str('',{'':value})}}if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j}throw new SyntaxError('JSON.parse');}}})();
}
