// global.js
// PHEAA.org Global JavaScript
// Property of AES/PHEAA 2011
// http://www.pheaa.org

var pheaa = (function() {
  
  // Set String.prototype.trim method
  if (!String.prototype.trim) {
    String.prototype.trim = function () {
      var re = /^\s+|\s+$/g;
      return this.replace(re, "");
    };
  }
  
  fnFireUrchin = function() {
      
      //Instantiate variables;
      var oTimeout,
          sLocation = window.location.pathname,
          iCountdown = 500,
          
        // Method to loop until PHEAA.Urchin can be called;
        fnCallUrchin = (function() {
            
        // Clear timeout, if present;
        if(oTimeout) {
          clearTimeout(oTimeout);
        }
        
        // Check if PHEAA.Urchin is defined;
        if(typeof PHEAA !== "undefined" && typeof PHEAA.Urchin !== "undefined") {
        
        // Call PHEAA.Urchin;
        PHEAA.Urchin.callUrchin(sLocation, "Page_Load");
        // Remove method from DOM;
        fnFireUrchin = null;
      } else if(iCountdown > 0) {
        iCountdown -= 1;
        oTimeout = setTimeout(fnCallUrchin, 100);
      }
            
    }());
  },
  
  stateGrantApplyModal = function() {
    oDom = $(document);
    
    // Append the fade layer and the modal window;
    oDom.find("body").append("<div id=\"fade\" /><div id=\"modal\" />").end();
    
    // Preload content into modal, center it, then prepend the close option;
    $("#modal").load("/funding-opportunities/state-grant-program/applying.shtml #modalContainer",function() {
      $(this).css({
        "background-image": "none", // This will disable the preloader;
        "margin-left": -(($("#modal").width() + 40) / 2),
        "margin-top": -(($("#modal").height() + 40) / 2)
      }).prepend("<a href=\"#\" class=\"close\" title=\"Close Window\"></a>");
    
      // Reset the CSS opacity, and fade in the fade layer;
      $("#fade").css({
        "opacity": ".4",
        "filter" : "alpha(opacity=40)"
      }).fadeIn(500,function() {
        // Set focus to the modal window;
        $(this).focus();
        // Fade in the modal layer  ;  
        $("#modal").fadeIn(500);
        $("a[rel=generic]","#modal").each(function() {
          $(this).click(function() {
            window.open($(this).attr("href"));
            return false;
          });
        }).end();
      });
    
    }).end();
    
    // Apply functionality to close modal;
    $("#fade, a.close").live("click",function() {
      // Fade out and remove the modal window, and then the fade layer;
      oDom.find("#modal").fadeOut(500,function() {
        $(this).remove();
        $("#fade").fadeOut(500,function() {
          $(this).remove();
        });
      }).end();
      
      // Restore focus to the page body;
      $("body").focus();
      
      return false;
      
    });
    
  },
  
  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();
    }
    
  },
  
  // Hide/show definitions, 508 style;
  fnHideShowDefinitions = function(element) {
    if(element.hasClass("active")) {
      element.removeClass("active").parent("dt").next("dd").addClass("hide");
    } else {
      element.addClass("active").parent("dt").css({
        "margin": "1em 0 0 0"
      }).next("dd").removeClass("hide");
    }
  },
  
  // Open calculators in external resized windows;
  fnOpenCalcWindow = function(theURL,windowName,features) { 
    window.open(theURL,windowName,features);
  }
  
  // Submit form to a new window, 508 style;
  fnSubmitFormExtWindow = function(form) {
    form.target = "_blank";
    return false;
  }
     
  return {
	
    cookies: (function () {
  return {
    createCookie: function (sName, sValue, oParams) {
      
      var dDate, iFutureDays, 
      sCookieString = "",  
      sExpires = "", 
      sPath = oParams && oParams.hasOwnProperty("sPath") ? 
        "; path=" + oParams.sPath : "; path=/", 
      sDomain = oParams && oParams.hasOwnProperty("sDomain") ?
        "; domain=" + oParams.sDomain : "";
  
      if (oParams && oParams.hasOwnProperty("iDays")) {
        dDate = new Date();
        iFutureDays = oParams.iDays * 24 * 60 * 60 * 1000;
        dDate.setTime(dDate.getTime() + iFutureDays);
        sExpires = "; expires=" + dDate.toGMTString();
      }

      sCookieString += sName + "=" + encodeURIComponent(sValue);
      sCookieString += sExpires + sPath + sDomain;
      document.cookie = sCookieString;
      
    }, 

    eraseCookie: function (sName, sType) {

      var i, iLength, aHashArray, // Instantiate variables;
      sThisType = sType ? sType : "single", // Set type of cookie to erase;
      
      /* 
        Initialize Regular Expression looking for given value at 
        the start of an entry;
      */
      reValue = new RegExp("^" + sName), 
      
      // Split string into array;
      aCookieArray = document.cookie.split(";"); 

      if (aCookieArray.length > 0) { // Loop through Cookie Array;
        for (i = 0, iLength = aCookieArray.length; i < iLength; i += 1) {
          // Split value into name|value pairs;
          aHashArray = aCookieArray[i].split("="); 

          /* 
            Reset the value to null if either the type is 'single' 
            (one cookie) and the cookie name matches the string given 
            (index) requested, or the type is 'class' (multiple cookies) 
            and the cookie's name starts with the string given (index)
          */

          aHashArray[0] = aHashArray[0].trim();
          if ((aHashArray[0] === sName && sThisType === "single") || 
              (aHashArray[0].match(reValue) && sThisType === "class")) {
            cookies.createCookie(aHashArray[0], "", {iDays: -1});
          }
        }
      }
    }, 
    
    readCookie: function (sName) {

      var i, iLength, sCookie, 
      sValue = false, 
      sNameEQ = sName.trim() + "=", // Append "=" to cookie name;
      
      // Create array of cookie name/values;
      aCookieArray = document.cookie.split(';'); 
  
      // Iterate through array;
      for (i = 0, iLength = aCookieArray.length; i < iLength; i += 1) { 
        sCookie = aCookieArray[i].trim(); // Save individual entry;
        
        // Compare value to desired cookie;
        if (sCookie.indexOf(sNameEQ) === 0) { 
          // Extract cookie if match;
          sValue =  decodeURIComponent(sCookie.substring(sNameEQ.length, sCookie.length)); 
        }
      }
   
      if (sValue && sValue.length > 0) {
        return sValue; // Return cookie value;      
      } else {
        return null; // Cookie not found, return no value;
      }
      
    }
  };
}()),
      
    init: function() {
      
      // Fire Urchin;
      fnFireUrchin();
      
      // Define the document as an object;
      oDom = $(document);
      
      // Apply external window functionality to links;
    // Create an array of rel attribute options;
      var relArray = new Array( 
        "external","pdf","excel","ppt","accountaccess","generic","contact_form"
      );
      // Open each link with a rel in the array in a new window;
      $.each(relArray, function() {
        $("a[rel=" + this + "]").click(function() {
          window.open($(this).attr("href"));
          return false;
        });
      });
      
      // Swap dropdown links if IE6 or lower;
      oDom.fnSwapSignInLinks();
      
      // Apply urchin class to all links;
      oDom.find("a[href!='#']").each(function() {
        if($(this).attr("href")) {
          $(this).addClass("urchin");
        }
      }).end()
      
      // Animate scrolling elements;
      .find("a[href='#top']").each(function() {
        $(this).fnAnimateScroll("#top", 0);
      }).end()
      
      // Apply placeholders to input fields;
      .find("input:text").each(function() {
        $(this).fnInputPlaceholder(this.value);
      }).end()
      
      // Disable form submit until input is accepted;
      .find("#search").submit(function() {
        if($(this).find("#sp-q").val() !== "" &&
           $(this).find("#sp-q").val() !== "Enter Search Term") {
          return true;
        } else {
          return false;
        }
      }).end()
      
      // Apply state grant modal, if the link exists;
      .find("a.stateGrantApplyButton").click(function() {
        stateGrantApplyModal();
        return false;
      }).end()
      
      // Hide/show definitions;
      /*.find("dl.faqList dd").addClass("hide").end()
      .find("dl.faqList dt a").each(function() {
        $(this).click(function() {
          fnHideShowDefinitions($(this));
          return false;
        });
      }).end()*/
      
      .find(".faqList dt").each(function () {
        var oThis = $(this), 
        oThat = oThis.attr("id");
        oTarget = oThis.next("dd").addClass("hide");
        
        oThis.removeAttr("id").wrapInner("<a href=\"#\" \/>").find("a").attr("id", oThat).attr("name", oThat).toggle(fnShow, fnHide).data("oTarget", oTarget).end();
      }).end()
      
      // I Want To... functionality;
      .find("#iWantToDropdown").each(function() {
        $(this).fnIWantTo();
      }).end()
      
      /* // Sample call to fnGetURLVar(var) is URL query string was "?s1=v"
      var s1 = $.fn.fnGetURLVar("s1"); */
      
    
      // Method to apply blinds;
      .find(".blinds").each(function () {
        var oThis = $(this), 
        oThat = oThis.children().first().attr("id"), 
        oTarget = oThis.children().not(":first-child").wrapAll("<div\/>").addClass("hide");
      
        oThis.children().first().removeAttr("id").wrapInner("<a href=\"#\" \/>").find("a").attr("name",oThat).attr("id",oThat).toggle(fnShow, fnHide).data("oTarget", oTarget).end();
      }).end();
      
      // Pre-open if there is an anchor in the URL;
      if (window.location.hash) {
        $(window.location.hash).trigger("click");
      }
  
    }
  }
  	
}());


/* jQuery extensions
 * pass jQuery to a self executing function (closure) that maps it to the dollar sign
 * so it can't be overwritten by another library in the scope of its execution.*/
(function($) {

  // fnAnimateScroll - This function will animate the vertical position of the page;
  $.fn.fnAnimateScroll = function(destination, offset) {
    $(this).click(function() {
      $("html, body").animate({
        scrollTop: $(destination).offset().top + offset
      }, 1200);
      return false;
    });
  }
  
  
  // fnSwapSignInLinks - This function will swap the dropdown sign in links (:hover) for plain text links in IE6 and below;
  $.fn.fnSwapSignInLinks = function() {
    $.each($.browser, function(i, val) {
      if(i == "msie" && $.browser.version.substr(0,3) < "7") {
        $("li.signIn","ul#headerLinks").remove().prev().removeClass("borderNone");
        $("ul#headerLinks").append('<li id="borrowersSignIn"><a rel="accountaccess" class="urchin" href="https://login.aessuccess.org/accountAccess/index.cfm?event=common.accountLogin" target="_blank">Borrowers Login</a></li>');
        $("ul#headerLinks").append('<li id="schoolsSignIn" class="borderNone"><a rel="accountaccess" class="urchin" href="https://callipygos.pheaa.org/portal/school/school_portal.cfm" target="_blank">Schools Login</a></li>');
      }
    });
  }
  
  
  // fnInputPlaceholder - This function will apply placeholder text to any input with a default value;
  $.fn.fnInputPlaceholder = function(d) {
    $(this).focus(function() {
      if(this.value == d) {
        this.value = "";
      }
    }).blur(function() {
      if(($.trim(this.value)) == "") {
        this.value = d;
      }
    });
  }
  
  
  // fnIWantTo - This function will create functionality for a dropdown menu;
  $.fn.fnIWantTo = function() {
    $(this).click(function(e) {
      e.stopPropagation();
      if($(this).find("ul").hasClass("hide")) {
        $(this).find("ul").removeClass("hide");
      } else {
        $(this).find("ul").addClass("hide");
      }
      $("html").click(function() {
        $("#iWantToDropdown").find("ul").addClass("hide").end();
      });
    });
  }
  
  
  // fnGetURLVars - This function returns an array of variables from the URL query string;
  $.fn.fnGetURLVars = function() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  }
  
  
  // fnGetURLVar - this function returns the value of a defined variable passed through the URL query string;
  $.fn.fnGetURLVar = function(v) {
    return $.fn.fnGetURLVars()[v];
  }
  
  
})(jQuery);

// Document ready function;
$(document).ready(pheaa.init);
