/*
 * Mike Stephens <mike@bitbytebit.co.uk>
 * Grafiky <http://grafiky.co.uk>
 */

 /*****************************************/
 /*               Variables               */
 /*****************************************/

var logoCtx;        // Canvas for logo
var speakerCtx;     // Canvas for speaker
var audioMusic;     // Audio element for music
var audioEffects;   // Audio element for sound effects
var seqenceActive;  // Array to hold the active sequence
var randomActive;   // Stores active random phases
var loadingTimeID;  // Timeout ID for loading event
var latestTweet;    // The latest tweet
var preventKeys     = true; // Prevent users from pressing keys until animation is complete
var keyHistory      = "";

var randomPhrases = {
   '1' : { 'response':'Please note, your visit may be recorded for training purposes.' },
   '2' : { 'response':'Your visit is important to us.' },
   '3' : { 'response':'To speak to an adviser, please stay on the site.' },
   '4' : { 'response':'Please continue to hold, your visit is important to us.' },
   '5' : { 'response':'Please hold...' },
   '6' : { 'response':'Please have your account number to hand. <br />Your account number is located on the top of a non-existent piece of paper.<br />If you do not have an account number please hold.' },
   '7' : { 'response':'Our opening hours are 5:30pm to 9:00am, Monday &mdash; Sunday.' },
   '8' : { 'response':'For all out of hours enquires please visit weareraw.co.uk.' },
   '9' : { 'response':'To speak to a technical advisor please visit bitbytebit.co.uk.' },
   '10' : { 'response':'For general enquiries please email info@grafiky.co.uk.' },
   '11' : { 'response':'For service updates please consult Tom Heaton.' },
   '12' : { 'response':'You are our next caller, please stay on this site.' },
   '13' : { 'response':'Thank you for your patience.' },
   '14' : { 'response':'Your patience will be rewarded shortly.' },
   '15' : { 'response':'We are currently experiencing technical difficulties, please stay on the site.' },
   '16' : { 'response':'This service is only available for touch-tone telephones.' },
   '17' : { 'response':'Did you know... Tom Heaton was 2006 UK national dodge ball quarter-finalist.' },
   '18' : { 'response':'We\'ll be with you in a second.' },
   '19' : { 'response':'To listen to the options again, press zero.' },
   '20' : { 'response':'If you would prefer to hold without music, press the space bar now.' },
   '21' : { 'callback':'showOfficeHours' },
   '22' : { 'callback':'showTweet' },
   '23' : { 'callback':'showTime' }
};

var sequence = {
  'response':'Welcome to Grafiky. If you are under 18 or not a designer/client or potential client, please hang up now.<br /><br />If you would like to see some design, please press 1.<br />If you are looking for Rafiki from the Lion King please press 2.',
  '1' : { 'response':'If you are using Chrome, FireFox, Opera or any half decent browser press 1.<br />If you are using Internet Explorer please press 2.',
          '1' : { 'response':null, 'callback':'showRandomPhrase' },
          '2' : { 'response':'If you have a sense of humour, press 1.<br />If you\'re dead inside press 2.',
                  '1' : { 'response':'Seriously?!... Hell is filled with people like you!' },
                  '2' : { 'response':null, 'callback':'ie6User' }
                }
        },
  '2' : { 'response':null, 'callback':'showRafikiVideo' }
};


/*****************************************/
/*          Sequence Callbacks           */
/*****************************************/

/*
 * Load a the rafiki video from YouTube and display in an overlay
 *
 * @param
 * @return
 */
function showOfficeHours()
{

  var currentTime = new Date();
  var day         = currentTime.getDay();
  var hour        = currentTime.getHours();
  var minute      = currentTime.getMinutes();
  var second      = currentTime.getSeconds();
  
  // Office open all weekend and after 5pm to 9am
  if((day == 7 || day == 0) || (hour >= 17 && hour <= 9))
  {
    return "Our offices are currently open, please contact Tom Heaton.";
  } else {
    return "Our offices are currently closed, for design emergencies please contact weareraw.co.uk."; 
  }

}

/*
 * Displays the current time
 *
 * @param
 * @return string
 */
function showTime()
{

  var currentTime = new Date();
  var hour        = currentTime.getHours();
  var minute      = (currentTime.getMinutes() < 10) ? '0' + currentTime.getMinutes() : currentTime.getMinutes();
  var second      = (currentTime.getSeconds() < 10) ? '0' + currentTime.getSeconds() : currentTime.getSeconds();
  
  return "At the third stroke, the time sponsored by Casio will be " + hour + ":" + minute + ":" + second + ".";
  
}

/*
 * Display the latest tweet
 *
 * @param
 * @return
 */
function showTweet()
{
  return "Did you know Tom Heaton said... &ldquo;" + latestTweet + "&rdquo;.";
}

/*
 * Load a the rafiki video from YouTube and display in an overlay
 *
 * @param
 * @return
 */
function showRafikiVideo()
{

  showOverlay();

  // Add YouTube iFrame to video player
  $("#videoPlayer").html('<iframe width="560" height="349" src="http://www.youtube.com/embed/xRdllxh_c6s?autoplay=1" frameborder="0" allowfullscreen></iframe>');

  // Allow user to click anywhere on overlay to close it
  $('#overlay').attr('title','Click to close').click(function() {
    hideOverlay();
    $("#videoPlayer").html("");
  });

}

/*
 * Redirects IE6 users to IE6Countdown website
 *
 * @param
 * @return
 */
function ie6User()
{
  window.open("http://www.ie6countdown.com/");
}

/*
 * Starts the main phrase loop
 *
 * @param
 * @return
 */
function showRandomPhrase()
{
 
  // Remove sequence
  sequenceActive = null;
  
  // Fade out current response text
  $("#content").fadeOut("slow", function() {
    
    // Display random phrase, wait 2 seconds and then repeat
    $("#content").jLetterByLetter({'text' : "<p>" + getRandomPhrase() + "</p>", 'speed' : '30'}, function() {

      setTimeout(function() {
        showRandomPhrase()
      }, 2000);
    });
    
  });
 
}


/*****************************************/
/*               Functions               */
/*****************************************/

/*
 * Checks to see if mobile user
 *
 * @param
 * @return boolean
 */
function isMobileUser()
{
  
  if(navigator.userAgent.match(/Android/i) || 
     navigator.userAgent.match(/webOS/i) || 
     navigator.userAgent.match(/iPhone/i) || 
     navigator.userAgent.match(/iPod/i))
  {
   return true;
  }
  
  return false;
  
}

/*
 * Preloads the keycode sound files and latest tweet
 *
 * @param
 * @return
 */
 function preLoadResources()
 {
   
   var totalObjects   = 20;
   var currentObjects = 0;

   // Show loading text, loop every 4 seconds until all files have loaded
   $("#content #loading").jLetterByLetter({'text' : "<p>Ring Ring... Ring Ring...</p>", 'speed' : '30'});
   
   loadingTimeID = setInterval(function() {
     $("#content #loading").jLetterByLetter({'text' : "<p>Ring Ring... Ring Ring...</p>", 'speed' : '30'}, function() {

       if(currentObjects == totalObjects)
       {
         clearInterval(loadingTimeID);
         loadingTimeID = 0;
         
         if(isMobileUser())
         {
           // Jump through to main loop for mobile users
           showRandomPhrase();
         } else {
           // Start the initial sequence once loaded sounds
           startSequence();  
         }
       }

     });

   }, 4000);
   
   // Load 0-9 sound clips in mp3 & ogg format
   for(i=0; i<=9; i++)
   {
     $.ajax({ url: 'resources/' + i + '.mp3', complete: function() { currentObjects++; } });
     $.ajax({ url: 'resources/' + i + '.ogg', complete: function() { currentObjects++; } });
   }
   
   // Load latest tweet
   $.getJSON("https://search.twitter.com/search.json?callback=?&q=tom_heaton", function(tweet) {
     latestTweet = (tweet.results[0].text != undefined) ? tweet.results[0].text : '';
   });

 }

/*
 * Init
 */
function init()
{
  
  //
  // Canvas Stuff
  //

  // Ensure browser supports canvas before trying to draw
  if(Modernizr.canvas)
  {

    // Draw logo on canvas
    logoCtx = $("canvas#logo")[0].getContext("2d");
    drawLogo(logoCtx);

    // Draw speaker icon on canvas
    speakerCtx = $("a#speaker canvas")[0].getContext("2d");
    drawSpeaker(speakerCtx, false);

  }


  //
  // Music/Sound Stuff
  //

  // Create cookie to store music state in
  if($.cookie('isMute') == null)
  {
    $.cookie('isMute', false, { expires: 7, path: '/'});
  }

  // Create audio elelemts. One for music, one for sound effects
  if(Modernizr.audio)
  {

    audioMusic   = new Audio();
    audioEffects = new Audio();

    // Load background music
    audioMusic.preload = 'auto';
    audioMusic.src     = Modernizr.audio.mp3 ? 'resources/aveMaria.mp3' :
                         Modernizr.audio.ogg ? 'resources/aveMaria.ogg' : '';
    audioMusic.load();
    audioMusic.play();

  }

  // Handle speaker button with fallback to images
  $("#container header a#speaker").toggle(function() {

    // Change icon
    (Modernizr.canvas) ? drawSpeaker(speakerCtx, true) : "";
    $('img', this).attr('src', 'img/icoSpeakerMute.png');

    (Modernizr.audio) ? audioMusic.pause() : '';

    $.cookie('isMute', true);

  }, function() {

    // Change icon    
    (Modernizr.canvas) ? drawSpeaker(speakerCtx, false) : "";
    $('img', this).attr('src', 'img/icoSpeaker.png');

    (Modernizr.audio) ? audioMusic.play() : '';

    $.cookie('isMute', false);

  });

  // If music is disabled in cookie, click the button
  if($.cookie('isMute') == 'true')
  {
    $("#container header a#speaker").trigger("click");
  }
  
  
  //
  // Main logic for sequences
  //
  
  $(document).keydown(function(e) {
    
    // Check all files have loaded before we allow any actions
    if(loadingTimeID == 0 && preventKeys == false)
    {

      // Get keycode as char
      var keycode = String.fromCharCode(e.keyCode);
      
      // Only store 0-9 chars
      if(keycode >= '0' && keycode <= '9')
      {
        // Store keycode
        keyHistory = keyHistory + keycode;
      
        // Check history for "Egg" aka 344
        if(keyHistory.search(/344/i) != -1)
        {
          window.open("mailto:info@grafiky.co.uk?subject=I'm%20a%20cleaver%20cloggs%20and%20I%20discovered%20your%20easter%20egg");
          keyHistory = "";
        }
      }

      playTone(keycode);

      // Traverse the array and find the associated nested array for the given char
      if(sequenceActive != null && sequenceActive[keycode] != undefined && sequenceActive[keycode] != null)
      {

        // Check to see if we have a response to display or a callback to execute
        if(sequenceActive[keycode].response != null)
        {

          // Prevent users from pressing keys until animation is complete
          preventKeys = true;

          $("#content").fadeOut("slow", function() {

            // Fade in new content
            $(this).wrap("<p></p>").jLetterByLetter({'text' : sequenceActive[keycode].response, 'speed' : '30'}, function() {
              preventKeys = false;
            });

            // Replace the active sequence with the given nested array
            sequenceActive = sequenceActive[keycode];

          });

        } else {

          // No response text, callback specified
          window[sequenceActive[keycode].callback]();

        }

      } else if(keycode == '0') {
        
        // Wait 500ms for the key tone to be played before reloading
        setTimeout(function() {
          window.location.reload(true); 
        }, 500);
        
      } else if(e.keyCode == 32) {
        
        // Space bar can toggle music mute
        $("#container header a#speaker").trigger("click");
        
      }
      
    }

  });

  // Copy the sequence array to the active variable
  sequenceActive = jQuery.extend(true, {}, sequence);
  
  // Copy the random phases to the active variable
  randomActive = jQuery.extend(true, {}, randomPhrases);

}

/*
 * Start the sequence
 *
 */
function startSequence()
{
 
  // Prerequisites done, now display the first sequence response
  $("#content #loading").fadeOut("slow", function() {
    $("#content").jLetterByLetter({'text' : "<p>" + sequenceActive.response + "</p>", 'speed' : '30'}, function() {
      preventKeys = false;
    });
  });
 
}

/*
 * Creates and fades in overlay
 * 
 * @param
 * @return
 */
function showOverlay()
{
  $('body').prepend($("<div id='overlay'>"));
  $('#overlay').css('filter', 'alpha(opacity=70)');
  $('#overlay').css('-ms-filter', 'progid:DXImageTransform.Microsoft.Alpha(Opacity=70)');
  $("#overlay").fadeIn();
}

/*
 * Fades out and removes olverlay
 * 
 * @param
 * @return
 */
function hideOverlay()
{
  $("#overlay").fadeOut(function()
  {
    $("#overlay").remove();
  });
}

/*
 * Returns a random phrase from the randpmPhrases array
 *
 * @param
 * @return string
 */
 function getRandomPhrase()
 {
   
   // Get random phrase from the array above
   rnd = pickRandomElement(randomActive);
   
   // Empty object, repopulate
   if(rnd == undefined)
   {
     randomActive = jQuery.extend(true, {}, randomPhrases);
     return getRandomPhrase();
   }
   
   // Store random item
   var rndItem = randomActive[rnd];
   
   // Remove item from active object
   delete randomActive[rnd];

   // Check to see if we have a response to display or a callback to execute
   if(rndItem != undefined && rndItem.response != null)
   {
     
     // Return random response text
     return rndItem.response;
     
   } else if(rndItem != undefined && rndItem.callback != null) {
     
     // No response text, callback specified
     return window[rndItem.callback]();
     
   }

 }

/*
 * Displays a top banner to IE6 users
 * 
 * @param
 * @return
 */
function showIE6Notice()
{
  if($('html').hasClass("ie6"))
  {
    var notice = "<div id='ie6Notice' style='display: none'><p>This site may not work with your out-dated browser. Please <a href='http://www.ie6countdown.com/' target='_blank'>consider upgrading</a>.</p></div>";
    $("#wrapper").prepend(notice);
    $("#ie6Notice").slideDown();
  }
}

/*
 * Plays a specific sound effect in the effects audio element
 *
 * @param char key
 * @return
 */
function playTone(key)
{

  // Only have sounds for 0 - 9 chars
  if(Modernizr.audio && key >= '0' && key <= '9')
  {
    // Load individual key sound clip
    audioEffects.src   = Modernizr.audio.mp3 ? 'resources/' + key + '.mp3' :
                         Modernizr.audio.ogg ? 'resources/' + key + '.ogg' : '';
    audioEffects.load();
    audioEffects.play();
  }

}

/*
 * Picks a random element from a given object
 *
 * @param Object
 * @return int
 */
function pickRandomElement(obj) {
  
  var result;
  var count = 0;
  
  for (var prop in obj)
  {
    if (Math.random() < 1/++count)
    {
      result = prop;
    }
  }
  
  return result;
  
}

/*
 * Draws the "TOM/MOT" logo on the specified canvas
 *
 * @param canvas
 * @return
 */
function drawLogo(ctx) {

  ctx.save();
  ctx.beginPath();

  ctx.moveTo(99.5, 38.3);
  ctx.lineTo(55.3, 38.3);
  ctx.lineTo(77.4, 0.0);
  ctx.lineTo(22.1, 0.0);
  ctx.lineTo(44.2, 38.3);
  ctx.lineTo(0.0, 38.3);
  ctx.lineTo(27.7, 86.2);
  ctx.lineTo(49.8, 47.9);
  ctx.lineTo(71.9, 86.2);
  ctx.lineTo(99.5, 38.3);
  ctx.closePath();

  ctx.moveTo(27.7, 66.9);
  ctx.lineTo(16.7, 47.9);
  ctx.lineTo(38.7, 47.9);
  ctx.lineTo(27.7, 66.9);
  ctx.closePath();

  ctx.moveTo(60.7, 9.6);
  ctx.lineTo(49.8, 28.7);
  ctx.lineTo(38.8, 9.6);
  ctx.lineTo(60.7, 9.6);
  ctx.closePath();

  ctx.moveTo(82.8, 47.9);
  ctx.lineTo(71.9, 66.9);
  ctx.lineTo(60.9, 47.9);
  ctx.lineTo(82.8, 47.9);
  ctx.closePath();
  ctx.fillStyle = "rgb(1, 1, 2)";
  ctx.fill();
  ctx.restore();

}

/*
 * Draws the "speaker" logo on the specified canvas
 *
 * @param canvas
 * @param boolen - optional cross through line
 * @return
 */
function drawSpeaker(ctx, isMute) {

  // Clear canvas
  ctx.clearRect (0, 0, 32, 28);

  ctx.save();
  ctx.beginPath();
  ctx.moveTo(17.4, 0.0);
  ctx.lineTo(17.4, 24.0);
  ctx.lineTo(11.4, 18.0);
  ctx.lineTo(3.4, 18.0);
  ctx.lineTo(3.4, 6.0);
  ctx.lineTo(11.4, 6.0);
  ctx.lineTo(17.4, 0.0);
  ctx.closePath();
  ctx.fillStyle = "rgb(1, 1, 2)";
  ctx.fill();

  ctx.beginPath();
  ctx.moveTo(26.7, 0.7);
  ctx.lineTo(25.2, 2.1);
  ctx.bezierCurveTo(27.8, 4.7, 29.3, 8.2, 29.3, 12.0);
  ctx.bezierCurveTo(29.3, 15.9, 27.8, 19.3, 25.2, 21.9);
  ctx.lineTo(26.7, 23.3);
  ctx.bezierCurveTo(29.6, 20.4, 31.4, 16.4, 31.4, 12.0);
  ctx.bezierCurveTo(31.4, 7.6, 29.6, 3.6, 26.7, 0.7);
  ctx.closePath();
  ctx.fill();

  ctx.beginPath();
  ctx.moveTo(23.9, 3.5);
  ctx.lineTo(22.5, 5.0);
  ctx.bezierCurveTo(24.3, 6.8, 25.4, 9.3, 25.4, 12.0);
  ctx.bezierCurveTo(25.4, 14.7, 24.3, 17.2, 22.5, 19.0);
  ctx.lineTo(23.9, 20.5);
  ctx.bezierCurveTo(26.0, 18.3, 27.4, 15.3, 27.4, 12.0);
  ctx.bezierCurveTo(27.4, 8.7, 26.0, 5.7, 23.9, 3.5);
  ctx.closePath();
  ctx.fill();

  ctx.beginPath();
  ctx.moveTo(21.1, 6.4);
  ctx.lineTo(19.6, 7.8);
  ctx.bezierCurveTo(20.7, 8.9, 21.4, 10.4, 21.4, 12.0);
  ctx.bezierCurveTo(21.4, 13.6, 20.7, 15.1, 19.6, 16.2);
  ctx.lineTo(21.1, 17.6);
  ctx.bezierCurveTo(22.5, 16.2, 23.4, 14.2, 23.4, 12.0);
  ctx.bezierCurveTo(23.4, 9.8, 22.5, 7.8, 21.1, 6.4);
  ctx.closePath();
  ctx.fill();
  ctx.restore();
  ctx.restore();

  if(isMute)
  {
    // Show line through speaker
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(2.0, 26.0);
    ctx.lineTo(0.0, 24.0);
    ctx.lineTo(24.0, 0.0);
    ctx.lineTo(26.0, 2.0);
    ctx.lineTo(2.0, 26.0);
    ctx.closePath();
    ctx.fill();
    ctx.restore();
  }

}

$(function() {  

  preLoadResources();  
  init();
  showIE6Notice();

});
