var variable;
var body;
var container;
var scroller;
var sectionItems;
var debug = false;

function Scroller() {
  var _this = this;
  this.containerOffset = container.offset().left;
  this.nav = $('#nav');
  this.navBg = $('#nav-bg');
  this.navPosition = parseInt(this.nav.css('top'));
  this.navTotalPadding = this.nav.outerWidth() - this.nav.width();
  this.oldNav = {
    width: parseInt(this.nav.css('width')),
    left: container.offset().left,
    paddingLeft: parseInt(this.nav.css('padding-left'))
  };
  this.sectionSpacing = parseInt($('.section').first().css('margin-bottom')) - 40;
  this.navBg.css('position', 'fixed');
  this.bodyW;
  this.navW;
  this.containerW = parseInt(container.css('width'));
  this.nav.css('left', container.offset().left);

  var findSections = function(nav_links) {
    //var sections = ['#web-section', '#design-section', '#experimental-section', '#about-section', '#contact-section'];
    var sections = [];
    nav_links.each(function(i) {
      sections.push($(this).attr('href'));
    });
    return sections;
  };
  //contains '#web-section' style strings of all sections
  this.sections = findSections($('#nav li a'));
  //alert(_this.sectionPositions[0]);

  $('#nav a, .button').click(function(e) {
    var $target = $(e.target);
    if (/^\#.*/.test($target.attr('href'))) {
      e.preventDefault();
      _this.scrollTo($target.attr('href'));
    }
  });

  $(window).resize(function(e) {
    _this.bodyW = parseInt(body.css('width'));
    _this.containerOffset = container.offset().left;
    _this.oldNav.left = _this.containerOffset;
    if (_this.navExpanding) {
      _this.nav.width(_this.bodyW - _this.navTotalPadding);
      _this.nav.css('padding-left', _this.containerOffset + _this.oldNav.paddingLeft);
    } else {
      _this.nav.width(_this.oldNav.width);
      _this.nav.css('padding-left', _this.oldNav.paddingLeft);
      _this.nav.css('left', _this.containerOffset);
    }
    if (_this.bodyW <= 1024) {
      $('#top-link').fadeOut(200);
    } else if(offset > _this.navPosition) {
      $('#top-link').fadeIn(200);
    }
    $('#buffer').css('height',
      $(window).height() -
      ($('#buffer').offset().top - 
      $('.section').last().offset().top + _this.sectionSpacing) -
      $('#footer').outerHeight()
    );
  });
  $(window).trigger('resize');

  this.navExpanding = false;
  this.expandOnce = false;
  this.shrinkOnce = false;
  var offset = 0;
  $(window).scroll(function(e) {
    offset = $(window).scrollTop();
    _this.setArrow();
    if (offset > _this.navPosition) {
      _this.nav.css('position', 'fixed');
      _this.nav.css('top', 0);
      if (!_this.navExpanding)
        _this.nav.stop();
      _this.navExpanding = true;
      if (!_this.expandOnce)
        _this.nav.animate({
          width: _this.bodyW - _this.navTotalPadding,
          left: 0,
          paddingLeft: _this.containerOffset + _this.oldNav.paddingLeft
        }, 200);
        if (parseInt(body.css('width')) >= 1024)
          $('#top-link').fadeIn(200);
      _this.expandOnce = true;
      _this.shrinkOnce = false;
    } else {
      if (_this.nav.outerWidth() >= _this.bodyW)
        _this.nav.width(600);
      _this.nav.css('position', 'absolute');
      _this.nav.css('top', 212);
      if (_this.navExpanding)
        _this.nav.stop();
      if (!_this.shrinkOnce) {
        _this.nav.animate(_this.oldNav, 300);
        $('#top-link').fadeOut(200);
      }
      _this.shrinkOnce = true;
      _this.expandOnce = false;
      _this.navExpanding = false;
    }
    //clearTrace();
    //trace("navExpanding: " + _this.navExpanding + "<br>");
    //trace("scrolled: " + $(window).scrollTop() + "<br>");
  });
}

Scroller.prototype.scrollTo = function(section) {
  URL.setTarget(section);
  $('body, html').animate({
    scrollTop: $(section).offset().top - this.sectionSpacing
  }, 1000);
}
Scroller.prototype.jumpTo = function(section) {
  $('body, html').scrollTop($(section).offset().top - this.sectionSpacing);
  this.setArrow();
}
Scroller.prototype.setArrow = function() {
  //clearTrace();
  var findSectionPositions = function(sections) {
    var positions = [];
    $(sections).each(function (i) {
      var spacing = (i == 0) ? 100 : 140;
      positions.push($(sections[i]).offset().top - spacing);
    });
    return positions;
  };
  var getXCenter = function(jElem) {
    return jElem.offset().left + jElem.outerWidth()/2;
  };
  var sectionPositions = findSectionPositions(this.sections);

  //_this.nav.find('.arrow').css('display', 'none');
  //$(e.currentTarget).parent().find('.arrow').delay(1000).fadeIn(200);
  var i;
  var current = undefined;
  //trace(this.sections[0]);
  //trace(sectionPositions.length);
  for (i = 0; i < sectionPositions.length; i++) {
    //trace(sectionPositions[i]);
    if ($(window).scrollTop() >= sectionPositions[i]) {
      current = i
      //this.nav.css('display', 'none');
      //this.nav.css('color', 'yellow');
      //trace($(window).scrollTop() + " > " + sectionPositions[i] + ": " + this.sections[i]);
      //break;
    }
  }
  URL.setSection(this.sections[current]);
  if (!URL.hasChanged())
    return;
  var arrow = $('#nav-arrow.arrow').first();
  if (current == undefined) {
    arrow.fadeOut(500);
    trace('fade out');
  } else if (URL.oldSection == undefined && URL.currSection != undefined) {
    trace('fade in');
    arrow.css('left', getXCenter($('#nav li a').first()));
    arrow.fadeIn(500);
  }
  $('#nav li a').each (function (index) {
    if (index == current && URL.reachedTarget()) {
      $(this).css('color', '#a8b8c9');
      var offset = getXCenter($(this));
      //arrow.css('left', offset);
      arrow.animate({
        left: offset
      }, 500);
    } else {
      $(this).css('color', '#f2f5f8');
    }
  });
}

function getExt(fileStr) {
  var dotIndex = fileStr.lastIndexOf(".");
  return fileStr.slice(dotIndex);
}

function getName(fileStr) {
  var dotIndex = fileStr.lastIndexOf(".");
  if (dotIndex == -1) dotIndex = fileStr.length;
  return fileStr.slice(0, dotIndex);
}

function onload(jViewBox) {
  //alert(jViewBox.attr('id'));
  var boxCover = jViewBox.find('.box-cover');
  boxCover.find('.box-loader').fadeOut(200);
  boxCover.delay(500).slideUp(400, function() {
    boxCover.css('top', 'auto');
    boxCover.css('bottom', '0');
    //boxCover.find('.box-loader').animate({opacity: 1, width: 0}, 0);
  });
}

var flash  = {
  swfVersionStr: "10.0.0",
  xiSwfUrlStr: "flash/playerProductInstall.swf",
  flashvars: {},
  params: {
    quality: "high",
    bgcolor: "#ffffff",
    allowscriptaccess: "sameDomain",
    allowfullscreen: "true",
    wmode: "transparent"
  },
  /*attributes: {
    id: "flash-stuff",
    name: "flash-stuff",
    align: "middle",
  },*/
  load: function(file, targetId) {
    var attributes = {id: targetId, name: targetId};
    swfobject.embedSWF('flash/swfs/' + file, targetId,
      "942", "500",
      flash.swfVersionStr, flash.xiSwfUrlStr, 
      flash.flashvars, flash.params, attributes);

      setTimeout(function() {
        var viewBox = $('#flash-' + getName(file));
        var flashBlocked = flash.isBlocked(viewBox);
        if (flashBlocked) onload(viewBox);
      }, 1000);
  },
  isBlocked: function(viewBox) {
    var content;
    if (viewBox.find('.box-content div').html() == null) {
      //alert('one level');
    } else {
      //alert('two levels');
      content = viewBox.find('.box-content div');
    }
      content = viewBox.find('.box-content');
    var html = content.html();
    var patterns = [
      /chrome.extension/,
      /span.{1,10}[Ff]lash.{1,10}span/,
      /fc\-toolbar/,
      /url\(.?data.image.png/,
      /url\(.?chrome.{0,10}flash/,
      /flash.{0,10}block/,
      /ensure.{1,10}adobe flash player/i //means that flash is not installed.
      ];
    var flashBlocked = false;
    for (var i = 0; i < patterns.length; i++) {
      if (patterns[i].test(html)) {//true means that it found flash-blocker insertions
        flashBlocked = true;
        break;
      }
    }
    //flashBlocked = true
    if (flashBlocked) {
      //display message that flash is blocked
      viewBox.find('.flash-detected').delay(1000).fadeIn(500).delay(1000).fadeOut(1000);
    } else {
      //alert(html);
    }
    return flashBlocked;
  }
}


function PrevIcons(jSectionItem) {
  this.icons = jSectionItem.find('.preview-icon');
  this.viewBox = this.icons.parent().find('.view-box');
  //currently open icon
  this.current = null;
  //previous icon
  this.previous = null;
  this.selected = false;
  //alert(this.icons.length);
  var _this = this;
  
  //var icons = this.icons;
  _this.icons.each(function (icon_num) {
    var i = PrevIcons.total;
    $(_this.icons[icon_num]).attr('id', 'icon' + i.toString());
    $(_this.icons[icon_num]).attr('current', false);
    PrevIcons.total++;
  });
  _this.icons.mouseover(function(e) {
    //trace($(e.currentTarget).attr('id'));
    //trace($(e.currentTarget).find('.icon-text').text());
    var iconText = $(e.currentTarget).find('.icon-text').first();
    iconText.slideDown('fast');
  });
  _this.icons.mouseout(function(e) {
    //trace($(e.currentTarget).attr('current') == true);
    if ($(e.relatedTarget).parent().parent().attr('id') !=
      $(e.currentTarget).attr('id') &&
      $(e.currentTarget).attr('current') == 'false')
    {
      $(e.currentTarget).find('.icon-text').first().slideUp(300);
    }
  });
  $('.icon-text').mouseout(function(e) {
    var iconText = $(e.currentTarget).parent().parent();
    if (iconText.attr('id') !=
      $(e.relatedTarget).parent().attr('id') &&
      iconText.attr('current') == 'false')
    {
      $(e.currentTarget).slideUp(300);
    }
    //prevent icons.mouseout() from being triggered.
    //Not sure why it gets triggered in the first place.
    e.stopImmediatePropagation();
  });

  _this.icons.click(function (e) {
    _this.previous = _this.current;
    //_this.selected = true;
    var icon = $(e.currentTarget);
    _this.current = icon;
    trace("curr: " + _this.current.attr('id'));

    if (_this.previous != null &&
      _this.current.attr('id') == _this.previous.attr('id')) return;

    //icon.find('.icon-text').fadeTo(50, 0.9).delay(50).fadeTo(50, 1);
    icon.find('.arrow').fadeIn();
    icon.attr('current', true);
    var target = icon.attr('data-target');
    var full_image = icon.attr('data-full-image');
    var path = "content/" + target + "?full_image=" + full_image;
    var boxCover = _this.viewBox.find('.box-cover');
    var firstTimeDelay = 0;
    if (_this.viewBox.css('display') == 'none') {
      firstTimeDelay = 500;
      _this.viewBox.fadeIn(firstTimeDelay);
    }
    boxCover.delay(firstTimeDelay).slideDown(300, function(e) {
      //boxCover.find('.box-loader').animate({width: 942-20}, 400);
      boxCover.find('.box-loader').fadeIn(400);
      _this.viewBox.find('img').first().fadeOut(100);
      boxCover.css('top', '0');
      boxCover.css('bottom', 'auto');
      if (getExt(target) == '.swf') {
        var flashId = 'flash-' + getName(target);
        _this.viewBox.attr('id', flashId);
        _this.viewBox.find('.box-content').empty();
        _this.viewBox.find('.box-content').prepend('<div id="flash-content">Hello</div');
        flash.load(target, 'flash-content');
        //swfobject.embedSWF('flash/swfs/' + target, "flash-content", "942", "500", "10.0.0");
        /*setTimeout(function() {
          var viewBox = $('#flash-' + getName(target));
          var flashBlocked = flash.isBlocked(viewBox);
          if (flashBlocked) onload(_this.viewBox);
        }, 1000);*/
        //_this.viewBox.find('.box-content div div').attr('id', 'flash-blocker');
      } else {
        _this.viewBox.find('.box-content').load(path, function() {
          _this.viewBox.find('img').first().load(function () {
            onload(_this.viewBox);
          });
        });
      }
    });
    trace(path);
    if (_this.previous != null) {
      _this.previous.find('.arrow').fadeOut();
      _this.previous.attr('current', false);
      _this.previous.trigger('mouseout');
    }
  });
  if (_this.viewBox.css('display') != 'none')
    _this.icons.first().trigger('mouseover').trigger('click');
}
PrevIcons.total = 0;
PrevIcons.list = [];


function trace(htmlMessge) {
  var trace = $('#trace');
  trace.html(trace.html() + htmlMessge + '<br />');
}
function clearTrace() {
  $('#trace').html('');
}

var URL = (function() {
  return {
    target: undefined,
    _reachedTarget: true,
    oldSection: undefined,
    currSection: undefined,
    init: function() {
      URL.currSection = URL.fromSectionHash(location.hash);
      URL.jumpToCurrent();
    },
    toSectionHash: function(section) {
      if (section == undefined)
        return '!';
      else
        return '#!' + section.replace('#', '').replace('\-section', '');
    },
    fromSectionHash: function(sectionHash) {
      if (sectionHash == '' || sectionHash == "#!")
        return '#everything';
      else
        return sectionHash.replace('!', '') + "-section";
    },
    setTarget: function(section) {
      URL.target = section;
      URL._reachedTarget = false;
    },
    reachedTarget: function() {
      if (!URL._reachedTarget) {
        URL._reachedTarget = URL.currSection == URL.target;
      }
      return URL._reachedTarget;
    },
    setSection: function(section) {
      URL.oldSection = URL.currSection;
      URL.currSection = section;
      if (URL.hasChanged())
        location.hash = URL.toSectionHash(section);
    },
    hasChanged: function() {
      return URL.oldSection != URL.currSection;
    },
    jumpToCurrent: function() {
      scroller.jumpTo(URL.currSection);
      //location.hash = URL.currSection;
    }
  }
})();

$(document).ready(function() {
  // Debug stuff
  if (debug) {
    $('#trace').show();
  }

  body = $('body');
  container = $('#everything .container');


  scroller = new Scroller();
  $('#nav-arrow').css('top', $('#nav').outerHeight());

  sectionItems = $('.section-item');
  sectionItems.each(function (i) {
    PrevIcons.list.push( new PrevIcons($(sectionItems[i])) );
  });

  $('#email-form textarea').autoResize();

  //create validators for contact form
  var emailValidators = Validators.create([
    {id: 'name-field', validator: validateNotEmpty},
    {id: 'email-field', validator: validateEmail},
    {id: 'message-field', validator: validateNotEmpty},
  ]);
  //var icons = new PrevIcons($('.section-item')[5]);
  
  $("#email-form").submit(function(e) {
    var request = $(this).serialize();
    if(!emailValidators.anyEmpty()) {
      $.post('/email', request, function(data) {
        //alert("it works");
        $("#mail-result").html(data);
        $('#mail-result').fadeIn();
        //$("#mail-result").animate({opacity: 0}, 0);
        //$("#mail-result").animate({opacity: 1}, 'fast');
        emailValidators.restore();
      });
    }
    //alert(request);
    return false;
  });

  $("#email-form a").click(function(e) {
    e.preventDefault();
  });

  $(window).load(function() {
    URL.init();
  });

});

function flashLoaded(fileName) {
  //alert('flash loaded: ' + fileName);
  var viewBox = $('#flash-' + getName(fileName));
  onload(viewBox);
}

