// Set up namespace
if(typeof(worldbar) == 'undefined') {
  worldbar = {};
  worldbar.helper = {};
  worldbar.config = {};
  worldbar.flyer = {};
}

/*** CONFIG ***/
// Config settings
worldbar.config = {
  // panels
  scale_speed: 200,
  flip_speed: 200,
  blend_speed: 100,
  // overlay
  overlay_speed: 400,
  overlay_opacity: 0.7,
  // content
  default_content: '/loader/content/featured',
  content_height_1: 522,
  content_height_2: 1054,
  content_height_3: 1586,
  content_padding: 5,
  // flyers
  expand_speed: 400,
  expand_height: 373,
  contract_speed: 100,
  contract_delay: 0,
  contract_height: 40,
  no_flyer_image: 'no_flyer_image.png',
  // window
  scroll_speed: 500
}

/*** FUNCTIONS ***/
// Change number of columns based on window width
worldbar.resize_window = function() {
  var width = $(window).width();
  var cols = parseInt((parseInt(width)) / 246);
  if(cols >= 5) {
    cols = 5;
  }
  
  $('#container').attr('class','cols_' + cols);
  $('#banner_content').attr('class','cols_' + cols);
  
  if(cols <= 2) {
    $('#logo').removeClass().addClass("logo_small");
    $('#navbar').removeClass().addClass("menu_small");
    $('#flyers').hide();
    $('#flyers_compact').show();
    $('#flyers_header_compact').removeClass().addClass("flyers_compact_2_col");
  }
  if(cols == 3) {
    $('#logo').removeClass().addClass("logo_medium");
    $('#navbar').removeClass().addClass("menu_main");
    $('#flyers').hide();
    $('#flyers_compact').show();
    $('#flyers_header_compact').removeClass().addClass("flyers_compact_3_col");
  }
  if(cols >= 4) {
    $('#logo').removeClass().addClass("logo_main");
    $('#navbar').removeClass().addClass("menu_main");
    $('#flyers_compact').hide();
    $('#flyers').show();
  }
}

// Load content in to content div
worldbar.load_content = function(url) {

  $content_window.fadeTo('fast', 0.01, function() {
    $('#featured').cycle('destroy');
    $content_window.empty();
    $('.content_preloader').show();
    
    $.getJSON(url, function(data){
      if(data.success) {
        $('.content_preloader').hide();
        
        $content_window.html(data.content);
        
        total_rows = worldbar.helper.num_rows($('#content_html').height());
        expand_rows = parseInt(total_rows) - 1;
        expand_delay = worldbar.config.expand_speed * expand_rows;
  
        $('#content_html').addClass('rows_'+total_rows);
        worldbar.helper.expand(expand_rows);
  
        $content_window.delay(expand_delay).fadeTo('slow', 1);
        
      } else {
        alert('Something went wrong');
      }
    });
    
    if (url != worldbar.config.default_content) {
      $content_close.show();
    }
  });
}

// Fancy spin action on panels
worldbar.spin_panel = function($this) {
  if ($.browser.msie && $.browser.version.substr(0, 1) < 9) {
    worldbar.simple_spin_panel($this);
    return;
  }

  var $frame = $this.parents('.frame');
  var $sides = $this.find(".info, .icon");
  var $showing = $sides.filter(':visible');
  var $hiding = $sides.not(':visible');
  var rotation = '+=180';
  if(worldbar.helper.showing_icon($showing)) {
    var rotation =  '-=180';
    $this.css('transform','skew(360deg, 180deg) scale(1, 1)');         
  }

  $sides.css('opacity',0);
    
  $this.addClass('spinning');

  if (!$this.filter(':animated').size() > 0) {
    $frame
      .stop()
      .animate({
        scale: 0.75
      },
      worldbar.config.scale_speed, function() {
        $this
          .stop()
          .rotate3Di(
            rotation,
            worldbar.config.flip_speed,
            {
              sideChange: function() {
                $frame.animate({
                  scale: 1
                },
                worldbar.config.scale_speed
                );
                $this.toggleClass('flipside');
              },
              complete: function() {
                $this
                  .removeClass('spinning')
                  .css('transform','');
                $hiding
                  .stop()
                  .css('opacity', 0.75)
                  .show()
                  .animate({
                    opacity: 1
                  },
                  worldbar.config.blend_speed
                  );
                if (!worldbar.helper.showing_icon($showing)) {
                  worldbar.overlay('on');
                }
              }
            });
      });
  }
}

// Basic spin action on panels
worldbar.simple_spin_panel = function($this){
  var $frame = $this.parents('.frame');
  var $sides = $this.find(".info, .icon");
  var $showing = $sides.filter(':visible');
  var $hiding = $sides.not(':visible');

  $this.toggleClass('flipside');
  $showing.hide();
  $hiding.show();
  if (!worldbar.helper.showing_icon($showing)) {
    worldbar.overlay('on');
  }
}

// Panels overlay
worldbar.overlay = function(state) {
  if (state == 'on') {
    // Show overlay
    $("#panel_overlay")
      .css({'height': $('#content').height()})
      .show()
      .animate({
        opacity: worldbar.config.overlay_opacity
      }, worldbar.config.overlay_speed
    );
  }
  else
  {
    // Hide overlay
    $('#panel_overlay').animate({
      opacity: 0
    }, worldbar.config.overlay_speed, function() {
      $('#panel_overlay').hide();
    });
  }
}

// Basic spin action on panels
worldbar.flyers_expand = function($this){
  $this
    .animate({
      height: worldbar.config.expand_height
    }, worldbar.config.expand_speed);
}

// Basic spin action on panels
worldbar.flyers_contract = function($this){
  $this
    .delay(worldbar.config.contract_delay)
    .animate({
      height: worldbar.config.contract_height
    }, worldbar.config.contract_speed);
}


// Load Flyers
worldbar.load_flyer = function($this){
  var $new_night = $this;
  var $old_night = $(".flyers_menu").find('.flyer_active').not($new_night);
  
  $old_night.removeClass('flyer_active');
  $new_night.addClass('flyer_active');
  
  worldbar.night = $new_night.attr('href');
  
  // Reset the carousel
  if (typeof flyCarousel != 'undefined') {
    $('#carousel_container *').remove();
    $('#carousel_container').append('<div id="mycarousel" class="jcarousel-skin"><ul></ul></div>')
  }
  
  worldbar.flyers_loaded = false;
  
  // Load the carousel
  $('#mycarousel').jcarousel({
    itemFallbackDimension: 1020,
    scroll: 1,
    initCallback: flyers_initCallback,
    itemLoadCallback: flyers_itemLoadCallback,
    itemVisibleInCallback: flyers_fbLoadCallback
  });

}

/*** HELPER FUNCTIONS ***/
// Is icon showing?
worldbar.helper.showing_icon = function($el) {
  if($el.filter('.icon').size() > 0) {
    return true;
  } else {
    return false;
  }
}

// Expand div
worldbar.helper.expand = function(rows) {
  h = ((rows+1) * worldbar.config.content_height_1)+(rows*(2 * worldbar.config.content_padding));
  $('.content_box').animate({
    height: h
  }, worldbar.config.expand_speed, function() {
    return true;
  });
}

// Number of rows to expand by
worldbar.helper.num_rows = function(pixels) {
  if(pixels > worldbar.config.content_height_2 - 64) {
    return "3";
  } else if (pixels > worldbar.config.content_height_1 - 64 && pixels <= worldbar.config.content_height_2 - 64) {
    return "2";
  } else {
    return "1";
  }
}

// Scale an image proportionately
worldbar.helper.scale_image = function(width, height) {
  var container_height = 260;
  var container_width = 390;
  var aspect_ratio = height/width;
  
  if(height > width) {
    // Portrait
    $('#photo img').css({
      'height': '100%',
      'width': 'auto'
    });
  } else {
    // Landscape
    var resize_width = container_width;
    var resize_height = aspect_ratio * resize_width
    
    var padding = ((container_height - resize_height) / 2);
    $('#photo img').css({
      'margin-top': padding
    });
  }
}

// Return day name from date
worldbar.helper.day_name = function(day, lower, shorten) {
  var weekday = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
  var day_name = weekday[day.getDay()];
  
  day_name = (lower) ? day_name.toLowerCase() : day_name;
  day_name = (shorten) ? day_name.substring(0,3) : day_name;
  
  return day_name;
}

// Pause a function
worldbar.helper.pause = (function() {
  var timer = 0;
  return function(callback, ms) {
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

// Spin panels back to original position
worldbar.helper.spin_back = function($new_panel) {
  var $old_panels = $(".container_panel").find('.panel.flipside').not($new_panel);
  $(".container_panel").css('z-index', '') 
  
  if($old_panels.size() > 0) {
    setTimeout(function() {
    $old_panels.each(function() {
      worldbar.spin_panel($(this));
    }); 
    }, 300);
  }
}

worldbar.helper.addthis_reload = function() {
  var script = 'http://s7.addthis.com/js/250/addthis_widget.js#domready=1';
  if ( window.addthis ) {
    window.addthis = null;
  }
  $.getScript(script);
}


/*** ACTION ***/
$(document).ready(function() {
  
  // Resize the columns to fit in the window -----------------------
  worldbar.resize_window();
  
  // jQuery objects ------------------------------------------------
  $spin_panels = $("#content .panel, #navbar a, .flyer_guestlist");
  $content_url = $("a.content_url, .fl_fb_images a, #flyers_compact a");
  $content_close = $("#content .content_box .close_icon, #panel_overlay, .flipside .icon");
  $content_window = $('#content .content_loader');
  $flyers = $('#flyers');
  $flyers_menu = $('.flyers_menu a');
  $button_like = $('.button_like');
  $button_share = $('.button_share');
  $photo_thumbs = $('#fbcarousel .jcarousel-item');

  // Load the default or shared contact ----------------------------
  if (loader_url.length) {
    if (loader_type == 'content') {
      var href = base_url + loader_url;
      var $new_panel = $('#content a.panel_image[href="' + href + '"]:first').closest('.panel');
      worldbar.screen_top = $("html").scrollTop();
      worldbar.spin_panel($new_panel);
      worldbar.load_content('/' + loader_url);
    } else if (loader_type == 'flyer') {
      worldbar.flyers_expand($flyers);
      var href = base_url + loader_url;
      var $this = $('.flyers_menu a[href="' + href + '"]:first');
      worldbar.load_flyer($this);
      var flyer_loaded = true;
    }
  } else {
    worldbar.load_content(worldbar.config.default_content);
  }

  // Load current day in to Flyer ----------------------------------
  if (!flyer_loaded) {
    var day=new Date();
    short_today = worldbar.helper.day_name(day, true, true);
    $this = $('.' + short_today);
    
    worldbar.load_flyer($this);
  }
  
  // Set initial overlay opacity
  $("#panel_overlay").css({'opacity': '0'});

  // Resize cols on window resize ----------------------------------
  $(window).resize(function() {
    worldbar.helper.pause(function(){
      worldbar.resize_window();
    }, 100);
  });
 
  // Spin panels and load content on panel click -------------------
  $spin_panels.live('click', function(e) {
    if ($(this).hasClass("panel")) {
      var $new_panel = $(this);
      var url = $new_panel.find('a').first().attr('href');
    } else if ($(this).hasClass('flyer_guestlist')) {
      var $new_panel = $('#content a.panel_image[href="' + base_url + 'loader/content/guestlist"]:first').closest('.panel');
      var url = $(this).attr('href');
    } else {
      var $new_panel = $('#content a.panel_image[href="' + $(this).attr('href') + '"]:first').closest('.panel');
      var url = $(this).attr('href');
    }
    
    if (!$(this).hasClass("flipside")) {
      worldbar.helper.spin_back($new_panel);
      
      $new_panel.parent().css('z-index', '40');
      
      worldbar.spin_panel($new_panel);
      
      worldbar.screen_top = $("html").scrollTop();
      $.scrollTo('0px', worldbar.config.scroll_speed, {
        easing: 'swing'
      });
      
      worldbar.load_content(url);
    }
    
    e.preventDefault();
  });
  
  // Load Whats On guide in to content window when flyers in compact mode

  
  // Load content in to window when clicking links -----------------
  $content_url.live('click', function(e) {
    worldbar.overlay('on');
    
    worldbar.screen_top = $("html").scrollTop();
    $.scrollTo('0px',worldbar.config.scroll_speed,{easing:'swing'});
    
    url = $(this).attr('href');
    worldbar.load_content(url);
    
    e.preventDefault();
  });
  
  // Close content window ------------------------------------------
  $content_close.live('click', function(e) {
    worldbar.overlay('off');
        
    var $old_panels = $(".container_panel").find('.panel.flipside');

    if($old_panels.size() > 0) {
      setTimeout(function() {
      $old_panels.each(function() {
        worldbar.spin_panel($(this));
      }); 
      }, 50);
    }
    
    $.scrollTo(worldbar.screen_top+'px', worldbar.config.scroll_speed, {easing:'swing'});
    
    worldbar.helper.expand(0);
    
    worldbar.load_content(worldbar.config.default_content);
    
    $content_close.hide();
  });

  // Expand/Contract flyers window ---------------------------------
  $flyers.mouseover(function() {
      $(this).stop();
      worldbar.flyers_expand($flyers);
    }
  );
  
  $('#logo_banner').mouseover(function() {
      $(this).stop();
      worldbar.flyers_contract($flyers);
    }
  );
  
  // Load flyers in to jCarousel -----------------------------------
  $flyers_menu.click(function(e) {
    worldbar.load_flyer($(this));
    e.preventDefault();
  });
  
  // Like something ------------------------------------------------
  $button_like.each(function(index) {
    url = $(this).parent().find('a').attr('href');
    $(this).addLikeSupport(url);
  });
  
  // ShareThis Panel (Open)
  $button_share.live('click', function(e) {
    $(this).parent().find('.share_options').slideToggle(50);
    e.stopPropagation();
  });
  
  // ShareThis Panel (Close)
  $('.share_options a').live('click', function(e) {
    $(this).closest('.share_options').slideToggle(100);
    if($(this).attr('class') == 'share_close') {
      e.stopImmediatePropagation();
      e.preventDefault();
    } else {
      e.stopImmediatePropagation();
    }
  });
  
  // Show large photo from carousel thumb -------------------------
  $photo_thumbs.live('click', function(e) {
    $image_info = $(this).find('a');
    url = $image_info.attr('href');
    height = $image_info.attr('alt');
    width = $image_info.attr('rel');
    title = ($image_info.attr('title') != 'undefined') ? $image_info.attr('title') : '';
    $('#photo').html('<img src="'+url+'" />');
    $('#content_html .block_link').html(title);
    worldbar.helper.scale_image(width, height);
    e.preventDefault();
  });
  
  // Wildmans signature
  $('a.wildman').click(function(e) {
    $("#panel_wildman").fadeIn("fast");
    e.preventDefault();
  });
  
  $('#panel_wildman').click(function(e) {
    $("#panel_wildman").fadeOut("fast");
    e.preventDefault();
  });
});


