var app = {},
    device = {
      detect: function(key) {
        if(this['_'+key] === undefined) {
          this['_'+key] = navigator.userAgent.match(new RegExp(key, 'i'));
        }
        return this['_'+key];
      },
      iDevice: function() {
        return this.detect('iPhone') || this.detect('iPod');
      },
      android: function() {
        return this.detect('Android');
      },
      webOS: function() {
        return this.detect('webOS');
      },
      mobile: function() {
        return this.iDevice() || this.android() || this.webOS();
      },
      windows: function() {
        return navigator.platform.indexOf('Win') > -1;
      },
      firefox: function() {
        return this.detect('Firefox');
      }
    };

function getQuerystring(key, default_) {
  if (default_==null) default_=""; 
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

$.fn.spin = function(opts) {
  this.each(function() {
    var $this = $(this),
    data = $this.data();

    if (data.spinner) {
      data.spinner.stop();
      delete data.spinner;
    }
    if (opts !== false) {
      data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
    }
  });
  return this;
};

/**
 * Initialize
 */
(function() {
  $(function() {

    var maxheight = 0,
      spinnerOpts = { 
        lines: 14, // The number of lines to draw
        length: 7, // The length of each line
        width: 4, // The line thickness
        radius: 12, // The radius of the inner circle
        color: '#666', //($('body.home').length)?'#333':'#eee', // #rgb or #rrggbb
        speed: 1, // Rounds per second
        trail: 60, // Afterglow percentage
        shadow: false // Whether to render a shadow
      },
      spinner = document.createElement('div');

    $(spinner).addClass('spinner').spin(spinnerOpts);

    $('.home div.box').each(function(i, e) {
      if($(e).height() > maxheight) {
        maxheight = $(e).height();
      } 
    });
    $('.home div.box').css({height: maxheight+'px'});

    $('#logo').click(function() { window.location = '/'; });

    if($('ul.team').length) {
      $('ul.team').css({width: '790px', height: '650px', position: 'relative'});
      $('ul.team li').each(function(i, e) {
        $(this).css({position: 'absolute', top: Math.floor(i/4) * 300 + 'px', left: (i%4) * 190 + 'px'});
        $(this).attr('origleft', (i%4) * 190);
      });
      $('ul.team a').click(function() {
        var w1, w2;
        if($(this).parent().hasClass('selected')) {
          w1 = 737;
          w2 = 170;
          $(this).html($(this).html().split('Less').join('More'));
          $(this).parent().css({width: w1+'px'});
          $(this).parent().stop().animate({left: $(this).parent().attr('origleft')+'px', width: w2+'px'}, 250, 'linear', function() {
            $(this).removeClass('selected');
          });
        } else {
          w1 = 170;
          w2 = 737;
          $(this).html($(this).html().split('More').join('Less'));
          $(this).parent().addClass('selected');
          $(this).parent().css({width: w1+'px'});
          $(this).parent().stop().animate({left: 0, width: w2+'px'}, 250);
        }
        return false;
      });
    }

    $('#home-anim').css({opacity: 0});
    /*
    setTimeout(function() {
      $('#home-anim').animate({opacity: 0}, 3000);
    }, 2000);
    */

    var loading = false,
      pageNum = 0,
      category,
      currentCategory,
      loadBlog = function(category) {
        if(loading === false) {
          if(!category) category = 'blog';
          if(currentCategory != category) {
            currentCategory = category;
          }   
        }   

        loading = true;
        pageNum++;
        $('#blog-posts').append(spinner);
        $.ajax('/blog?content_category=' + currentCategory + '&page_size=3&page_num=' + pageNum, {
            method: 'get',
            success:
            function(data) {
              console.log(data);
              if(data == '') {
                $('#load-posts').remove();
              }
              $('#blog-posts').append(data);
              $(spinner).remove();
              loading = false;
              $('#blog-posts .new').css({visibility: 'visible', opacity: 0})
                .stop().animate({opacity: 1}, 500, function(a, b, c) {
                  $(this).removeClass('new');
                });
            }   
          }); 
    };

    $('#load-posts').click(function() {
      loadBlog($(this).attr('data-slug') != undefined ? $(this).attr('data-slug') : 'blog'); 
      return false;
    });

  });
}());

/**
 * Initialize rotator
 */
(function() {
  $(function() {
    var 
    currentItemNum = -1,
    width = $('div.rotator').width(),
    gotoItem = function(num) {
      var direction = 'right',
          duration = 500,
          totalItems = $('div.rotator li').length;
      if(num < 0 || num > totalItems -1) {
        return;
      }
      if(num != undefined) {
        direction = num > currentItemNum ? 'right' : 'left';
        currentItemNum = num;
      } else {
        currentItemNum = 0;
        duration = 1;
        $('div.rotator li').css({opacity: 0, 'z-index': '0'});
      }
      $('a.rotator').css({opacity: 1});
      if(currentItemNum == 0) {
        $('a.rotator.left').css({opacity: 0.3});
      }
      if(currentItemNum == totalItems -1) {
        $('a.rotator.right').css({opacity: 0.3});
      }
      if(totalItems == 1) {
        $('a.rotator').css({opacity: 0});
      }
      $('div.rotator li').each(function(i, e) {
        if(i == currentItemNum ||
            (direction == 'right' && i == currentItemNum - 1) ||
            (direction == 'left' && i == currentItemNum + 1)) {
          $(e).css({opacity: 1});
          if(i != currentItemNum) {
            $(e).css({'z-index': '5'}).stop().animate({left: (direction == 'right' ? '-' : '') + width + 'px'}, duration);
          }
          if(i == currentItemNum) {
            $(e).css({left: (direction == 'right' ? '' : '-') + width + 'px'});
            $(e).css({'z-index': '10'}).stop().animate({left: 0}, duration);
          }
        } else {
          $(e).css({opacity: 0});
        }
      });
    };
    gotoItem();
    $('a.rotator').click(function() {
      gotoItem(currentItemNum+($(this).hasClass('left')?-1:1));
      return false;
    });
  });
}());

