$(document).ready(function() {
  $("#navigation").animateNavigation();
  $("#news-ticker").newsticker("slide");  
  /*$('a[@rel*=lightbox]').lightBox({
    imageLoading:			'/javascripts/jquery-lightbox-0.5/images/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
		imageBtnPrev:			'/javascripts/jquery-lightbox-0.5/images/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
		imageBtnNext:			'/javascripts/jquery-lightbox-0.5/images/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
		imageBtnClose:		'/javascripts/jquery-lightbox-0.5/images/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
		imageBlank:				'/javascripts/jquery-lightbox-0.5/images/lightbox-blank.gif'
  });*/
  
  $("#content-right ul").after('<span class="clear"></span>');
  
  $("#content-right h2, #content-left h2, #footer h1").flashComplexImageReplacement(
      "/images/text-replace.swf", 
      {
        base: {
          font:"Klavika-Light",
          size:"32",
          color:"0xFFFFFF",
          xOffset:"-5",
          textTransform:"uppercase"
       },
       span:{
         font:"Arial-Bold",
         size:"17",
         color:"0x008EDE",
         yOffset:"11",
         align:"right"
       }
     }
   );
   
});

function textReplacedHeight(id, height){
  if(height > 0){
    $("#"+id).css({height:height+"px"});
    $("#"+id).parent().css({height:height+"px"});
  }
}

$.fn.animateNavigation = function() {
  // Set up
  var current = null;
  var animating; //boolean
  var boxes = $(this).children();
  
  var openSection; // string, id of current section
  
  var DURATION = "normal";
  var EASING = "swing";
  var HOVER_DELAY = 160;
  
  var NORMAL_WIDTH = "186px";
  var MAX_WIDTH = "516px";
  var MIN_WIDTH = "21px";
  
  var NORMAL_HEIGHT = "73px";
  var MAX_HEIGHT = "125px";
  var MIN_HEIGHT = "21px";
  
  // for the positioning of the middle boxes
  var MIDDLE_X_MIN_LEFT = MIDDLE_X_MAX = "28px";
  var MIDDLE_X_MIN_RIGHT = "523px";
  var MIDDLE_X_NORMAL = "193px";
  
  var defaultBgPos = "0px 0px";
  var greenBgPos = "0px -44px";
  var blueBgPos = "0px -88px";
  var redBgPos = "0px -132px";
  var pinkBgPos = "0px -176px";
  var greyBgPos = "0px -220px";
  var yellowBgPos = "0px -264px";
  
  var hoverHandler = function(){
    var element = this;
    if($(this).data('hoverTimeout')) clearTimeout($(this).data('hoverTimeout'));
    var hoverTimeout = setTimeout(function(){hoverIn(element)}, HOVER_DELAY);
    $(this).data('hoverTimeout', hoverTimeout);
  }
  
  // Event handlers
  var hoverIn = function(element) {
    //if (animating) return;
    if(!element) var element = this;
    animating = true;
    current = element;
    stopAll();
    if (element.id == "hire-it" || element.id == "follow-it"){
      $(element).animate({width: MAX_WIDTH, height: MAX_HEIGHT, left:MIDDLE_X_MAX}, DURATION, EASING, onMaximise);
    } else {
      $(element).animate({width: MAX_WIDTH, height: MAX_HEIGHT}, DURATION, EASING, onMaximise);
    }
    minimiseOthers();
    switchLabels(element,"expanded");
    positionTriangle(element.id);
  };
  
  var onMaximise = function() {
    $(this).children().fadeIn(DURATION);
    animating = false;
  }
  
  var checkOver = function() {}
  
  // position the background sprite for different states
  var switchLabels = function(obj,mode) {
    var coords;
    switch (mode) {
      case "normal":
      $(obj).children().hide();
      coords = "-33px -22px";
      break;
      case "expanded":
      coords = "-42px -41px";
      break;
      case "tall":
      coords = "1px -94px";
      $(obj).children().hide();
      break;
      case "wide":
      coords = "-220px 4px";
      $(obj).children().hide();
      break;
    }
    $(obj).css({backgroundPosition:coords});
  }
  
  
  var hoverOut = function() {
    boxes.each(function(){
      if($(this).data('hoverTimeout')) clearTimeout($(this).data('hoverTimeout'));
    });
    //if(current != this) return;
    //if (animating) return;
    animating = true;
    current = null;
    stopAll();
    if(!openCurrentSection()) normalise();
  };
  
  // when we get back to neutral position
  var onNeutral = function(){
    animating = false;
  }
  
  var minimiseOthers = function(){
    
    var currentID = getCurrentChildCount();
    
    
    for (var i = 0; i < 3; i++){
      var box = boxes[i];
      if (current != box){
        if (currentID < 3){
          if (i == 1){
            $(box).animate({width: MIN_WIDTH, height: MAX_HEIGHT, left: currentID == 2 ? MIDDLE_X_MIN_LEFT : MIDDLE_X_MIN_RIGHT}, DURATION, EASING);
          } else {
            $(box).animate({width: MIN_WIDTH, height: MAX_HEIGHT}, DURATION, EASING);
          }
          switchLabels(box,"tall");
        } else {
          
          if(i == 1){
            $(box).animate({width: NORMAL_WIDTH, height: MIN_HEIGHT, left:MIDDLE_X_NORMAL}, DURATION, EASING);
          } else {
            $(box).animate({width: NORMAL_WIDTH, height: MIN_HEIGHT}, DURATION, EASING);
          }
          switchLabels(box,"wide");
        }
      }

    }
    
    for (var i = 3; i < 6; i++){
      var box = boxes[i];
      if (current != box){
        if (currentID >= 3){
          if (i == 4){
            $(box).animate({width: MIN_WIDTH, height: MAX_HEIGHT, left: currentID == 5 ? MIDDLE_X_MIN_LEFT : MIDDLE_X_MIN_RIGHT}, DURATION, EASING);
          } else {
            $(box).animate({width: MIN_WIDTH, height: MAX_HEIGHT}, DURATION, EASING);
          }
           switchLabels(box,"tall");
         } else {
          if (i == 4){
            $(box).animate({width: NORMAL_WIDTH, height: MIN_HEIGHT, left:MIDDLE_X_NORMAL}, DURATION, EASING);
          } else {
            $(box).animate({width: NORMAL_WIDTH, height: MIN_HEIGHT}, DURATION, EASING);
          }
           switchLabels(box,"wide");
         }
      }
    }
  
  
  }
  
  // kill all the animations
  var stopAll = function(){
    boxes.each(function(i){
      $(this).stop();
    })
  }
  
  var normalise = function(){
    boxes.each(function(i){
        switch (i) {
          case 1:
          case 4:
            $(this).animate({width: NORMAL_WIDTH, height: NORMAL_HEIGHT, left:MIDDLE_X_NORMAL}, DURATION, EASING, onNeutral);
          break;
          default:
            $(this).animate({width: NORMAL_WIDTH, height: NORMAL_HEIGHT}, DURATION, EASING, onNeutral);
        }
        switchLabels(this,"normal");
    })
  }


  // forces the nav to open up to the current section when being rolled over
  var openCurrentSection = function(){
    if (!openSection) return;
    hoverIn(boxes.filter(openSection).get(0));
    return true;
  }
  
  // which one of the boxes is supposed to be open?
  var determineCurrentSection = function(){
    boxes.each(function(){
      if ($(this).hasClass("current")){
       openSection = "#" + this.id;
       defaultBgPos = this.id;
       positionTriangle(this.id);
       openCurrentSection();
       return;
      }
    });
  }

  
  var getCurrentChildCount = function(){
    var count = 0;    
    for (var i=0; i < boxes.length; i++){
      if (current == boxes[i]) return count;
      count ++;
    }
  }
  
  //split the lis up into 2 columns
  var setupChildLists = function(){
    boxes.each(function(i, e){
      var box = $(e);
      var lis = box.find("> ul li");
      
      box.append("<ul></ul>");
      
      var uls = box.find("> ul");
      var ul1 = $(uls[0]);
      var ul2 = $(uls[1]);
      
      ul1.addClass("left");
      ul2.addClass("right");
      
      if(lis.length > 3){
        
        var half = Math.ceil(lis.length/2);
        
        //add the second half of child lis to the new ul
        for(i=half; i<lis.length; i++){
          ul2.append(lis[i]);
        }
      }
    });
  }
  
  var setupTriangles = function(){
    $("#header").append('<span class="triangles"></span>');
  }
  
  var positionTriangle = function(targetId){
    
    targetPosition = defaultBgPos;
    if (targetId == "make-it")
      targetPosition = greenBgPos;
    else if (targetId == "hire-it")
      targetPosition = blueBgPos;
    else if (targetId == "watch-it")
      targetPosition = redBgPos;
    else if (targetId == "learn-it")
      targetPosition = pinkBgPos;
    else if (targetId == "follow-it")
      targetPosition = greyBgPos;
    else if (targetId == "join-us")
      targetPosition = yellowBgPos;
    
    $("#header > .triangles").css({backgroundPosition:targetPosition});
    
  }
  
  var click = function() {
    $(this).children(":first").click();
  };
  
  setupChildLists();
  setupTriangles();
  // Attach events
  boxes.mouseover(hoverHandler);
  boxes.parent().bind("mouseleave", hoverOut);
  boxes.click(click);
  
  // should the nav be made to open up for the current section?
  determineCurrentSection();
  

};

// Flash image replacement
jQuery.fn.flashImageReplacement = function(path, settings) {
  settings = jQuery.extend({wmode: "transparent"}, settings);
  var options = [
    {src: path, wmode: settings.wmode, flashvars: {css: '* {color: ' + $.colour.rgbToHex(this.css("color")) + ';}'}},
    {version: 7}
  ];

  if (settings.swapOnly) {
    options.push(function(flash) {
      var heading = $(this);
      flash.height = "100%";
      flash.width = "100%";
      heading.html($.fn.flash.transform(flash));
    });
  } else {
    options.push(function(flash) {
      var heading = $(this);
      heading.addClass("imageReplaced");
      flash.flashvars.txt = this.innerHTML.toUpperCase();
      flash.height = heading.height();
      flash.width = heading.width();
      heading.html($.fn.flash.transform(flash));
    });
  }
  this.flash.apply(this, options);
  return this;
};

jQuery.fn.flashComplexImageReplacement = function(path, vars, extras) {
  
  this.each(function(i, e){
    //
    var item = $(e);
    item.addClass("textReplaced");
    
    var flashvars = {};
    //pass txt to flash
    var txt = item.html();
    flashvars.txt = escape(txt);
    
    //assign any extra parameters
    for(var v in extras){
      flashvars[v] = extras[v];
    }
    
    //break up all the variables for all the selectors into textReplace flashvars
    for(var v in vars){
      for(var k in vars[v]){
        flashvars["textReplace_"+v+"_"+k] = vars[v][k];
      }
    }
    
    //create a holder for the flash file
    var rand = String(Math.random() + Math.random() + Math.random());
    rand = rand.replace(".", "");
    var id = "flash_text_replace_" + i + rand;
    item.html('<div id="'+id+'" class="textReplacedWrap">' + txt + '</div>');
    //setup any params
    params = {};
    params.wmode = "transparent";
    
    //pass variables to the flash so it knows what its called and what number it is
    flashvars.embeddedID = id;
    flashvars.embeddedKey = i;
    
    flashvars.width = item.width();
    flashvars.height = item.height();
    
    //check for a url and pass it to the flash
    if(item.attr("href")){
      flashvars.embeddedURL = item.attr("href");
    }
    
    //assign id and name (good practise for ExternalInterface)
    var attributes = {id:id, name:id};
    
    //embed the swf
    swfobject.embedSWF(path, id, item.width(), item.height(), "8.0.0", null, flashvars, params, attributes);
    
  });
  
  return this;
  
};


jQuery.colour = {
  rgbToHex: function(rgb) {
    if (rgb && rgb.match(/rgb/)) {
      var rgbvals = rgb.match(/rgb\((.+),(.+),(.+)\)/i);
      return '#' + (
        parseInt(rgbvals[1]).toString(16) +
        parseInt(rgbvals[2]).toString(16) +
        parseInt(rgbvals[3]).toString(16)
      );
    } else {
      return rgb;
    }
  }
};

