/** Configuration variables ***********************************************/

var splashspeed = 1800
var mainspeed = 1200 // Main anim doesn't follow this duration accurately...
var pageswitchspeed = 500

/** Detect suitability of browser *****************************************/

usejs = true
usepushstate = !!(window.history && window.history.pushState)

/** Global variables ******************************************************/

var popped = ('state' in window.history), initialURL = location.href // for xbrowser history popstate event
var iframecounter = 0 // postfix for iframe names, to keep them unique.
var pageload = null // Holds the jqXHR object for the current page load.

/** Init ******************************************************************/

if(usejs) {
  $('.workshopregisterform').live('submit', workshopregsubmit)
  $('#contactusform').live('submit', contactsubmit)
  
  $('.hover')
  .live('mouseenter', latestimageover)
  .live('mouseleave', latestimageout)
  
  $('#bodyworkshops .upcominglist .item a')
  .live('mouseenter', upcominglistover)
  .live('mouseleave', upcominglistout)
  
  $('.workshopschedule .item a')
  .live('mouseenter', workshopschedover)
  .live('mouseleave', workshopschedout)
}

if(usepushstate) {
  $('a.ajax').live('click', linkhandler)
  window.onpopstate = pophandler
}

/** Hidden/shown 'CSS' for HTML *******************************************/

function shownforsplashanim ()
/*
  Set the last element in the DOM to be shown:
    display: block
  Only does anything if usepushstate === true
*/
{
  if(usepushstate) $('*').eq(-2).css('display', 'block')
}

function hiddenforsplashanim ()
/*
  Set the last element in the DOM to be hidden:
    visibility: hidden
    opacity: 0
  Only does anything if usepushstate === true
*/
{
  if(usepushstate) $('*').eq(-2).css('visibility', 'hidden')
                         .css('opacity', '0')
}

/** Splash to main screen animation ***************************************/

function showsplash ()
/*
  Animates splash sequence. Leaves splash DIV on #splash-logo.
*/
{
  if(!usepushstate) return
  
  function step0 (duration) {
    $('#splash-welcome').css('display', 'block')
    $('#splash-welcome').animate({
      opacity: 1, left: 556
    }, duration, 'easeOutExpo')
  }
  function step1 (duration) {
    $('#splash-to').css('display', 'block')
    $('#splash-to').animate({
      opacity: 1, left: 615
    }, duration, 'easeOutExpo')
    $('#splash-welcome').animate({
      left: 536
    }, duration, 'swing')
  }
  function step2 (duration) {
    $('#splash-welcome , #splash-to').animate(
      { opacity: 0, left: -600 },
      duration,
      'swing',
      function () {
        $('#splash-welcome , #splash-to').css('display', 'block')
      }
    )
    $('#splash-logo').css('display', 'block')
    $('#splash-logo').animate({
      opacity: 1, left: 461
    }, duration, 'easeOutExpo')
  }
  
  function loadingin () {
    if($('#splash-loading').length) {
      $('#splash-loading').animate(
        { opacity:1 }, 200, 'easeOutCirc', loadingout
      )
    }
  }
  function loadingout () {
    if($('#splash-loading').length) {
      $('#splash-loading').animate(
        { opacity:0.4 }, 400, 'easeInCirc', loadingin
      )
    }
  }
  
  loadingin()
  
  step0(splashspeed * 0.16)
  setTimeout(function () { step1(splashspeed*0.16) }, splashspeed * 0.32)
  setTimeout(function () { step2(splashspeed*0.5) }, splashspeed * 0.68)
}

function showmain ()
/*
  Transition from splash to main.
  Removes #splash from the DOM.
*/
{
  if(!usepushstate) return
  
  function out (duration) {
    $('#splash-logo').animate(
      { top: 0 },
      duration,
      'easeOutExpo',
      function () { $('#splash').remove() }
    )
  }
  
  function in0 (duration) {
    $('#mainlogo').css('visibility', 'visible')
    $('#mainlogo').css('opacity', '1')
  }
  function in1 (duration) {
    $('#mainheading >div > div')
    .slice(0, -1)
    .each(function (i, col) {
      setTimeout(function () {
        $(col).css('visibility', 'visible')
        $(col).animate({opacity:1}, duration*0.4, 'easeOutExpo')
      }, i*duration*0.1)
    })
  }
  function in2 (duration) {
    $('#mainline').css('visibility', 'visible')
    $('#mainline').animate({opacity:1}, duration)
  }
  function in3 (duration) {
    $('#mainbody > div > div')
    .slice(0, -1)
    .each(function (i, col) {
      setTimeout(function () {
        $(col).css('visibility', 'visible')
        $(col).animate({opacity:1}, duration*0.4, 'easeOutExpo')
      }, i*duration*0.1)
    })
  }
  function in4 (duration) {
    $('#footer , #disclaimer').css('visibility', 'visible')
    $('#footer').animate({opacity:1}, duration-100, 'easeInQuad')
    setTimeout(function () {
      $('#disclaimer').animate({opacity:1}, duration-100, 'easeInQuad')
    }, 100)
  }
  function in5 (duration) {
    $('#main').css('background-image', 'url(img/bg.png)')
    $('#floatbuttons').css('visibility', 'visible')
    $('#floatbuttons').animate({opacity:1}, duration)
  }
  
  out(mainspeed*0.3)
  setTimeout(function () { in0(mainspeed*0.3) }, mainspeed*0.301)
  setTimeout(function () { in1(mainspeed*0.6) }, mainspeed*0.35)
  setTimeout(function () { in2(mainspeed*0.4) }, mainspeed*0.4)
  setTimeout(function () { in3(mainspeed*0.6) }, mainspeed*0.55)
  setTimeout(function () { in4(mainspeed*0.6) }, mainspeed*0.5)
  setTimeout(function () { in5(mainspeed*0.15) }, mainspeed*0.85)
}

/** Window resizing handlers **********************************************/

function floatbuttons_reposition (ev)
/*
  Repositions #floatbuttons after window resizing.
*/
{
  var w = $(window).width()
  $('#floatbuttons').css(
    'right',
    Math.max(-9, w/2-630) + 'px'
  )
}

/** AJAX loading **********************************************************/

function loadpage (url, success, error)
/*
  Loads the page at url, which is a normal URL, as a JSON object.
  On success, calls success with the object.
  On failure/abort, calles error with the textStatus.
*/
{
  if(pageload) pageload.abort()
  url = url.split('#')[0]
  pageload = $.ajax({
    url: url + '?ajax',
    success: function (json) {
      pageload = null
      try {
        var o = eval(json)
        success(o)
      } catch(e) {}
    },
    dataType: 'text',
    error: function (jqxhr, err, exc) {
      pageload = null
      if(error) error(err)
    }
  })
}

/** Page switching ********************************************************/

function switchpage (p)
/*
  Switches the page contents to p.
*/
{
  var bodyheight = $('#mainbody > div').height()
  var newbody = $('<div></div>')
  newbody.css('display', 'none')
  newbody.html(p.body ? p.body : '')
  newbody.append('<div class="clear"></div>')
  
  var headingheight = $('#mainheading > div').height()
  var newheading = $('<div></div>')
  newheading.css('display', 'none')
  newheading.html(p.heading ? p.heading : '')
  newheading.append('<div class="clear"></div>')
  
  if(p.title !== undefined) {
    document.title = p.title + ' - WebWeaver Learning Center'
  } else {
    document.title = 'WebWeaver Learning Center'
  }
  
  $('#mainbody > div').animate(
    {'margin-top': -bodyheight},
    pageswitchspeed,
    'easeOutExpo',
    function () { $(this).remove() }
  )
  $('#mainbody').append(newbody)
  newbody.slideDown(pageswitchspeed, 'easeOutExpo')
  
  $('#mainheading > div').animate(
    {'margin-top': -headingheight},
    pageswitchspeed,
    'easeOutExpo',
    function () { $(this).remove() }
  )
  $('#mainheading').append(newheading)
  newheading.slideDown(pageswitchspeed, 'easeOutExpo')
  
  if(p.postjs !== undefined) setTimeout(function () {
    eval(p.postjs)
  }, pageswitchspeed+50)
}

/** Navigation handlers for dynamic content loading ***********************/

function linkhandler (ev)
/*
  Handles clicks on links.
  Links with class = 'ajax' are handled specially if usepushstate === true.
  Shows "loading" graphic next to clicked link while loading.
*/
{
  ev.preventDefault()
  
  var href = this.href
  
  loadpage(
    href,
    function (p) {
      $('#linkloading').hide()
      if(href !== location.href) {
        window.history.pushState(
          null,
          (p.title !== undefined ? (p.title+' - ') : '')
          + 'Web Weaver Learning Center',
          href
        )
      }
      switchpage(p)
    },
    function () {
      $('#linkloading').hide()
    }
  )
  
  var offset = $(this).offset()
  $('#linkloading').css('top', offset.top+$(this).outerHeight())
  $('#linkloading').css(
    'left',
    offset.left + ($(this).width()-$('#linkloading').outerWidth())/2
  )
  $('#linkloading').show()
}

function pophandler ()
/*
  Handles the onpopstate event.
  Shows "loading" graphic at the center of the page while loading.
*/
{
  var initialPop = !popped && location.href == initialURL
  popped = true
  if ( initialPop ) return
  
  loadpage(
    location.href,
    function (p) {
      $('#naviloading').hide()
      switchpage(p)
    },
    function () {
      $('#naviloading').hide()
    }
  )
  
  $('#naviloading').show()
}

/** Form submission handlers **********************************************/

function workshopregsubmit (ev)
{
  if(!/[^ ]/.test($('input[name=name]').val())) {
    alert('Please enter your name')
    ev.preventDefault()
    return false
  }
  
  if(!/[^@]+@.+/.test($('input[name=email]').val())) {
    alert('Invalid email address! Please enter your correct email address')
    ev.preventDefault()
    return false
  }
  
  doform(
    this,
    function (text) {
      if(text === 'success') {
        alert(
          'Workshop registration successful! We will notify you via'
          +' email on any upcoming workshops.'
        )
      } else {
        alert(
          'Workshop registration NOT successful :( Please email'
          +' cheryn@mywebweaver.com to enquire about our workshops.'
        )
      }
    }
  )
}

function contactsubmit (ev)
{
  if(!/[^ ]/.test($('input[name=name]').val())) {
    alert('Please enter your name')
    ev.preventDefault()
    return false
  }
  
  if(!/[^@]+@.+/.test($('input[name=email]').val())) {
    alert('Invalid email address! Please enter your correct email address')
    ev.preventDefault()
    return false
  }
  
  doform(
    this,
    function (text) {
      if(text === 'success') {
        alert(
          'Your enquiry has been sent. Thank you for your interest!'
        )
      } else {
        alert(
          'We could not send your enquiry :( Please email'
          +' cheryn@mywebweaver.com to enquire about our workshops.'
        )
      }
    }
  )
}

/** Latest image hover functions ******************************************/

function latestimageover (ev)
{
  $('.hoverimage', $(this))
  .stop(true)
  .fadeIn(200, 'easeOutQuint', function () { $(this).css('opacity','') })
}

function latestimageout (ev)
{
  $('.hoverimage', $(this))
  .stop(true)
  .fadeOut(200, 'easeInCirc', function () { $(this).css('opacity','') })
}

/** Upcoming workshops list hover functions *******************************/

function upcominglistover (ev)
{
  itemlist_hoverhelper(
    $('#bodyworkshops .upcominglist .item'), 'addClass', this
  )
}

function upcominglistout (ev)
{
  itemlist_hoverhelper(
    $('#bodyworkshops .upcominglist .item'), 'removeClass', this
  )
}

/** Workshops schedule hover functions ************************************/

function workshopschedover (ev)
{
  itemlist_hoverhelper($('.workshopschedule .item'), 'addClass', this)
}

function workshopschedout (ev)
{
  itemlist_hoverhelper($('.workshopschedule .item'), 'removeClass', this)
}

/** Utility functions *****************************************************/

function itemlist_hoverhelper (items, method, elt)
/*
  For making all a's in a div.item highlighted on mouseover of any a.
*/
{
  var self
  var breakout = false
  for(self=0; self<items.length; self++) {
    $('a', items.eq(self)).each(function (i, a) {
      if(a === elt) breakout = true
    })
    if(breakout) break
  }
  
  items.each(function (i, item) {
    $('a', item).removeClass('hover')
    if(i === self) {
      $('a', item)[method]('hover')
    }
  })
}

function doform (form, callback)
/*
  Submits a form and returns the results to callback, without leaving the
  page.
*/
{
  var name = 'workshopreg' + iframecounter++
  
  var results = $('<iframe name="'+name+'" id="'+name+'"></iframe>')
  results.css('display', 'none')
  $(document.body).append(results)
  
  form.target = name
  
  function checker () {
    var text = $('#'+name).contents().text()
    if(text === '') setTimeout(checker, 50)
    else {
      callback(text)
      $('#'+name).remove()
    }
  }
  
  checker()
}

