//Settings
var menuAnimateTime = 500;  //How long in milliseconds should the menu toggle animation take?
var menuEvent = "mouseenter";  // what activates the left nav menu expansion?

var sliderAnimateTime = 500; //How long in milliseconds should the slider animation take when activated by user input?
var sliderAutoAnimateTime = 2000; //How long in milliseconds should the slider animation take when activated by the automatic timer?
var sliderAutoAnimateDelay = 5000; //How long in milliseconds between activation of the slider's automatic timer?
var sliderInteractiveAnimateDelay = 10000; //How long after interacting with the slider until the automatic timer starts again?

var newsAnimateTime = 500; //How long in milliseconds should the news animation take?
var newsSizeThreshold = 5000; //How many characters a news article can have before we don't try to animate it anymore?

var index = 0;
var numItems;
var initialPosition;
var itemWidth;
var containerWidth;
var table;
var newPosition;
var timeoutId;
var scrolling = false;
var menuAnimating = false;

$(document).ready(function() {
  //Random quote stuff
  if ( $(".random").size() ) {
    $(".random").each(function() {
      $(this).children("div").hide();
      $(this).children("div").eq(Math.floor(Math.random() * $(this).children("div").size())).show();
    });
//     $(".random div").hide();
//     $(".random div").eq(Math.floor(Math.random() * $(".random div").size())).show();
  }
  
  //News expand stuff
  if ($("#page").size()  ) {
    $(".expand-header").bind("click",expandNews).css("cursor","pointer");
    //$(".section-body").css("margin-top","0px");
    
    initialNewsExpand();
    
    
  }
   
  //Front page slider stuff
  if ($("#slider").size()) {
    numItems = $("#slider table td").size();
    initialPosition = $("#slider table").position().left;
    itemWidth = $("#slider table td:first").width();
    containerWidth = $("#slider").width();
    table = $("#slider table");
    
    //Set up extra td's for wraparound
    var firstTd = $("#slider table td:first").html();
    var secondTd = $("#slider table td:first").next("td").html();
    var penultimateTd = $("#slider table td:last").prev("td").html();
    var lastTd = $("#slider table td:last").html();
    
    table.find("tr").prepend("<td>" + lastTd + "</td>").prepend("<td>" + penultimateTd + "</td>").append("<td>" + firstTd + "</td>").append("<td>" + secondTd + "</td>");
    table.css("left",(initialPosition - itemWidth * 2)+"px");
    initialPosition = initialPosition - itemWidth * 2;
    
/*    $("#slider").prepend('<div id="left-slide-button" class="slide-button"></div><div id="right-slide-button" class="slide-button"></div>');
    $(".slide-button").css("height","100%").css("width","100px");*/
    
    $("#slider-button-left").click(scrollLeft).css("cursor","pointer");
    $("#slider-button-right").click(scrollRight).css("cursor","pointer");
    $("#slider").hover(function() {
      if (scrolling) {
        table.stop();
      }
      clearTimeout(timeoutId);
    },function() {
      if (scrolling) {
        index--;
        autoSlide();
      } else {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(autoSlide, sliderInteractiveAnimateDelay);
      }
    });
    
    timeoutId = setTimeout(autoSlide, sliderAutoAnimateDelay);
  }
  
  //Menu expand stuff
  $("#menu>a").bind(menuEvent, expandMenu);

    // button glow on hover
    $(".product-all-roll").hover(
      function() {
        $(this).stop();
        $(this).children("img").fadeIn(200);
      },
      function(){
        $(this).stop();
        $(this).children("img").fadeOut(600);
      }
    );

    // button rollover states
    $(".product-info-button").hover(
      function() {
        $(this).stop();
        $(this).animate( {backgroundPosition: '(0 -28)'}, 100);
      },
      function() {
        $(this).stop();
        $(this).animate( {backgroundPosition: '(0 0)'}, 100);
      }
    );

    $(".product-roll").hover(
      function() {
        $(this).stop();
        $(this).animate( {backgroundPosition: '(0 -19)'}, 100);
      },
      function() {
        $(this).stop();
        $(this).animate( {backgroundPosition: '(0 0)'}, 100);
      }
    );

    $(".callout-button").hover(
      function() {
        $(this).stop();
        $(this).animate( {backgroundPosition: '(0 -28)'}, 100);
      },
      function() {
        $(this).stop();
        $(this).animate( {backgroundPosition: '(0 0)'}, 100);
      }
    );

    $(".nav-callout-button").hover(
      function() {
        $(this).stop();
        $(this).animate( {backgroundPosition: '(0 -28)'}, 100);
      },
      function() {
        $(this).stop();
        $(this).animate( {backgroundPosition: '(0 0)'}, 100);
      }
    );

    $(".nav-callout-button-flip").hover(
      function() {
        $(this).stop();
        $(this).animate( {backgroundPosition: '(0 -28)'}, 100);
      },
      function() {
        $(this).stop();
        $(this).animate( {backgroundPosition: '(0 0)'}, 100);
      }
    );

    $(".product-big-roll").hover(
      function() {
        $(this).stop();
        $(this).animate( {backgroundPosition: '(0 -32)'}, 100);
      },
      function() {
        $(this).stop();
        $(this).animate( {backgroundPosition: '(0 0)'}, 100);
      }
    );
    
    // Script for sitemap animation.
    // Execute this after the site is loaded.
    $(function() {
    
      $('.expandable-list li').each(function(i) {
        $(this).prepend('<span class="list-icon-container"><img src="images/list-spacer.gif" class="list-icon" /></span>');
      });

      $('.expandable-list li > ul').each(function(i) {
        // Find this list's parent list item.
        var parent_li = $(this).parent('li');
        parent_li.addClass('plus');
        parent_li.children('.list-icon-container').wrapInner('<a/>').find('img').attr('src','images/list-plus.gif');
        // Temporarily remove the list from the
        // parent list item, wrap the remaining
        // text in an anchor, then reattach it.
        var sub_ul = $(this).remove();
        parent_li.find('a').not(".expand-target").click(function() {
          if (sub_ul.css("display") == "none") {
            $(this).children('img').attr('src','images/list-minus.gif');
          } else {
            $(this).children('img').attr('src','images/list-plus.gif');
          }
          //Remove the 250 to have this expand instantaneously.
          sub_ul.toggle(250);
          return(false);
        });
        parent_li.append(sub_ul);
      });

      $('.expandable-list .list-selected img').each(function(i) {
        $(this).attr('src','images/list-selected.gif');
      });

      // Hide all lists except the outermost.
      $('.expandable-list ul ul').hide();

      //Show the path to any selected nodes.
      $('.expandable-list .list-selected').parents('ul').show();
      $('.expandable-list .list-selected').parents('li').each(function(i) {
        $(this).children('span').children('a').children('img').attr('src','images/list-minus.gif');
      });
      // locations of links that will auto-expand targeted open/close sections
      $("#menu .sub-menu a").add("#footer a").add(".quote-key-area a").add(".nav-callout a").add("a.expand-target").click(function() {
        var thisButton = $(this);
        document.location = thisButton.attr("href");
        initialNewsExpand();
      });
    });
    
});

function initialNewsExpand() {
  // Hide all of the sections (if there are any), then open the appropriate one.
  // Note that this code requires a certain structure in the .section divs...that 
  // is, the anchor tag <a name="articleX"></a> must be the first tag inside the 
  // .section div.  Any other arrangement will be dealt with in an undefined and 
  // potentially quite dangerous manner.  The safety of the world depends on you
  // properly formatting your html.  Don't let us down.
  
  // If the hash (#) part of the url is not present, this code will close all
  // sections and open the first one on the page.
  
  $("#page #main .expand-body").add("#page #main .expand-divider").hide();
  $("#page #main .expand-header .open-toggle").attr("src", "images/header-but-open.gif");
  if (document.location.hash.substr(1)) {
    var anchor = $("a[name="+document.location.hash.substr(1)+"]");
    anchor.next(".expand-header").nextAll(".expand-body").show();
    anchor.next(".expand-header").nextAll(".expand-divider").show();
    anchor.next(".expand-header").find(".open-toggle").attr("src", "images/header-but-close.gif");
    window.location = document.location;
  } else {
    // open first sections, unless marked always-start-closed
    $("#page #main .expand:first .expand-body").add("#page #main .expand:first").not(".always-start-closed").find(".expand-body").show();
    $("#page #main .expand:first  .expand-header .open-toggle").not(".always-start-closed .expand-header .open-toggle").attr("src", "images/header-but-close.gif");
    // $("#page #main .expand:first .expand-header .open-toggle").attr("src", "images/header-but-close.gif");
  } 
}

function expandNews() {
  var thisButton = $(this);
  var thisImg = thisButton.find(".open-toggle");
  var newsSection = thisButton.closest(".expand");
  var newsItem = newsSection.children(".expand-body");
  var subItem = newsSection.children(".expand-divider");

  //alert(thisButton.attr("src"));
    if (thisImg.attr("src") == "images/header-but-close.gif") {
      thisImg.attr("src", "images/header-but-open.gif");
    } else {
      thisImg.attr("src", "images/header-but-close.gif");
    }
    
  var sectionLength = 0;
  newsItem.each(function() {
    sectionLength += $(this).html().length;
  });
  if(sectionLength < newsSizeThreshold) {
    newsItem.slideToggle(newsAnimateTime, function() {
    });
    subItem.slideToggle(newsAnimateTime, function() {
    });
  } else {
    newsItem.toggle();
    subItem.toggle();
  }
//   newsSection.children(".edge-faint-left,.edge-faint-right,.edge-faint-top,.edge-faint-bot").toggle(newsAnimateTime);
}

function expandMenu() {
  if (menuAnimating == false) {
    
    if ($(this).next(".sub-menu").size()) {
      menuAnimating = true;
      var expand = $(this).next(".sub-menu");
      var contract = $("#menu .sub-menu").not(expand);
      var thisButton = $(this);
      thisButton.unbind(menuEvent);
      thisButton.bind(menuEvent,retFalse);
  //Uncomment the following call if using menuEvent = "click"
  /*    expand.toggle(menuAnimateTime, function() { 
        thisButton.unbind(menuEvent);
        thisButton.bind(menuEvent, expandMenu); 
        menuAnimating = false;
      });*/
  //Uncomment the following call if using menuEvent = "mouseenter"
      expand.show(menuAnimateTime, function() {
        thisButton.unbind(menuEvent);
        thisButton.bind(menuEvent, expandMenu);
        menuAnimating = false;
      });
      contract.hide(menuAnimateTime);
    //alert($(this).attr("href"));
      return(false);
    } else {
      return(true);
    }
  } else {
    return(false);
  }
}

function autoSlide() {
  scrolling = true;
  var thisButton = $("#slider-button-right");
  thisButton.unbind("click");
  index++;
  if (index >= numItems) {
    index = 0;
    newPosition = initialPosition - ((index-1) * itemWidth);
    table.css("left",newPosition+"px");
  }
  newPosition = initialPosition - (index * itemWidth);
  params = {left: newPosition+"px"};
  table.animate(params, sliderAutoAnimateTime, "swing", function() { 
    thisButton.bind("click",scrollRight);
    clearTimeout(timeoutId);
    timeoutId = setTimeout(autoSlide, sliderAutoAnimateDelay);
    scrolling = false;
  });
}

function retFalse() {
  return(false);
}

function slideLeft() {
    
}

function slideRight() {
 
}

function scrollLeft() {
  var thisButton = $(this);
  thisButton.unbind("click");
  clearTimeout(timeoutId);
  index--;
  if (index < -1) {
    index = numItems - 2;
    newPosition = initialPosition - ((index+1) * itemWidth);
    table.css("left",newPosition+"px");
  }
  newPosition = initialPosition - (index * itemWidth);
  params = {left: newPosition+"px"};
  table.animate(params, sliderAnimateTime, function() { 
    thisButton.bind("click",scrollLeft);
    clearTimeout(timeoutId);
    timeoutId = setTimeout(autoSlide, sliderInteractiveAnimateDelay);
  });
}

function scrollRight() {
  var thisButton = $(this);
  thisButton.unbind("click");
  clearTimeout(timeoutId);
  index++;
  if (index >= numItems) {
    index = 0;
    newPosition = initialPosition - ((index-1) * itemWidth);
    table.css("left",newPosition+"px");
  }
  newPosition = initialPosition - (index * itemWidth);
  params = {left: newPosition+"px"};
  table.animate(params, sliderAnimateTime, function() { 
    thisButton.bind("click",scrollRight);
    clearTimeout(timeoutId);
    timeoutId = setTimeout(autoSlide, sliderInteractiveAnimateDelay);
  });
}
