/* -------------------------------------------------------------- 
a17.ui.loader.js 
kol a17 js
Copyright 2009 Nobleskine @ AREA 17 

Lightweight js loader. 
- Should be the only javascript file put at the bottom of the page (in addition to the main js framework such as jQuery).
- Use it to dynamically load "user interaction" oriented javascript.
- Don't use it for "css-fix" oriented javascript (to avoid any css jump) unless for progressive enhancement.
	
-------------------------------------------------------------- */

/*
* jQuery.use - The jQuery plugin manager
* http://github.com/aheckmann/jQuery.use
* Copyright (c) 2009 Aaron Heckmann
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
(function(e,n){var B={},d={LOADED:3,LOADING:2,UNLOADED:1},x="1.0.0",C=false,v=false,o=false,E=document,t={},z=E.getElementsByTagName("head")[0]||E.documentElement,F=E.createElement("div"),j="*",w="ui-lightness",r=false,u=n.toString,A=function(H,M,K){if(e.use.lib_root===false){throw"jQuery.use.lib_root has not been set. Please set this to your libray's root before continuing."}if(e.use.service&&e.use.serviceURI===false){throw"jQuery.use.serviceURI has not been set."}D();var L=h(y(H)),G=0,p=function(){if(++G===2&&M){setTimeout(function(){if(!m(L.provides)){return setTimeout(arguments.callee,30)}M.call(K||window,jQuery);a(L.preload)},30)}};if(0===L.js.length+L.css.length){M&&M();return}function I(N){return N.isPkg&&(N.url.indexOf("http")==-1||N.url.indexOf(v)===0)}function J(W,U,O){var R=W.length,T,N,P="",X=[],V=e.use.service&&!O,S=f(),Q=100;if(R===0){p();return}T=W.splice(0,1)[0];N=c(T.url.toLowerCase(),I(T),!V);if(t.hasOwnProperty(N)){if(t[N].status===d.LOADING){t[N].queue.push(function(){J(W,U,O)})}else{J(W,U,O)}}else{while(V&&I(T)){P+="d"+(Q++)+"="+T.url+"&";N=c(T.url.toLowerCase(),true);t[N]={status:d.LOADING,queue:[]};X[X.length]=N;T=W.length&&I(W[0])&&W.splice(0,1)[0]}if(P.length>0){P=P.substring(0,P.length-1);U(S+P,function(){for(var Z=0,Y=X.length;Z<Y;Z++){b(X[Z])}J(W,U,O)})}else{U(N,function(){J(W,U,O)})}}}J(L.css,k,!e.use.combineCSS);J(L.js,l);return jQuery},a=function(p){if(p.length){setTimeout(function(){for(var I=0,H=p.length,G=e.use.lib_root;I<H;I++){(new Image()).src=G+p[I]}},1)}},m=function(M){var K=true,H=0,p=M.length,L,J,I,G;while(K&&H<p){L=M[H].split(".");J=L.length;I=window;G=0;for(;G<J;G++){if(!(L[G] in I)){K=false;break}I=I[L[G]]}H++}return K},k=function(H,p){t[H]={status:d.LOADING,queue:[]};var G=E.createElement("link");G.type="text/css";G.rel="stylesheet";G.href=H;G.media="screen";z.appendChild(G);b(H,p)},l=function(G,p){t[G]={status:d.LOADING,queue:[]};e.ajax({type:"GET",url:G,cache:true,dataType:"script",success:function(){b(G,p)}})},b=function(K,G){var I=t[K],J=I.queue,p=J.length,H=0;I.status=d.LOADED;G&&G();for(;H<p;H++){J[H]()}I.queue=[]},f=function(){var p=e.use.serviceURI||"";return p+(p.indexOf("?")>-1?"&":"?")},y=function(R,G){var Q,M,L=[],p=[],S=[],H=/\.css/i,K=0,T,J,O=[],P=[],N=!!G,I=e.use.uiTheme;if(u.call(R)==="[object Array]"){Q=R}else{if(B.hasOwnProperty(R)){Q=(B[R].requires||[]).concat(B[R].file||[]);P=B[R].provides||[];S=B[R].preload||[];N=true}else{Q=[R]}}for(M=Q.length;K<M;K++){J=Q[K];if(""===J){continue}if(B.hasOwnProperty(J)){T=y(J,N);p=p.concat(T.js);L=L.concat(T.css);P=P.concat(T.provides);S=S.concat(T.preload)}else{if(H.test(J)){L.push({url:J.replace("{THEME}",I),isPkg:N})}else{p.push({url:J,isPkg:N})}}}return{js:p,css:L,provides:P,preload:S}},h=function(p){p.js=q(p.js);p.css=q(p.css);p.preload=q(p.preload);return p},q=function(K){var J=0,p=K.length,G={},H=[],L,I;for(;J<p;J++){L=K[J];I=L.url?L.url:L;if(!G[I]){G[I]=1;H[H.length]=L}}return H},D=function(){var H=s(),G=H.length+1,p;while(--G){p=H[G-1].toLowerCase();if(!t.hasOwnProperty(p)){t[p]={status:d.LOADED}}}return t},c=function(G,H,p){if(H){return(p?e.use.lib_root:j)+G}F.innerHTML='<a href="'+G+'"></a>';return F.firstChild.href},s=function(){var G=new RegExp(f().replace("?","\\?"),"i"),p=function(H){var I=c,J=e.use.service;return function(){if(J&&G.test(this[H])){return(j+this[H].replace(G,"").split("&").join("&"+j)).split("&")}return I(this[H])}};return e("script[src]").map(p("src")).get().concat(e("link[href][type=text/css]").map(p("href")).get())},g=function(G,I){if(!G){return e}if(u.call(G)==="[object Array]"){for(var H=0,p=G.length;H<p;H++){g(G[H],I)}return e}if(B.hasOwnProperty(G.name)&&!I){throw"Package name already taken."}if(G.file){G.file=e.makeArray(G.file)}if(G.requires){G.requires=e.makeArray(G.requires)}if(G.provides){G.provides=e.makeArray(G.provides)}B[G.name]=G;delete B[G.name].name;return e},i=function(p){return p?B[p]:B};e.use=A;e.use.add=g;e.use.modules=i;e.use.VERSION=x;e.use.combineCSS=r;e.use.uiTheme=w;e.use.serviceURI=v;e.use.service=o;e.use.lib_root=C})(jQuery,Object.prototype);

$.use.lib_root = ""; // NOT WORKING !?
// This can be a fully qualified domain, or an absolute path. Omit trailing slash.
var assets_root = '/assets';

/* -------------------------------------------------------------- 
ON DOM READY
-------------------------------------------------------------- */
$(document).ready(function(){
  // Site-wide common functions
	sound_effects_user_preference();
	mod_questions();
	placeholder_text();
	handle_stocks_form_validation();
	handle_character_icon_selection();
	handle_closing_alert_messages();
	warrenism_generator();
	no_thanks_to_signup();
	set_current_navigation_tab();
	
	navigation_sound_effects();
	skin_select_menus();
	validate_user_age();
	
	
	// Page/module level specific calls
	// Example for the blog page
	// Usage #1 : all javascript related to the blog page should be defined in a blog() function defined below.
	// Usage #2 : define blog() in an external blog.js and use the jQuery.use() plugin to asynchronously load it when needed and/or load other js librairies it would require.
	// Notes : in general, go for usage #1. If blog() becomes complex and relies on various plugins very specific to blog, thus unecessary to the site in general, then go for Usage #2.
});

/* -------------------------------------------------------------- 
HANDLE THE "NO THANKS" BUTTON
The user can choose to refuse opening an account. If so, we hide
the signup and login forms, and remember that choice in a cookie.
-------------------------------------------------------------- */
function no_thanks_to_signup() {
  if ($('#smcWelcome_close').length === 0) return false;
  
  jQuery.use(assets_root+'/js/ext/jquery.cookies.2.2.0.min.js', function ($) {
    $('#smcWelcome_close').click(function(ev){
      // Animation
      $('.smcWelcome_header').slideUp('fast');
      $('.smcWelcome_content').slideUp('fast', function(){
        $('#smcWelcome').removeClass('expanded');
      });
    
      // Cookie handling
      var expires = new Date();
      var days_until_expiration = 30;
      expires.setTime(expires.getTime() + (days_until_expiration *24*60*60*1000));
      $.cookies.set('portfolioNoThanks', '1', {expiresAt: expires});
    
      ev.preventDefault();
    });
  });
}

/* -------------------------------------------------------------- 
SET WHICH TOP NAVIGATION TAB IS CURRENTLY SELECTED
This is handled in JS because of a limitation of the CMS.
Expects a global variable "current_smc_section" holding the name
('home', 'portfolio', 'episodes', 'characters', etc).
-------------------------------------------------------------- */
function set_current_navigation_tab() {
  if ($('#GH_nav_'+current_smc_section).length === 0) return false;
  $('#GH_nav li').removeClass('current'); // Just in case there's one left behind.
  $('#GH_nav_'+current_smc_section).addClass('current');
}

/* -------------------------------------------------------------- 
MOD QUESTIONS FUNCTIONS 
-------------------------------------------------------------- */
function mod_questions() {
	if ($('.post_thequestion').length === 0) return false;
	
  // Setup: only show the first answer, the others are collapsed.
  $('.post_thequestion:gt(0)').next().hide();
  $('.post_thequestion:first').parents('li').addClass('expanded');
  
  var previously_animated = $('.post_thequestion:first');
	$('.post_thequestion').click(function(e) {
		if (previously_animated != undefined && !$(this).parents('li').hasClass('expanded')){
	    $(this).next().slideDown('fast');
	    $(previously_animated).next().slideUp('fast');
		  $(this).parents('ul').find('li').removeClass('expanded');
		  $(this).parents('li').addClass('expanded');
		}
		previously_animated = $(this);
	});
	
}

/* -------------------------------------------------------------- 
PLACEHOLDER TEXT FOR TEXT INPUTS (SEARCH, LOGIN…)
-------------------------------------------------------------- */
function placeholder_text() {
  $('input[placeholder]').each(function(){
    $(this).attr('value', $(this).attr('placeholder')).addClass('has_placeholder_text');
  }).focus(function(){
    el = $(this);
    if (el.attr('value') === el.attr('placeholder')) {
      el.attr('value', '').removeClass('has_placeholder_text');
    }
  }).blur(function(){
    el = $(this);
    if (el.attr('value') == '' || el.attr('value') === el.attr('placeholder')) {
      el.attr('value', el.attr('placeholder')).addClass('has_placeholder_text');
    }
  })
}

/* -------------------------------------------------------------- 
NAVIGATION BAR SOUND EFFECTS
-------------------------------------------------------------- */
function navigation_sound_effects() {
  window.SM2_DEFER = true;
  //jQuery.use(assets_root+'/js/ext/soundmanager2.js', function ($) {
  jQuery.use(assets_root+'/js/ext/soundmanager2-nodebug-jsmin.js', function ($) {
    window.soundManager = new SoundManager(); // Flash expects window.soundManager.
    soundManager.beginDelayedInit();
    soundManager.flashVersion = 9;
    soundManager.url = assets_root+'/swf/';
    soundManager.onready(function() {
      if (soundManager.supported()) {
        // SM2 is ready to go!
        soundManager.createSound({
          id: 'martian',
          url: assets_root+'/audio/martian.mp3',
          autoLoad: true,
          autoPlay: false,
          volume: 50,
          onload: function() {
            // Attach the sound effect to the menu elements.
            $('#GH_nav :not(.current) a').mouseover(function(){
              if (smc_sound_effects_user_preference == 'on') {
                soundManager.getSoundById('martian').play();
              }
            })
          }
        });
        character_page_sound_effect();
      } else {
        //console.log('sound manager could not be loaded');
      }
    });
  });
}

/* -------------------------------------------------------------- 
SOUND EFFECT ON ROLL OVER OF THE BIG CHARACTER IMAGE
Called from within the navigation_sound_effects function,
to only intanciate one SoundManager.
-------------------------------------------------------------- */
function character_page_sound_effect() {
  if ($('#big_character_image').length === 0) return false;
  // We rely on the SoundManager instanciated for the navigation buttons.
  soundManager.createSound({
    id: 'big_character_image',
    url: assets_root+'/audio/'+$('#big_character_image').attr('data-character-name')+'_line.mp3',
    autoLoad: true,
    autoPlay: false,
    multiShot: false,
    volume: 50,
    onload: function() {
      $('#big_character_image').mouseover(function(){
        if (smc_sound_effects_user_preference == 'on') {
          soundManager.getSoundById('big_character_image').play();
        }
      })
    }
  });
}

/* -------------------------------------------------------------- 
STOCKS FORM VALIDATION (can't spend more BBucks than you have!)
-------------------------------------------------------------- */
function handle_stocks_form_validation(){
  if ($('#stocks-form').length === 0) return false;
  if ($('.smcWelcome_footer_message span[data-cash-total]').length === 0) return false;
  
  // Only enable the Buy button if there's a checked stock.
  $('.icon_buy').attr('disabled', true).addClass('disabled');
  $('#stocks-form :checkbox').each(function(check){
    if ($(this).attr('checked')) $('.icon_buy').attr('disabled', false).removeClass('disabled');
  });
  
  $('#stocks-form .mod_stocks_line').not('.stock_bought').find(':checkbox').bind('change', validate_stocks_form);
  $('#stocks-form .icon_cancel').click(function(){
    $('#displayed_total').html('$0.00');
    $('.icon_buy').attr('disabled', true).addClass('disabled');
    if ($('.mod_footer_alert').length >= 1)
      $('.mod_footer_alert').slideUp('fast');
  });
}
// Check if the user has enough BBucks to buy the stock he just checked.
// If not, display a pretty error message.
function validate_stocks_form() {
  var available_bbucks = parseFloat($('.smcWelcome_footer_message span[data-cash-total]').attr('data-cash-total'), 10);
  var total_bbucks = calculate_stocks_total_amount();
  
  $('#displayed_total').html('$'+total_bbucks.toFixed(2));
  if (available_bbucks < total_bbucks) {
    $('#stocks-form').addClass('error');
    if ($('.mod_footer_alert').length === 0) {
      $('.mod_footer').append('<div class="mod_footer_alert" style="display:none">Oops, you only have $'+available_bbucks.toFixed(2)+' BBucks</div>');
    }
    $('.mod_footer_alert').slideDown('fast');
    $('.icon_buy').attr('disabled', true).addClass('disabled')
  } else {
    $('#stocks-form').addClass('checked');
    $('#stocks-form').removeClass('error');
    if ($('.mod_footer_alert').length >= 1) {
      $('.mod_footer_alert').slideUp('fast');
    }
    // Only enable the Buy button if there's a checked stock.
    $('.icon_buy').attr('disabled', true).addClass('disabled');
    $('#stocks-form :checkbox').each(function(check){
      if ($(this).attr('checked')) $('.icon_buy').attr('disabled', false).removeClass('disabled');
    });
  }
}
function calculate_stocks_total_amount() {
  var the_total = 0.0;
  $('.mod_stocks_col_checkbox input:checked').each(function(){
    the_total += parseFloat($(this).parent().siblings('.mod_stocks_col_value').attr('data-value'), 10);
  })
  return the_total;
}

/* -------------------------------------------------------------- 
SKIN SELECT MENUS
-------------------------------------------------------------- */
function skin_select_menus(){
  if ($('select').length === 0) return false;
  
  jQuery.use(assets_root+'/js/ext/jquery.uniform.min.js', function ($) {
    $('.input_select select').uniform();
  });
}

/* -------------------------------------------------------------- 
HANDLE THE "PICK A CHARACTER" FUNCTIONALITY, AFTER REGISTRATION.
-------------------------------------------------------------- */
function handle_character_icon_selection(){
  if ($('form.mod_myportfolio_intro').length === 0) return false;
  
  // FIXME: Branch off for IE6.
  //if ($('html').hasClass('ie6')) { handle_character_icon_selection_ie6(); return false; }
  
  $('.mod_myportfolio_intro .mod_content a').click(function(e){
    $(this).parents('ul').find('.ch').removeClass('selected');
    $(this).parents('li').find('.ch').addClass('selected');
    if ($(this).hasClass('thumbs_title')) {
      $('#chosen_character_name').attr('value', $(this).html());
    } else {
      $('#chosen_character_name').attr('value', $(this).parents('li').find('a.thumbs_title').html());
    }
    e.preventDefault();
  })
}

/* -------------------------------------------------------------- 
HANDLE THE 'CLOSE' BUTTON FOR ALERT MESSAGES
-------------------------------------------------------------- */
function handle_closing_alert_messages(){
  $('.smcWelcome_footer_message_alert .icon_close').click(function(ev){
    ev.preventDefault();
    $(this).parents('.smcWelcome_footer_message_alert').fadeOut('fast', function() {
      $(this).remove();
    })
  })
}

/* -------------------------------------------------------------- 
DISPLAY AN ALERT MESSAGE AT THE TOP OF THE WINDOW
-------------------------------------------------------------- */
function display_alert_message(msg){
  var close_icon_html = '<a href="" class="icon icon_close green_bg">X</a> ';
  if ($('.smcWelcome_footer').length === 0) return false;
  if ($('.smcWelcome_footer_message_alert').length > 0) {
    $('.smcWelcome_footer_message_alert').html(close_icon_html + msg);
  } else {
    var alert_box = $('<div >').addClass('smcWelcome_footer_message smcWelcome_footer_message_alert');
    // HTML Source order is important, must display the alert after the standard message.
    $('.smcWelcome_footer_message').first().after(alert_box.html(close_icon_html + msg));
  }
  handle_closing_alert_messages();
}

/* -------------------------------------------------------------- 
XHR CALL TO INCREMENT THE USER'S POINTS, GAINED BY PARTICIPATION
Parameters
  itemType: 'video' or 'game'
  itemId: some unique identifier
  
Expects from JSON
  status: 'ok' | 'error'
  error_msg: string ; not displayed to user 
  amount_earned: the amount of BBucks the user just earned
  total_bbucks: the total amount of BBucks the user has.
-------------------------------------------------------------- */
function register_site_participation(itemType, itemId){
  $.getJSON("/smc/stocks/earnbbucks.jsp", {'itemType': itemType, 'itemId': itemId}, function(data){
    if (data.status === 'ok') {
      display_alert_message("You just earned $"+data.amount_earned+" Buffet Bucks");
      // Update the Cash Total amount.
      var portfolio_total = $('.smcWelcome_footer_message span[data-cash-total]');
      if (portfolio_total.length > 0) {
        portfolio_total.attr('data-cash-total', data.total_bbucks);
        //portfolio_total.html(portfolio_total.html().replace(/\d+/, data.total_bbucks)); // Disabled because number formatting is uncertain.
      }
    } else {
      // No error handling.
    }
  })
}

/* -------------------------------------------------------------- 
WARRENISM GENERATOR, PICK A RANDOM ANSWER FROM A SET.
-------------------------------------------------------------- */
function warrenism_generator(){
  if ($('#warrenism_form').length === 0) return false;
  
  var warrenism_state = 'default';
  $('#warrenism_form').submit(function(ev){
    ev.preventDefault();
    var answers_array = $('#anwser_set li').map(function(idx, el){ return $(el).text() }).get();
    var random_num = Math.ceil(Math.random() * (answers_array.length));
    $('.warrenism_image').css({backgroundPosition: '0px -144px'});
    $('#warrenism_form .field_holder').hide();
    $('#answer_given').html( answers_array[random_num-1] );
    $('#warrenism_form .icon.submit').removeClass('icon_showme').addClass('icon_showmore');
  })
}

/* -------------------------------------------------------------- 
Toggle sounds effects on/off, and remember the user's choice.
-------------------------------------------------------------- */
var smc_sound_effects_user_preference;
function sound_effects_user_preference() {
  // Set up the default state (effects on).
  $('#GH_soundeffectsoff').hide();
  smc_sound_effects_user_preference = 'on';
  
  // Override the default state with a user-chosen preference.
  jQuery.use(assets_root+'/js/ext/jquery.cookies.2.2.0.min.js', function ($) {
    if ($.cookies.get('smc_soundeffects')) {
      // User has explicitly changed state.
      if ($.cookies.get('smc_soundeffects') == 'off') {
        $('#GH_soundeffectson').hide();
        $('#GH_soundeffectsoff').show();
        smc_sound_effects_user_preference = 'off';
      }
      if ($.cookies.get('smc_soundeffects') == 'on') {
        $('#GH_soundeffectsoff').hide();
        $('#GH_soundeffectson').show();
        smc_sound_effects_user_preference = 'on';
      }
    }
  });
  
  // Handle the toggle UI between the two states.
  $('#GH_soundeffectson').click(function(ev){
    ev.preventDefault();
    $(this).hide();
    $('#GH_soundeffectsoff').show();
    soundManager.stopAll(); // Interrupt any currently playing sound.
    $.cookies.set('smc_soundeffects', 'off');
    smc_sound_effects_user_preference = 'off';
  });
  $('#GH_soundeffectsoff').click(function(ev){
    ev.preventDefault();
    $(this).hide();
    $('#GH_soundeffectson').show();
    $.cookies.set('smc_soundeffects', 'on');
    smc_sound_effects_user_preference = 'on';
  })
}

/* -------------------------------------------------------------- 
Emulation of <input type="number">
-------------------------------------------------------------- */
function validate_user_age() {
  if ($('#comment_userage').length === 0) return false;
  $('#comment_userage').keyup(function(ev){
    $(this).attr('value', $(this).attr('value').replace(/[^0-9]/, ''));
  });
}

/* -------------------------------------------------------------- 
INTERNAL : ONLY FOR DEMO PURPOSE  
-------------------------------------------------------------- */
function demo(trigger) {
	if (trigger) {
		$('#container').after('<div id="demo" style="position:absolute;top:0;right:0;font-size:10px"></div');

		$("#demo").load('demo.html',
			function(responseText, textStatus, XMLHttpRequest) {
				
				var loc = window.location.href;
				
				$("#a17nav option").each(function() {
					var val = $(this).attr('value');
					if (loc.indexOf(val) != -1) {
						$(this).attr('selected', 'selected');
					}
					
				});
				
				$('#a17nav').change(function() {
					var URL = $('#a17nav option:selected').attr('value');
					if (URL != '' && URL != '#' && URL !='undefined')
						window.location.href = URL;
				});
			}
		);
	} 
}

