/* EducationPlanner.org | global.js | Global Javascript */

/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, indent: 2 */

/*global $, window, PHEAA */

var edplanner = (function () {
  
  // Declaring Private Variables
  var aSlides,
  oTimeout = null, 
  oSlideshowList = null,
  oSlideshowController = null,
  iCurrentSlide = 0,
  bSlideBlocker = false,
  oIFrame = null,
  
  // Declaring Private Methods
  fnSlideShow = function (e) {
    // Declare variables;
    var oNewSlide,
    // Transform "this" into jQuery object;
    oThis = $(this),
    // Speed interval in milliseconds;
    iSpeed = 400,
    // Extract slide index from this;
    iNewSlide = oThis.data("slideIndex"),
    // Get DOM object of current slide;
    oCurrentSlide = $(aSlides[iCurrentSlide]);
    
    /*
      End function if there is no new slide index, 
      if this is the current slide, 
      or if the animation is already in progress;
    */
    if (isNaN(iNewSlide) || 
        iNewSlide === iCurrentSlide || 
        bSlideBlocker) {
      return false;
    } else {
      // Get DOM object of new slide;
      oNewSlide = aSlides[iNewSlide];
      // Set blocking variable;
      bSlideBlocker = true;
    }
    
    // Fade out old slide and "508" hide it at end;
    oCurrentSlide.data("nextSlide", oNewSlide).fadeOut(iSpeed, function () {
      // Transform this into a jQuery object;
      var oThis = $(this);
      
      // Hide last slide for 508;
      oThis.addClass("hide").css("display", "block");
      // Fade in new slide;
      $(oThis.data("nextSlide")).css("display", "none").removeClass("hide").fadeIn(iSpeed, function () {
        // Discativate blocking variable;
        bSlideBlocker = false;
      }).find("p.storyButton").css("display", "none").fadeIn(iSpeed).end();
    }).find("p.storyButton").fadeOut(iSpeed, function () {
      $(this).css("display", "block");
    }).end();
    
    //Fade for controller;
    $("ul#slideShowController").fadeOut(iSpeed, function () {
      $(this).fadeIn(iSpeed);
    });
    
    // Turn all images to off source image;
    oSlideshowController.find("img").attr("src", "\/images\/homepage\/controller.png").end();
    // Turn initiating image to on source image;
    oThis.find("img").attr("src", "\/images\/homepage\/controller-active.png").end().blur();
    // Set current slide index to new slide index;
    iCurrentSlide = iNewSlide;
    
    // End function;
    if (e && e.preventDefault) {
      if (oTimeout) {
        clearTimeout(oTimeout);
        oTimeout = null;
      }
      e.preventDefault();
    }
    return false;
  },
  
  fnSlideTimer = function () {
    var oNewSlideLink,
    iNewIndex = (iCurrentSlide + 1) >= aSlides.length ? 0 : iCurrentSlide + 1;
     
    if (oTimeout) {
      clearTimeout(oTimeout);
      oTimeout = null;
    }
     
    $("ul#slideShowController a").each(function () {
      var oThis = $(this);	
	
      if (oThis.data("slideIndex") === iNewIndex && 
          typeof oNewSlideLink === "undefined") {
        oNewSlideLink = this;
      }
    });
     
    if (typeof oNewSlideLink !== "undefined") {
      fnSlideShow.call(oNewSlideLink);
       
      oTimeout = setTimeout(fnSlideTimer, 7000);
    }
  }, 
  
  fnShow = function () {
    var oSource = $(this);
    
    if (oSource.data("oTarget")) {
      $(oSource.data("oTarget")).removeClass("hide");
      oSource.addClass("activeLink").blur();
    }
    
  },
  
  fnHide = function () {
    var oSource = $(this);
    
    if (oSource.data("oTarget")) {
      $(oSource.data("oTarget")).addClass("hide");
      oSource.removeClass("activeLink").blur();
    }
    
  },
  
  fnShowAll = function () {
    $(".expandBox div").removeClass("hide");
    $(".expandBox a").addClass("activeLink").blur();
  },
  
  fnHideAll = function () {
    $(".expandBox div").addClass("hide");
    $(".expandBox a").removeClass("activeLink").blur();
  },
  
  // Changes link text between Hide and View
  fnChangeViewTitle = function () {
    var iTitleIndex = this.innerHTML.indexOf("View"),
    sTitleText,
    sReturnText = "";
    
    if (iTitleIndex !== -1) {
      sTitleText = "Hide";
    } else if ((iTitleIndex = this.innerHTML.indexOf("Hide")) !== -1) {
      sTitleText = "View";
    } else {
      return;
    }
    
    if (iTitleIndex > 0) {
      sReturnText += this.innerHTML.slice(0, iTitleIndex);
    }
    
    sReturnText += sTitleText;
    
    if (iTitleIndex + 4 < this.innerHTML.length) {
      sReturnText += this.innerHTML.slice(iTitleIndex + 4);
    }
    
    this.innerHTML = sReturnText;
    
  },
  
  // Changes link text between Expand and Collapse
  fnChangeExpandCollapse = function () {
    
    $(this).toggleClass("activeLink");
    $(this).text($(this).text() == "Expand All" ? "Collapse All" : "Expand All");
    
  },
  
  // Changes hover states on IE Menu Fix
  fnIEMenuFixOn = function () {
    // Save a reference to "this";
    var that = this, 
    // Initialize a variable to hold a setTimeout call;
    oMenuDelay = null,
             
    // Method to position iFrame under submenu;
    fnExecuteFix = function () {
      // Get child UL element in main menu;
      var oSubMenu = $(that).children("ul"), 
      // Get position and size of the submenu UL;
      oPos = oSubMenu.position(), 
      iLeft = oPos && typeof oPos.left === "number" && oPos.left >= 0 ? 
        oPos.left : -9999,
      iTop = oPos && typeof oPos.top === "number" && oPos.top >= 0 ? 
        oPos.top : -9999,
      iHeight = oSubMenu.outerHeight(),
      iWidth = oSubMenu.outerWidth(), 
      iZIndex = oSubMenu.css("z-index") - 1;
      
      // Clear timeout and reset, if present;
      if (oMenuDelay) {
        clearTimeout(oMenuDelay);
        oMenuDelay = null;
      }
      
      // Insert iframe into DOM and set style properties;
      oIFrame.insertBefore(oSubMenu).css({
        "background-color" : "#FFFFFF", 
        "height" : iHeight + "px",
        "left" : iLeft + "px",
        "position" : "absolute", 
        "top" : iTop + "px",
        "width" : iWidth + "px",
        "z-index" : iZIndex
      }).data("bDomOff", false);
    };
    
    // Build iframe, if not present;
    if (!oIFrame) {
      oIFrame = $("<iframe id=\"menuIFrame\" \/>").data("bDomOff", true).attr("src", "javascript:\"\";");
    }
    
    oMenuDelay = setTimeout(fnExecuteFix, 5);
  },
  
  fnIEMenuFixOff = function () {
    // If the iframe exists, detach it from the DOM;
    if (oIFrame && !oIFrame.data("bDomOff")) {
      oIFrame.detach().data("bDomOff", true);
    }
  };
  
  return function () {
    
    // Launch New Window Script
    var oDom = $(document);
    
    oDom.find("a[rel=external],.contentButton em[rel=external],a[rel=generic],a[rel=pdf],a[rel=excel],a[rel=ppt],map#Map area").live("click", function () {
      var oWidth = (screen.width/1.5);
      var oHeight = (screen.height/1.5);
      var oLeft = (screen.width  - oWidth)/2;
      var oTop = (screen.height - oHeight)/2;
      window.open(this.href,"External_Link","height=500,width=800,resizable=yes,top="+oTop+",left="+oLeft+",scrollbars=yes,menubar=yes,toolbar=yes,status=yes,location=yes");
      return false;
    }).end()
    
    // Test Your Knowledge Script
    .find(".detailsBox,.answerBox").each(function () {
      
      var sCaption = "View " + this.className.replace(/(details|answer)Box/, function (a, b) {
        return b.charAt(0).toUpperCase() + b.slice(1);
      });
      
      $("<p class=\"detailLink\"><a href=\"#\">" + sCaption + "<\/a><\/p>").find("a").toggle(fnShow, fnHide).data("oTarget", this).click(fnChangeViewTitle).end().insertBefore(this);
      
    }).addClass("hide").end()
    
    // Show and Hide Script
    .find(".blinds").each(function () {

      var oThis = $(this), 
      oTarget = oThis.children().not(":first-child").wrapAll("<div \/>").addClass("hide");
      
      oThis.children().first().wrapInner("<a href=\"#\" \/>").find("a").toggle(fnShow, fnHide).data("oTarget", oTarget).end();

    }).end()
    
    // Expand and Collapse Script    
    .find(".expandBox").each(function () {

      var oThis = $(this),
      oDiv = oThis.children().not(":first-child").wrapAll("<div \/>"),
      oTarget = oThis.children("div").addClass("hide");
      
      oThis.children().first().addClass("first").wrapInner("<a href=\"#\" \/>").find("a").click(function() {
        if($(this).hasClass("activeLink")) {
          $(this).removeClass("activeLink");
          oTarget.addClass("hide");
        } else {
          $(this).addClass("activeLink");
          oTarget.removeClass("hide");
        };
        return false;
      }).end()

    }).end()
    
    // Add Expand / Collapse All Option
    .find(".expandBox:first").each(function () {
      
      $("<p class=\"expandAll\"><a href=\"#\">Expand All<\/a><\/p>").find("a").toggle(fnShowAll, fnHideAll).data("oTarget", this).click(fnChangeExpandCollapse).end().insertBefore(this);
      
    }).end()
          
    // Write in controller for slideshow;
    
    // Get Slidshow list element;
    .find("ul#slideShow").each(function () {
      var i, iLength, sImgSrc;
      
      oSlideshowList = $(this);
      
      // Save a reference to each slide instance as an array;
      aSlides = oSlideshowList.children("li");
      
      // Build the slideshow controller;
      oSlideshowController = $("<ul id=\"slideShowController\" \/>").insertAfter(oSlideshowList);
      
      // Insert a control selector for each slide in the list;
      for (i = 0, iLength = aSlides.length; i < iLength; i += 1) {
        // Determine image source variable value;
        sImgSrc = i > 0 ? 
          "\/images\/homepage\/controller.png" : 
          "\/images\/homepage\/controller-active.png";
        
        // Construct slide selecter and append to list;
        $("<li><a href=\"#\"><img src=\"" + sImgSrc + "\" alt=\"Image #" + (i + 1) + " Slide\" height=\"15\" width=\"15\" \/></a></li>").find("a").data("slideIndex", i).click(fnSlideShow).end().appendTo(oSlideshowController);
      }
      
      // Start slideshow timer;
      $(window).bind("load", function () {
        oTimeout = setTimeout(fnSlideTimer, 7000);
      });
      
    }).end()
    
    // Initialize blur and focus methods on search box;
    .find("input#sp-q").bind("focus", function () {
      this.value = this.value === "Enter Search Term" ? "" : this.value;
    }).bind("blur", function () {
      this.value = this.value.replace(/^\s+|\s+$/g, "").length > 0 ? this.value : "Enter Search Term";
    }).val("Enter Search Term").end();
    
    // Activate drop-down menu behavior in IE 6.0;
    if (typeof document.body.style.maxHeight === "undefined") { 
      oDom.find("ul#siteNav").children("li").hover(function () {
        $(this).addClass("navHover");
      }, function () {
        $(this).removeClass("navHover");
      }).end();
    }
    
    // 508 Drop-down Menu fix for IE
    if (document.all && !window.opera && oDom.find("object,embed").length > 0) {
      // Bind fix methods through jQuery hover;
      oDom.find("ul#siteNav").children("li").hover(fnIEMenuFixOn, fnIEMenuFixOff).end();
      
      // Build seed of initial iFrame;
      oIFrame = $("<iframe id=\"menuIFrame\" \/>").data("bDomOff", true).attr("src", "javascript:\"\";");
    }
    
    // Report load of page to Urchin;
    if (typeof PHEAA !== "undefined" && typeof PHEAA.Urchin !== "undefined") {
      PHEAA.Urchin.callUrchin(window.location.pathname + window.location.search + window.location.hash, "Page_Load");
    }
  };
  
}());

$("document").ready(edplanner);
