
var Made = Made || {};

Made.page_id = null;
Made.page_data = {};

// JSON URLs
//////////////////////////////////////////////////////////////
Made.json_urls = {};
Made.json_urls.page = '/assets/json/page.php';
Made.json_urls.discography = '/assets/json/discography.php';
Made.json_urls.events = '/assets/json/events.php';

// Fade Background
//////////////////////////////////////////////////////////////
Made.fadeBg = function ($obj, url, link, index, callback) {
  var $wrap = $obj.find('#bg_wrapper');  
  
  $obj.addClass('loading');     
  if ( ! $wrap.length) { 
    $obj.prepend('<div id="bg_wrapper">');
    $wrap = $obj.find('#bg_wrapper');         
  }

  $wrap
  .css({'opacity' : 0, 'height' : $obj.innerHeight() })
  
  // append a placeholder image
  // we are doing this to have something
  // to bind a load event to, later we
  // will set a css background preperty,
  // and remove the image
  
  .append('<img src="' + url + '" class="bg_placeholder" />')
    .find('img.bg_placeholder')
    .bind('load', function () {
      
      $('#banner .overlay').remove();
      
      $wrap
      // Set Wraps background as requested images source.
      .css('background', 'url(' + url + ') no-repeat 50% 0')
      // fade background wrapper in
      .animate({
        'opacity' : 1
      }, 500, function () {
        // Remove loading class
        $obj.removeClass('loading');
        
        // tooltip
        var tooltip_text = Made.page_data.media.slides[index].tooltip;
                
        // bind the tooltip
        if( tooltip_text ) {
          var banner_speed = 300;
          
          if( !$('#banner .tooltip').length ) {
            $('#banner').append('<div class="tooltip"><div class="tip"></div><div class="content">' + tooltip_text + '</div></div>');
          } else {
            $('#banner .tooltip .content').html( tooltip_text );
          }

          var $tooltip = $('#banner .tooltip');
          
          // $tooltip.hide();
          
          $('#banner').unbind('mouseenter').unbind('mouseleave').unbind('mousemove');
          
          $tooltip.hide();
          
          $('#banner').css({
            'overflow': 'visible'
          })
          
          $('#banner').bind('mouseenter', function() {
            
            $('#banner').css({
              'zIndex': 3
            });
            
            $tooltip.find('.tip').stop(true,true).show();
            $tooltip
              /*
              .fadeTo(banner_speed,1,function() {
                $tooltip.css('overflow','visible');
              })
              */
              .show()
              .fadeTo( banner_speed, 1 )
              .addClass('bottom')
              .css('overflow', 'visible');
            
          }).bind('mouseleave', function() {

            $tooltip.fadeTo(banner_speed,0,function() {
              $tooltip.css('overflow','visible');
              $tooltip.find('.tip').hide();
              $tooltip.hide();
              
              $('#banner').css({
                'zIndex': 1
              });
            });
            
          }).bind('mousemove', function(e) {
            var top = ( e.pageY - $(this).offset().top );
            var left = ( e.pageX - $(this).offset().left );
            
            $tooltip.find('.tip').show();  
            $tooltip.show().css({
              'top': Made.misc.in_range( top+30, 90+80, 520 ),
              'left': Made.misc.in_range( left, 0, 960 ) - 30
            });

            var offset = 10;
            var marginLeft = ($tooltip.outerWidth()-(offset*3.5)) * (left/960);

            $tooltip
              .addClass('bottom')
              .css({
                'marginTop': -1 * ( $tooltip.outerHeight() + 45 ),
                'marginLeft': -1 * marginLeft
              });
            
            $tooltip
              .find('.tip')
              .css({
                'left': offset + marginLeft
              });
            
          })
        } else {
        
          $('#banner .tooltip').fadeTo(300,0).remove();
          
        }
        
        // fire callback function if set
        if (callback) {
          callback();      
        }
        // fade in play bu if needed
        if ($('#video_player .play').length) {
          $('#video_player .play').animate({
            opacity : 1
          }, 250);
        } else {
                
          // Link
          if( link != '' && typeof link != 'undefined' ) {
            $('#banner').append('<a href="' + link + '" class="overlay"></a>');
          }
        
        }
      })
        // Remove placeholder image
       .find('img.bg_placeholder')
       .remove(); 
    }); 
};

// Page Background
//////////////////////////////////////////////////////////////
Made.pageBg = function ($obj) {
  this.len = Made.page_data.media.slides.length;
  this.curSlideIndex = 0;
  this.slideObj = $obj;
  this.trigObj = $('#bg_page_control a');
  
  var that = this,
      nextImage = function () {
        var dir = $(this).attr('class'),          
            index = (dir === 'next') ?  that.curSlideIndex + 1 : that.curSlideIndex - 1;
        // Last or First ?
        if (index === that.len) {
          index = 0;
        } else if (index < 0) {
          index = (that.len - 1);
        }
        // Reset Index
        that.curSlideIndex = index;
        // Prevent Overfire
        that.trigObj.unbind('click').click(function () { return false; });
        //  Fade In Next Image
        Made.fadeBg($obj, Made.page_data.media.slides[index].src, Made.page_data.media.slides[index].link, index, function () {
          // Reset Event
          that.trigObj.bind('click', nextImage);
        });
        return false;
      };
  // Bind Clicks
  this.trigObj.bind('click', nextImage);
};

// Add Player
//////////////////////////////////////////////////////////////////////////////
Made.addBannerPlayer = function ($obj){
  var bannerPlayer;
  $obj.prepend(Made.templates.player());

  $('#video_player .play').css('opacity', 0).bind('click', function () {
    $(this).animate({
      'opacity' : 0
    }, 250, function () {
      bannerPlayer = new Made.Player('video_player', Made.page_data.media.vim_id, 'video_player', 960, 488, null);
    });
    return false;
  });
};

// Video Player
//////////////////////////////////////////////////////////////////////////////
Made.Player = function(elem, vid_id, swf_id, vidY, vidX, autoplay) {
  this.elem = elem;
  this.vid_id = vid_id;
  this.swf_id = swf_id;
  this.vidY = vidY;
  this.vidX = vidX;
  this.autoplay = autoplay;
  var that = this;
  that.build();
};

Made.Player.vimeo_player_loaded = function (swf_id) {
  var _player = document.getElementById(swf_id);
  _player.api_addEventListener('onPlay', 'Made.Player.vimeo_on_play');
  _player.api_addEventListener('onPause', 'Made.Player.vimeo_on_pause');
  _player.api_setVolume(80);
  _player.api_play();    
};

Made.Player.vimeo_on_play = function () {
  $('#bg_wrapper').animate({
     opacity : 0.25
  }, 400);
  $('.subscribe-tab').hide();
};

Made.Player.vimeo_on_pause = function () {
  $('#bg_wrapper').animate({
     opacity : 1
  });
};

Made.Player.prototype.play = function() {
  var _player = document.getElementById(this.swf_id);
  if(_player) {
    _player.api_play();
  }
  
};

Made.Player.prototype.pause = function () {
  var _player = document.getElementById(this.swf_id);
  if(_player) {
    _player.api_pause();
  }
};

Made.Player.prototype.stop = function() {
  var _player = document.getElementById(this.swf_id);
  if(_player) {
    _player.api_seekTo(0);
    _player.api_pause();
  }
};

Made.Player.prototype.setVol = function(level) {
  var _player = document.getElementById(this.swf_id);
  if(_player) {
    _player.api_setVolume(level);
  }
};

Made.Player.prototype.build = function() {

  var flashvars = {
        clip_id : this.vid_id,
        server : 'vimeo.com',
        color : Made.page_data.color,
        show_title : 0,
        show_byline : 0,
        show_portrait : 0,
        fullscreen : 1,
        js_api : 1,
        js_onLoad : 'Made.Player.vimeo_player_loaded',
        js_swf_id:  this.swf_id
      }, 
      params = {
        'allowscriptaccess': 'always',
        'allowfullscreen': true,
        'wmode' : 'transparent'
      },
      attributes = {
        'id' : this.swf_id,
        'bgcolor' : '#000000'
      };

  swfobject.embedSWF("http://www.vimeo.com/moogaloop.swf", this.elem, this.vidY, this.vidX, "9.0.28", '', flashvars, params, attributes);

};

// Ajax Module
//////////////////////////////////////////////////////////////
Made.AjaxModule = function (elem, module) {
  this.elem = elem;
  this.module = module;
  this.template = Made.templates[this.module];
  this.data = Made.page_data[this.module];

  var that = this;
  return (function () {
    var $obj = $(that.elem),
        $trig = $obj.find('.more'),
        skip = $obj.find('article').length;
  
    $trig.bind('click', function () {
      $(this).animate({
        'height' : 0
      }, 300, function () {
        that.addItems(skip); 
      });
      return false;
    });  
  } () );
};

Made.AjaxModule.prototype.addItems = function (skip) {
  var i = skip;
  for (i; i < this.data.length; i++) {
    var $elem = $(this.elem)
                  .append(this.template(this.data[i]))
                  .find('article:eq(' + i + ')');

    var height = $elem.height();
    $elem.height(0).css('overflow','hidden');
    $elem.delay((i-skip)*300).animate({'height':height});
    
  }
  $(this.elem).find('article:even').addClass('alt');
};

// Templates
//////////////////////////////////////////////////////////////
Made.templates = {};
//  Discography Module
Made.templates.discography = function (item) {
  var html = '';

  html += '<article class="">';
   html += '<div class="inside">';
      html += '<header>';
        html += '<h1><a href="' + item.url + '">' + item.title + '</a></h1>';
      html += '</header>';
      
      html += '<p>';
        html += 'Buy:';
         html += '<a href="' + item.itunes + '">iTunes</a>, ';
         html += '<a href="' + item.amazon + '">Amazon</a>';
      html += '</p>';
    html += '</div>';
  html += '</article>';
  
  return html;
};
// Events Module
Made.templates.events = function (item) {
  var html = '';
  
  html += '<article class="">';
    html += '<div class="inside clearfix">';
      html += '<header>';
        html += '<h1>' + item.title + '</h1>';
      html += '</header>';
  
      html += '<dl>';
        html += '<dt>Place</dt>';
        html += '<dd><a href="' + item.place_url + '">' + item.place + '</a></dd>';
        
        html += '<dt>Date</dt>';
        html += '<dd>' + item.date + '</dd>';
        
        html += '<dt>Time</dt>';
        html += '<dd>' + item.time + '</dd>';
      html += '</dl>';
    html += '</div>';
  html += '</article>';
  
  return html;
};
// Pager Module
Made.templates.bgPager = function () {
  var html = '';
  
  html += '<div id="bg_page_control">';
    html += '<a href="#" class="prev">Previous</a>';            
    html += '<a href="#" class="next">Next</a>';            
  html += '</div>';
  
  return html;
};
// Player
Made.templates.player = function () {
  var html = '';
  html += '<div id="video_player"><a href="#" class="play">Play</a></div>';
  return html;
};
// Models
//////////////////////////////////////////////////////////////
Made.models = {};
Made.models.page = function (controller) {
  $.ajax({
    url : Made.json_urls.page,
    dataType : 'json',
    data : {
      id : Made.page_id
    },
    success: function (data) {
      // Set page data
      Made.page_data = data;    
      // Pass data to controller
      // for dispatch
      controller( Made.page_data );
    }
  });
};
// Controllers
//////////////////////////////////////////////////////////////
Made.controllers = {};
Made.controllers.page = function (data) {

  if ( data.media.slides ) {
    Made.fadeBg( $('body'), data.media.slides[0].src, data.media.slides[0].link, 0 );
  }
  
  // Do We Need a PLayer ? 
  if (data.media.vim_id) {
    Made.addBannerPlayer($('#banner'));
  }
  // Do We Need a Slideshow 
  if (data.media.slides && data.media.slides.length > 1) {
    $('.psuedoBody').prepend( Made.templates.bgPager() );
    Made.pageBg($('body'));
    
    // The 'autoplay' feature.
    if ($('#auto').length){
      setInterval(function() {
        $('#bg_page_control a.next').trigger('click');
      }, 5000);
    }

  }
  // Do we need an Events Module
  if (data.events) {
    var eventsModule = new Made.AjaxModule('#events_module', 'events');
  }
  // Do we need a Discography Module
  if (data.discography) {
    var discoModule = new Made.AjaxModule('#discography_module', 'discography');
  }
  // Do We need a Player Module
  if (data.playlist) {
    var madePlayer;
    madePlayer = new MusicPlayer('player_audio', {
       playlist : data.playlist
    });
    madePlayer.init();
    
    
    $('#player ul li').bind('click', function(e) {
	
			e.preventDefault();
			
      var $e = $(e.target);
      
      if( !$e.is('a') ) {
        var $li = ( $e.is('li') ? $e : $e.parents('li').eq(0) );
        
        if( $li.hasClass('playing') ) {
          $li.find('.pause').trigger('click');
        } else {
          $li.find('.play').trigger('click');
        }
      }
    });
    
    $('#player ul li .track_info a')
      .bind('mouseenter', function() {
        var $li = $(this).parents('li');
        
        $li.addClass('no-hover')
      })
      .bind('mouseleave', function() {
        var $li = $(this).parents('li');
        
        $li.removeClass('no-hover')
      });
  }

};
// Initialization
//////////////////////////////////////////////////////////////
Made.init = function (section) {
  Made.models[ section ]( Made.controllers[ section ] );
};
// Block Links
//////////////////////////////////////////////////////////////
Made.blockLink = function( selector, link_selector ) {
  $(selector).css({'cursor':'pointer'}).each(function() {
    $(this).bind('click', function(e) {
      e.preventDefault();
      window.location.href = $(this).find(link_selector).attr('href');
    });
  });
};
// Check if the link is External
//////////////////////////////////////////////////////////////
Made._URLroots = ['made.verbsite.com','localhost:9999'];
Made.isExternalLink = function(link) {
	// check if local
	var local = false;
	// check if roots match
	for( var i = 0; i<Made._URLroots.length; i++ ){
		rootURL = new RegExp(Made._URLroots[i]);
		
		if( rootURL.test( link ) ) {
			local = true;
		}
	}
	// if "/store"
	if( link.substr(0,1) == '/' ) {
		local = true;
	}
  // seems like it failed.
	if( !local ) {
		return true;
	}
	return false;
};
// Misc.
//////////////////////////////////////////////////////////////
Made.misc = {};
Made.misc.in_range = function( input, min, max ) {
  if( input <= min ) { return min; }
  if( input >= max ) { return max; }
  return input;
};
// Document
//////////////////////////////////////////////////////////////
$(document).ready(function () {
  Made.init('page');
  // Facebox
  $('a[rel*=lightbox]').each(function () {
    var url = $(this).attr('href');
    $(this).facebox({
      ajax : url
    });
  });
  // Set the externals
  $('a[rel*=external]').click(function(){
   window.open(this.href);
   return false;
  });
  // Block links
  Made.blockLink( '#posts article', 'header h1 a' );
  Made.blockLink( '#listing article', 'header a:first' );  
  
  if($('#twitterPost').length){    
    user = $('#twitterPost').attr('class');
    $("#twitterPost").tweet({
        username: user,
        count: 1,
        loading_text: "loading..."
    });
  }
  
});
// Test
//////////////////////////////////////////////////////////////
if( $.browser.msie ) {
  document.execCommand("BackgroundImageCache",false,true);
}
