var 
  pos, delay = 0, tick = 0, tickerPause = 5000, tickerTimer, 
  lightboxItems = {"gallery":[],"company":[],"news":[]}, currentLightboxItem = {"gallery":0,"company":0,"news":0}, 
  sectionHeight = {}, resizeTimer, homeContainer, connectContainer, subsectionContainer, 
  employees, employeeCount = 1, currentEmployee = 0,
  defaultState = 'or',
  mapZoom = 2, mapMode = 'satellite';

function setPos() {
  pos = [];
  //console.log("scroll: "+$(window).scrollTop());
  $("body>section").each(function(){
    var elem = $(this), id = elem.attr("id"), offset = elem.offset().top, height = elem.height();
    pos.push({"id":"#"+id,"top":offset-200,"bottom":height+offset-100});
    //console.log("#"+id+" "+offset+" ("+(offset-200)+") "+(height+offset-0)+" ("+(height+offset-100)+")");
  });
  sectionHeight['gallery'] = $("#home").height();
  sectionHeight['company'] = $("#about").height();
  sectionHeight['news'] = $("#press-news").height();
}
function checkPos() {
  var currentPos = $(window).scrollTop();
  for (var i in pos) {
    section = pos[i];
    if (currentPos>=section['top'] && currentPos<=section['bottom']) {
      highlightSection($("#main-nav a[href="+section['id']+"]"));
      return;
    }
  }
}
function openSection(a) {
  var id = a.attr("href"), offset = $(id).offset().top;
  delay = 1;
  scrollToSection(id);
  highlightSection(a);
  window.setTimeout(function(){delay = 0;}, 250);
}
function scrollToSection(id) {
  var currentPos = $(window).scrollTop(), offset = $(id).offset().top, diff = ((currentPos-offset)/80)*-1;
  //console.log("scrollTo: "+offset);
  if (currentPos==offset) return;
  if (diff>0 && diff<10) diff = 10;
  if (diff<0 && diff>-10) diff = -10;
  if (id=='#home') {
    homeContainer.css({borderTopWidth:(144+(diff*-1))+"px"});
    $("html,body").animate({scrollTop: 0}, 250, function(){
      homeContainer.animate({borderTopWidth:"144px"}, 150);
    });
  }
  else if (id=='#connect') {
    connectContainer.css({borderBottom:'solid '+($(window).height()-(620+(diff*-1)))+'px #222'});
    $("html,body").animate({scrollTop: offset+diff}, 250).animate({scrollTop: offset}, 150, function(){
      connectContainer.css({borderBottom:'solid '+($(window).height()-620)+'px #222'});
    });
  }
  else $("html,body").animate({scrollTop: offset+diff}, 250).animate({scrollTop: offset}, 150);
}
function highlightSection(a) {
  var li = a.parent(), ul = li.parent();
  ul.find(".selected").removeClass("selected");
  li.addClass("selected");
}
function openSubSection(a, doScroll) {
  if (typeof doScroll=='undefined') doScroll = 1;
  var
    selector = a.attr("href"), li = a.parent(), ul = li.parent(), 
    section = ul.parent().parent(), sectionSelector = "#"+section.attr("id"),
    subSection = $(selector);
  if (doScroll) scrollToSection(sectionSelector);
  section.find("li.selected").removeClass("selected");
  li.add(selector).addClass("selected");
  var leftPos = $(selector).position().left*-1;
  subsectionContainer.animate({"margin-left":leftPos}, 250);
  setPos();
}
function processTweets(tweets) {
  var ticker = [], press = [];
  for (var i=0; i<tweets.length; i++){
    var
      username = tweets[i].user.screen_name,
      userImg = tweets[i].user.profile_image_url,
      status = '',
      postTime = relativeTime(tweets[i].created_at),
      link = '<a href="http://twitter.com/'+username+'/statuses/'+tweets[i].id_str+'" target="_blank">'+postTime+'</a>';
    if (tweets[i].retweeted_status!=undefined) userImg = tweets[i].retweeted_status.user.profile_image_url;
    status = tweets[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'" class="block">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return '<a href="http://twitter.com/'+reply.substring(1)+'">'+reply+'</a>';
    });
    ticker.push(
      '    <li>'+status+'</li>'+"\r\n"
    );
    press.push(
      '      <li><img src="'+userImg+'"/><span>'+status+'</span>'+link+'</li>'+"\r\n"
    );
  }
  $("#ticker ul").html(ticker.join(''));
  $("#buzz").html(press.join(''));
}
function relativeTime(timeValue) {
  var values = timeValue.split(" ");
  timeValue = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsedDate = Date.parse(timeValue);
  var relativeTo = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relativeTo.getTime() - parsedDate) / 1000);
  delta = delta + (relativeTo.getTimezoneOffset() * 60);
  if (delta<60) return 'less than a minute ago';
  else if (delta<120) return 'about a minute ago';
  else if (delta<(60*60)) return (parseInt(delta / 60)).toString() + ' minutes ago';
  else if (delta<(120*60)) return 'about an hour ago';
  else if (delta<(24*60*60)) return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  else if (delta<(48*60*60)) return '1 day ago';
  else return (parseInt(delta / 86400)).toString() + ' days ago';
}
function showState(e, state) {
  e.preventDefault();
  $("#offices .selected, #states .selected").removeClass("selected");
  $("#offices-"+state+", #state-"+state).addClass("selected");
}
function scrollTicker() {
  window.clearTimeout(tickerTimer);
  if (tick==1) {
    var tickerObj = $("#ticker ul"), tickerItem = tickerObj.find("li:first-child"), 
        tickerItemWidth = tickerItem.width()+8, tickerItemTime = tickerItemWidth*2.5;
    tickerItem.animate({marginLeft:(tickerItemWidth)*-1}, tickerItemTime, function(){
      tickerObj.append(tickerItem);
      tickerItem.css({marginLeft:0});
      tickerTimer = window.setTimeout(scrollTicker, tickerPause);
    });
  }
}
function openLightbox(type, obj) {
  $("#close-lightbox").remove();
  var prev = '', next = '';
  if (lightboxItems[type].length>1) {
    prev = ' <a class="prev">Prev</a>';
    next = ' <a class="next">Next</a>';
  }
  $("body").append('<div id="close-lightbox"></div><div id="'+type+'" class="lightbox"><a class="close">Close</a>'+prev+next+' <div class="content"></div></div>');
  if (type=='company') scrollToSection('#about');
  if (type=='news') scrollToSection('#press');
  populateLightbox(type, obj, 0, 1);
  $("#close-lightbox, .close").click(function(){closeLightbox(type);});
  $(".prev, .next").click(function(e){
    e.preventDefault();
    navLightboxSlides(type, $(this).attr("class"));
  });
}
function populateLightbox(type, obj, motion, newLightbox) {
  if (type=='gallery') {
    var 
      href = obj.attr("href"),
      file = obj.attr("data-file"),
      title = obj.attr("data-title"),
      subtitle = obj.attr("data-subtitle"),
      height = obj.attr("data-height"),
      isVideo = obj.parent().attr("class")=='video',
      html = isVideo ?
        '<video poster="/_content/posters/'+file+'.jpg" controls>'+
          '<source src="/_content/videos/'+file+'.mp4" type="video/mp4"/>'+
          //'<source src="/_content/videos/'+file+'.webm" type="video/webm"/>'+
          '<object type="application/x-shockwave-flash" data="/_scripts/player.swf" width="100%" height="350" bgcolor="#000000" id="mediaplayer" name="mediaplayer" tabindex="0">'+
            '<param name="allowfullscreen" value="true">'+
            '<param name="allowscriptaccess" value="always">'+
            '<param name="seamlesstabbing" value="true">'+
            '<param name="wmode" value="opaque">'+
            '<param name="flashvars" value="id=mediaplayer&amp;file=/_content/videos/'+file+'.mp4&amp;skin=http%3A%2F%2Fcontent.longtailvideo.com%2Fskins%2Fglow%2Fglow.zip&amp;controlbar.position=over">'+
          '</object>'+
        '</video>' :
        '<img src="'+href+'" height="'+height+'" alt=""/>',
    contentWidth = 708;
    html = '<h1>'+title+'&nbsp;</h1><h2>'+subtitle+'&nbsp;</h2>'+html;
  }
  if (type=='company') {
    var 
      file = obj.attr("data-file"),
      title = obj.attr("data-title"),
      height = obj.attr("data-height"),
      isVideo = obj.parent().attr("class")=='video',
      html =
        '<h1>'+title+'&nbsp;</h1><h2>&nbsp;</h2>'+
        '<video poster="/_content/posters/'+file+'.jpg" height="'+height+'" controls>'+
          '<source src="/_content/videos/'+file+'.mp4" type="video/mp4"/>'+
          //'<source src="/_content/videos/'+file+'.webm" type="video/webm"/>'+
          '<object type="application/x-shockwave-flash" data="/_scripts/player.swf" width="100%" height="350" bgcolor="#000000" id="mediaplayer" name="mediaplayer" tabindex="0">'+
            '<param name="allowfullscreen" value="true">'+
            '<param name="allowscriptaccess" value="always">'+
            '<param name="seamlesstabbing" value="true">'+
            '<param name="wmode" value="opaque">'+
            '<param name="flashvars" value="id=mediaplayer&amp;file=/_content/videos/'+file+'.mp4&amp;skin=http%3A%2F%2Fcontent.longtailvideo.com%2Fskins%2Fglow%2Fglow.zip&amp;controlbar.position=over">'+
          '</object>'+
        '</video>',
    contentWidth = 708;
  }
  if (type=='news') {
    var clonedHtml = obj.clone(), html, contentWidth = 768;
    clonedHtml.find("em, a").remove();
    html = clonedHtml.html();
  }
  currentLightboxItem[type] = obj.attr("data-lightbox");
  $("#"+type+" .loading-slide").attr("class", "slide");
  if (typeof motion=='undefined' || motion==0) {
    $("#"+type+" .slide").remove();
    $("#"+type+" .content").append('<div class="slide">'+html+'</div>');
  }
  else {
    $("#"+type+" .content").append('<div class="loading-slide">'+html+'</div>');
    if (motion=='prev') {
      $("#"+type+" .loading-slide").css({"left":"auto","right":contentWidth+"px"}).fadeTo(0,0).delay(10).animate({right:0,"opacity":1}, 250, function(){
        $(this).attr("class", "slide").animate({right:"5px"}, 25, function(){
          $(this).animate({right:"10px"}, 100);
        });
      });
      $("#"+type+" .slide").css({"left":"auto","right":"0"}).animate({right:-1*contentWidth,"opacity":.5}, 250, function(){$(this).remove();});
    }
    else {
      $("#"+type+" .loading-slide").css({"right":"auto","left":contentWidth+"px"}).fadeTo(0,0).delay(10).animate({left:0,"opacity":1}, 250, function(){
        $(this).attr("class", "slide").animate({left:"5px"}, 25, function(){
          $(this).animate({left:"10px"}, 100);
        });
      });
      $("#"+type+" .slide").css({"right":"auto","left":"0"}).animate({left:-1*contentWidth,"opacity":.5}, 250, function(){$(this).remove();});
    }
  }
  if (type=='gallery') {
    id = 'home';
    extraOffset = 95;
    extraHeight = 20;
    diffHeight = 18;
    if (isVideo) $("video").hover(function(){$(this).attr("controls", "");},function(){$(this).removeAttr("controls");});
  }
  if (type=='company') {
    id = 'about';
    extraOffset = 95;
    extraHeight = 62;
    diffHeight = -30;
    if (isVideo) $("video").hover(function(){$(this).attr("controls", "");},function(){$(this).removeAttr("controls");});
  }
  else if (type=='news') {
    id = 'press-news';
    extraOffset = 95;
    extraHeight = 200;
    diffHeight = 110;
  }
  var 
    elem = $("#"+id), offset = elem.offset().top+extraOffset,
    slideHeight = $(".slide").height()+extraHeight,
    loadingSlideHeight = $(".loading-slide").height()+extraHeight,
    maxSlideHeight = Math.max(slideHeight, loadingSlideHeight),
    elemHeight,
    lightboxHeight;
  if (maxSlideHeight>sectionHeight[type]) {
    //console.log('maxSlideHeight ('+maxSlideHeight+') > sectionHeight ('+sectionHeight[type]+')');
    elem.height(loadingSlideHeight);
    if (loadingSlideHeight==extraHeight) loadingSlideHeight = slideHeight;
    if (loadingSlideHeight<sectionHeight[type]) loadingSlideHeight = sectionHeight[type];
    elemHeight = loadingSlideHeight;
    lightboxHeight = loadingSlideHeight+diffHeight;
  }
  else {
    //console.log('maxSlideHeight ('+maxSlideHeight+') < sectionHeight ('+sectionHeight[type]+')');
    elemHeight = sectionHeight[type];
    lightboxHeight = sectionHeight[type]+diffHeight;
  }
  elem.animate({'height':elemHeight}, 250);
  if (newLightbox==1) $("#"+type).fadeOut(0).css({'top':offset,'left':0, 'height':lightboxHeight}).fadeIn(250);
  else $("#"+type).css({'top':offset}).animate({'height':lightboxHeight}, 250);
  $("[data-type="+type+"] .selected").removeClass("selected");
  obj.addClass("selected");
}
function navLightboxSlides(type, motion) {
  var selector = 'a';
  if (type=='news') selector = 'article';
  var lastSlide = lightboxItems[type].length-1, items = $("[data-type="+type+"] "+selector);
  if (motion=='prev') currentLightboxItem[type]--;
  if (motion=='next') currentLightboxItem[type]++;
  if (currentLightboxItem[type]<0) currentLightboxItem[type] = lastSlide;
  if (currentLightboxItem[type]>lastSlide) currentLightboxItem[type] = 0;
  var item = items.filter('[data-lightbox="'+currentLightboxItem[type]+'"]');
  populateLightbox(type, item, motion);
}
function closeLightbox(type) {
  $("#close-lightbox").remove();
  $("#"+type).fadeOut(250, function(){$(this).remove();});
  $("#home, #press-news").height('');
}
function nextEmployee() {
  var employee = employees.eq(currentEmployee);
  employee.find("header").animate({right:"-250px"}, 150).parent().find("img").animate({top:"390px",opacity:0}, 150, function(){
    employee.removeClass("selected");
    currentEmployee++;
    if (currentEmployee>employeeCount-1) currentEmployee = 0;
    employee = employees.eq(currentEmployee).addClass("stage");
    employee.find("header").animate({right:0}, 150);
    employee.find("img").animate({top:0,opacity:1}, 150, function(){
      employee.addClass("selected").removeClass("stage");
    });
  });
}
function updateHqMap() {
  $("#map-hq .selected").removeClass("selected");
  $("#map-hq-"+mapMode+"-"+mapZoom).addClass("selected");
}

$(document).ready(function() {
  homeContainer = $("#home");
  connectContainer = $("#connect");
  connectContainer.css({borderBottom:'solid '+($(window).height()-620)+'px #222'});
  $("html").addClass("js");
  $.get(
    '/_processes/tweets.json.php',
    {},
    function(data){processTweets(data);},
    "json"
  );
  $("#main-nav a").click(function(e){
    openSection($(this));
    return false;
  });
  $("a[href='#home']").click(function(e){
    openSection($("#main-nav a").eq(0));
    return false;
  });
  $("#ticker").hover(function(){
    tick = 0;
  },function(){
    tick = 1;
    window.clearTimeout(tickerTimer);
    tickerTimer = window.setTimeout(scrollTicker, tickerPause/2);
  }).find(">a").click(function(e){
    e.preventDefault();
    window.clearTimeout(tickerTimer);
    var toggle = $(this), ticker = toggle.parent().find("ul");
    if (ticker.width()==0) {
      toggle.animate({width:"945px","border-left-width":"36px"}, 250);
      ticker.animate({width:"912"}, 250);
      tick = 1;
      tickerTimer = window.setTimeout(scrollTicker, 250+tickerPause);
    }
    else {
      toggle.animate({width:"28px","border-left-width":"0"}, 250);
      ticker.animate({width:"0"}, 250);
      tick = 0;
    }
  });
  $("#home a").each(function(){
    var item = $(this);
    item.attr("data-lightbox", lightboxItems['gallery'].length);
    lightboxItems['gallery'].push(item.href);
  }).click(function(e){
    openLightbox('gallery', $(this));
    return false;
  });
  $("#about a").each(function(){
    var item = $(this);
    item.attr("data-lightbox", lightboxItems['company'].length);
    lightboxItems['company'].push(item.href);
  }).click(function(){
    openLightbox('company', $(this));
    return false;
  });
  $("section nav a").each(function(){
    $(this).parent().width($(this).width()+6);
  }).click(function(e){
    openSubSection($(this));
    return false;
  });
  $("#services").append('<div id="subsections"><div id="subsection-container"></div></div>').find("article").appendTo("#subsection-container");
  subsectionContainer = $("#subsection-container");
  $("#hotspots area").click(function(e){
    defaultState = $(this).data("state");
    showState(e, defaultState);
    return false;
  });
  $(".office-close").click(function(e){
    showState(e, 'or');
    return false;
  });
  $("#send").click(function(e){
    $(this).attr("href", "ma"+"il"+"to"+":"+"webmaster"+"@"+"billupsworldwide"+"."+"com");
  });
  $.get(
    '/_processes/news.json.php',
    {},
    function(data){
      var news = $("#press-news"), article, x;
      if (data && data.entries) for (var i=0; i<data.entries.length; i++) {
        x = data.entries[i];
        article = '    <article>'+"\r\n";
        article+= '      <header>'+"\r\n";
        if (x['title']!='...') article+= '        <h2>'+x['title']+'</h2>'+"\r\n";
        article+= '        <div class="date">'+x['published']+'</div>'+"\r\n";
        article+= '        <img src="'+x['image']+'" alt=""/>'+"\r\n";
        article+= '      </header>'+"\r\n";
        article+= '      <p>'+x['content']+'</p>'+"\r\n";
        article+= '    </article>'+"\r\n";
        news.append(article);
      }
      news.jPaginate({items:3});
      news.find("span").before(' <a class="more">&rsaquo; Read more</a>');
      /*
      news.find("article").each(function(){
        var item = $(this);
        item.attr("data-lightbox", lightboxItems['news'].length);
        lightboxItems['news'].push(item.href);
      }).click(function(){
        openLightbox('news', $(this));
      });
      */
      setPos();
    },
    "json"
  );
  //$("#press-news").jPaginate({items:3, position:"both"});
  //$("#press-news span").before('<em>&hellip; </em><a class="more">&rsaquo; Read more</a>');
  employees = $("#employee-container>div");
  employeeCount = employees.length;
  $("#next-employee").click(function(e){
    e.preventDefault();
    nextEmployee();
  });
  setPos();
  $(window).scroll(function(){
    if (delay==0) checkPos();
  });
  $("#view-roads").click(function(e){
    e.preventDefault();
    mapMode = 'roads';
    updateHqMap();
  });
  $("#view-satellite").click(function(e){
    e.preventDefault();
    mapMode = 'satellite';
    updateHqMap();
  });
  $("#zoom-map-in").click(function(e){
    e.preventDefault();
    if (mapZoom>0) mapZoom--;
    updateHqMap();
  });
  $("#zoom-map-out").click(function(e){
    e.preventDefault();
    if (mapZoom<9) mapZoom++;
    updateHqMap();
  });
});

(function($){
  $.fn.jPaginate = function(options) {
    var
      defaults = {
        items: 5,
        active: "active",
        paginationClass: "pagination",
        minimize: false,
        navItems: 6,
        position: "after",
        equal: false,
        offset: 50
      },
      options = $.extend(defaults, options);
    return this.each(function() {
      obj = $(this);
      var
        showPerPage = options.items,
        numberOfItems = obj.children().size(),
        numberOfPages = Math.ceil(numberOfItems/showPerPage),
        arrayOfElements = [],
        numP = 0,
        nexP = showPerPage,
        height = 0,
        maxHeight = 0;
      for (i=1;i<=numberOfPages;i++) {    
        arrayOfElements[i] = obj.children().slice(numP, nexP);
        if (options.equal) {	
          obj.children().slice(numP, nexP).each(function(){
            height += $(this).outerHeight(); 
          });
          if (height > maxHeight) maxHeight = height;
          height = 0;
        }
        numP += showPerPage;
        nexP += showPerPage;
      }
      if (options.equal) {	
        maxHeight += options.offset;
        obj.css({"height":maxHeight});
      }
      showPage(1);
      createPagination(1);
      function showPage(page) {
        obj.children().hide();
        arrayOfElements[page].show();
      }
      function createPagination(curr) {
        var 
          start = '<ul class="'+options.paginationClass+'">',
          end = '</ul>',
          items = '',
          nav = '',
          after = numberOfPages-options.after+1,
          pagi_range = paginationCalculator(curr);
        for (i=1;i<=numberOfPages;i++) {
          if (options.minimize == true) {
            var half = Math.ceil(numberOfPages/2)
            if (i>=pagi_range.start && i<=pagi_range.end) {
              if (i==curr) items+= '<li><a class="'+options.active+'" title="'+i+'">'+i+'</a></li>';
              else items+= '<li><a href="#" class="goto" title="'+i+'">'+i+'</a></li>';
            }
            else if (curr<=half) {
              if (i>=(numberOfPages-2)) {
                if (i==curr) items+= '<li><a class="'+options.active+'" title="'+i+'">'+i+'</a></li>';
                else items+= '<li><a href="#" class="goto" title="'+i+'">'+i+'</a></li>';
              } 
            }
            else if (curr>=half) {
              if (i<=2) {
                if (i==curr) items+= '<li><a class="'+options.active+'" title="'+i+'">'+i+'</a></li>'; 
                else items+= '<li><a href="#" class="goto" title="'+i+'">'+i+'</a></li>';
              }
            }
          }
          else {
            if (i==curr) items+= '<li><a class="'+options.active+'" title="'+i+'">'+i+'</a></li>';
            else items+= '<li><a href="#" class="goto" title="'+i+'">'+i+'</a></li>';
          }
        }
        nav = start + items + end;
        if (options.position == "before") obj.before(nav);
        else if (options.position == "after") obj.after(nav);
        else {
          obj.after(nav);
          obj.before(nav)
        }
      }
      function paginationCalculator(curr) {
        var
          half = Math.floor(options.navItems/2),
          upper_limit = numberOfPages-options.navItems,
          start = curr>half ? Math.max( Math.min(curr-half, upper_limit), 0) : 0,
          end = curr>half ? Math.min(curr+half+(options.navItems % 2), numberOfPages) : Math.min(options.navItems, numberOfPages);
        return {start:start, end:end};
      }
      $(".goto").live("click", function(e){
        e.preventDefault();
        openSection($("#nav-press a"));
        showPage($(this).attr("title"));
        $(".pagination").remove();
        createPagination($(this).attr("title"));
      });
    });
  };
})(jQuery);
