// remap jQuery to $
(function($){

  // Recreate $.post with 'error' callback
  $.post = function( url, data, callback, type ) {
		if ( jQuery.isFunction( data ) || (data != null && (jQuery.isFunction( data.success ) || jQuery.isFunction( data.error ))) ) {
			type = type || callback;
      callback = data;
			data = {};
		}
    settings = {
			type: "POST",
			url: url,
			data: data,
			dataType: type
		};
    if ( jQuery.isFunction( callback ) ) {
      settings.success = callback;
    } else {
      if ( jQuery.isFunction( callback.success ) ) {
        settings.success = callback.success;
      }
      if ( jQuery.isFunction( callback.error ) ) {
        settings.error = callback.error;
      }
    }

		return jQuery.ajax(settings);
	}
  // Recreate $.get with 'error' callback
  $.get = function( url, data, callback, type ) {
		if ( jQuery.isFunction( data ) || (data != null && (jQuery.isFunction( data.success ) || jQuery.isFunction( data.error ))) ) {
			type = type || callback;
      callback = data;
			data = null;
		}
    settings = {
			type: "GET",
			url: url,
			data: data,
			dataType: type
		};
    if ( jQuery.isFunction( callback ) ) {
      settings.success = callback;
    } else {
      if ( jQuery.isFunction( callback.success ) ) {
        settings.success = callback.success;
      }
      if ( jQuery.isFunction( callback.error ) ) {
        settings.error = callback.error;
      }
    }

		return jQuery.ajax(settings);
  };

  // Create missing postJSON function
  $.postJSON = function(url, data, callback) {

    // Force disable jQuery cache setting
    var cache = jQuery.ajaxSettings.cache; jQuery.ajaxSettings.cache = false;

    $.post(url, data, callback, "json");

    // Restore jQuery caching setting
    jQuery.ajaxSettings.cache = cache;
  };

  // Superfish 1.4.8 minified, with slight modification to hideSuperfishUl
  $.fn.superfish=function(k){var g=$.fn.superfish,j=g.c,f=$(['<span class="',j.arrowClass,'"> &#187;</span>'].join("")),i=function(){var c=$(this),l=d(c);clearTimeout(l.sfTimer);c.showSuperfishUl().siblings().hideSuperfishUl()},e=function(){var c=$(this),m=d(c),l=g.op;clearTimeout(m.sfTimer);m.sfTimer=setTimeout(function(){l.retainPath=($.inArray(c[0],l.$path)>-1);c.hideSuperfishUl();if(l.$path.length&&c.parents(["li.",l.hoverClass].join("")).length<1){i.call(l.$path)}},l.delay)},d=function(c){var l=c.parents(["ul.",j.menuClass,":first"].join(""))[0];g.op=g.o[l.serial];return l},h=function(c){c.addClass(j.anchorClass).append(f.clone())};return this.each(function(){var c=this.serial=g.o.length;var m=$.extend({},g.defaults,k);m.$path=$("li."+m.pathClass,this).slice(0,m.pathLevels).each(function(){$(this).addClass([m.hoverClass,j.bcClass].join(" ")).filter("li:has(ul)").removeClass(m.pathClass)});g.o[c]=g.op=m;$("li:has(ul)",this)[($.fn.hoverIntent&&!m.disableHI)?"hoverIntent":"hover"](i,e).each(function(){if(m.autoArrows){h($(">a:first-child",this))}}).not("."+j.bcClass).hideSuperfishUl();var l=$("a",this);l.each(function(n){var o=l.eq(n).parents("li");l.eq(n).focus(function(){i.call(o)}).blur(function(){e.call(o)})});m.onInit.call(this)}).each(function(){var c=[j.menuClass];if(g.op.dropShadows&&!($.browser.msie&&$.browser.version<7)){c.push(j.shadowClass)}$(this).addClass(c.join(" "))})};var a=$.fn.superfish;a.o=[];a.op={};a.IE7fix=function(){var c=a.op;if($.browser.msie&&$.browser.version>6&&c.dropShadows&&c.animation.opacity!=undefined){this.toggleClass(a.c.shadowClass+"-off")}};a.c={bcClass:"sf-breadcrumb",menuClass:"sf-js-enabled",anchorClass:"sf-with-ul",arrowClass:"sf-sub-indicator",shadowClass:"sf-shadow"};a.defaults={hoverClass:"sfHover",pathClass:"overideThisToUse",pathLevels:1,delay:800,animation:{opacity:"show"},speed:"normal",autoArrows:true,dropShadows:true,disableHI:false,onInit:function(){},onBeforeShow:function(){},onShow:function(){},onHide:function(){}};$.fn.extend({hideSuperfishUl:function(){var e=a.op,d=(e.retainPath===true)?e.$path:"";e.retainPath=false;var c=$(["li.",e.hoverClass].join(""),this).add(this).not(d).removeClass(e.hoverClass).find(">ul");if (!c.hasClass('sfIgnore')) {c.hide().css("visibility","hidden");e.onHide.call(c);}return this},showSuperfishUl:function(){var e=a.op,d=a.c.shadowClass+"-off",c=this.addClass(e.hoverClass).find(">ul:hidden").css("visibility","visible");a.IE7fix.call(c);e.onBeforeShow.call(c);c.animate(e.animation,e.speed,function(){a.IE7fix.call(c);e.onShow.call(c)});return this}});
  // jquery.cookie
  $.cookie=function(b,j,m){if(typeof j!="undefined"){m=m||{};if(j===null){j="";m.expires=-1}var e="";if(m.expires&&(typeof m.expires=="number"||m.expires.toUTCString)){var f;if(typeof m.expires=="number"){f=new Date();f.setTime(f.getTime()+(m.expires*24*60*60*1000))}else{f=m.expires}e="; expires="+f.toUTCString()}var l=m.path?"; path="+(m.path):"";var g=m.domain?"; domain="+(m.domain):"";var a=m.secure?"; secure":"";document.cookie=[b,"=",encodeURIComponent(j),e,l,g,a].join("");return true}else{var d=null;if(document.cookie&&document.cookie!==""){var k=document.cookie.split(";");for(var h=0;h<k.length;h++){var c=$.trim(k[h]);if(c.substring(0,b.length+1)==(b+"=")){d=decodeURIComponent(c.substring(b.length+1));break}}}return d}};
  // this is a small helper extension i stole from
  // http://www.texotela.co.uk/code/jquery/reverse/
  // it merely reverses the order of a jQuery set.
  // Used to restore order of elements removed by prevAll
  $.fn.reverse = function() { return this.pushStack(this.get().reverse(), arguments); };

  // Document ready jquery
$(document).ready(function() {
$('.acc_container').hide(); //Hide/close all containers
//$('.acc_trigger:first').addClass('active').next().show(); //Add "active" class to first trigger, then show/open the immediate next container

//On Click
$('.acc_trigger').click(function(){
	$(this).toggleClass("active").next().slideToggle("fast");//Toggle the active class and slide in the appropriate way
	return false; //Prevent the browser jump to the link anchor
});

$('.news_container').hide(); //Hide/close all containers
$('.news_trigger:first').addClass('active').next().show(); //Add "active" class to first trigger, then show/open the immediate next container

//On Click
$('.news_trigger').click(function(){
	if( $(this).next().is(':hidden') ) { //If immediate next container is closed...
		$('.news_trigger').removeClass('active').next().slideUp(); //Remove all "active" state and slide up the immediate next container
		$(this).toggleClass('active').next().slideDown(); //Add "active" state to clicked trigger and slide down the immediate next container
	}
	return false; //Prevent the browser jump to the link anchor
});


//Handle contribution methods
$('.cont_container').hide(); //Hide/close all containers
//$('.news_trigger:first').addClass('active').next().show(); //Add "active" class to first trigger, then show/open the immediate next container

//On Click
$('.cont_trigger').click(function(){
	if( $(this).next().is(':hidden') ) { //If immediate next container is closed...
		$('.cont_trigger').removeClass('active').next().slideUp(); //Remove all "active" state and slide up the immediate next container
		$(this).toggleClass('active').next().slideDown(); //Add "active" state to clicked trigger and slide down the immediate next container
	}
	return false; //Prevent the browser jump to the link anchor
});

  // Superfish
  $('#mainnav > ul').addClass('sf-menu').find('ul ul').addClass('sfIgnore').end().superfish({
    pathClass:    'sfBreadcrumb', /* class applied to list items leading to current page */
    autoArrows:   false,
    dropShadows:  false
  });

  // Homepage slides
  if ($('body').is('.home')) {
    // Isolate slider components
    var slideContainer = $('#slides .wrap'),
        slideList = $('#slides .wrap ul:not(#switch,.account) li').each(function(idx){ this.id = 'slide'+idx; }),
        triggers = $('<ul id="switch"/>'),
        timer = false;
    slideList.each(function(idx){
      var img = $('img',this)[0],
          thumb1 = $('<img/>').attr({
            src: img.src.replace(/homepage/,'homepage/thumbs'),
            width: '80',
            height: '30',
            alt: img.alt
          }),
          thumb2 = thumb1.clone().attr({
            src: thumb1[0].src.replace(/.aspx/,'_hover.aspx')
          }).hide();
      triggers.append($('<li id="trigger'+idx+'"/>').prepend('<span>'+img.alt+'</span>').append(thumb1).append(thumb2));
    });
    triggers.appendTo(slideContainer.parent());
    var triggerList = $('li',triggers).each(function(idx){
      this.id = 'trigger'+idx;
      var tgt = $(this),
          img1 = tgt.find('img:first'),
          img2 = tgt.find('img:last');
      tgt.bind('up',function(){
        img1.hide(); img2.show();
      }).bind('down',function(){
        img2.hide(); img1.show();
      }).hover(function(){
        tgt.addClass('hover').trigger('up');
      },function(){
        tgt.removeClass('hover');
        if (tgt.is(':not(.curr)')) { tgt.trigger('down'); }
      });
    });

    // Create rotation listener
    slideContainer.bind('rotate',function(event){
      var idx = $(this).data('index'),
          trigger = $('#trigger'+idx),
          slide = $('#slide'+idx);
      slideContainer.data('index',triggerList.index(trigger)); // Update index
      triggerList.trigger('down').removeClass('curr').filter(trigger).trigger('up').addClass('curr'); // Highlight trigger
      slide.parent().stop().animate({top:'-='+slide.position().top+'px'},1000,function(){
        var move = slide.prevAll().remove().reverse(); // Must use 'reverse' to restore order after prevAll
        $(this).css({top:0}).append(move); // Append removed slides to end
      });
    })
    // Stop animation when mouse is over image
    .mouseover(function(){
      clearInterval(timer); timer = false;
    })
    // Re-start animation when mouse leaves image
    .mouseleave(function(){
      autoRotate();
    });

    // Create rotation timer
    autoRotate = function(){
      if (!timer) {
        timer = setInterval(function(){
          var idx = slideContainer.data('index') || 0;
          slideContainer.data('index',(idx < slideList.length-1 ? idx+1 : 0)).trigger('rotate');
        },10000);
      }
    }

    // Set up triggers to stop auto-rotate and go to specific slide
    triggerList.each(function(idx){
      $(this).click(function(e){
        e.preventDefault();
        slideContainer.data('index',idx).trigger('rotate');
      });
    });

    // Highlight first trigger as current
    $(triggerList[0]).addClass('curr').trigger('up');

    // Start timer to auto-rotate slides
    autoRotate();
  }

  // Page 'Alert' message
  if ($('#alert-message').length>0) {
    var alertmsg = $('#alert-message')
    // Remove alert if user has hidden it previously
    if ($.cookie('hideMessage') == 'true') {
      alertmsg.remove();
    }
    // Append 'hide' link so user can hide message
    else {
      $('<a class="alertx">Hide This Message <span>[x]</span></a>').
      appendTo(alertmsg)
      .click(function(e){
        e.preventDefault();
        alertmsg.animate({bottom:'-='+alertmsg.height()},750,function(){
          alertmsg.remove();
          $.cookie('hideMessage', 'true', { expires: null, path: '/' });
        })
      });
    }
  }
  // Add Font size, print, email links (only on subpages)
  if (!$('body').is('.home')) {
    // Create function to change font size
    var updateFont = function(val){
          if (typeof val == 'undefined') { val = 'font1'; }
          $('body').removeClass('font1 font2 font3').addClass(val);
          $.cookie('fontSize', val, { path: '/' });
          Cufon.refresh();
        };
    // Check for cookie and update page font size as req'd
    if ($.cookie('fontSize')!==null) {
      updateFont($.cookie('fontSize'));
    }
    // Add links to email/print page, and update font size
    var pageActions = $('<ul id="pageActions"/>').prependTo('#sidebar'),
        emlPage = $('<li><a>E-mail</a></li>').appendTo(pageActions),
        printPage = $('<li><a>Print</a></li>').appendTo(pageActions),
        fontSize = $('<li><a class="font1">A</a><a class="font2">A</a><a class="font3">A</a></li>').appendTo(pageActions);
    // Assign print action
    $('a',printPage).click(function(e){
      e.preventDefault();
      window.print();
    });
    // Assign font size link actions
    $('a',fontSize).click(function(e){
      e.preventDefault();
      updateFont(this.className);
    });
    //Assign email link actions
    $('a', emlPage).click(function(e){
      window.location = "mailto:"+"?subject=I thought this link might interest you." + "&body="+document.title+"  "+window.location;
  });
  }
  
  if ($('#graphinfo').length > 0) {
      // Save defaults
      var graphinfo = $('#graphinfo');
      graphinfo.data('defaults',{
        //title: $('#graphinfo .graph h4').text(),
        img: $('#graphinfo .graph img').attr('src')
      });
      var source = $(location).attr('href').replace('.aspx', '/');
      // Detect change and perform actions
      $('#change-graph select').change(function(){
        var selVal = $(this).val(),
            tgt = {
              //title: $('#graphinfo .graph h4'),
              img: $('#graphinfo .graph img')
            };
        switch (selVal) {
          case ('0-3'):
	   //tgt.title.text(graphinfo.data('defaults').title);
            //tgt.title.text(tgt.title.text()+': Age '+selVal);
            tgt.img.attr('src', source +'0-3.aspx');
            break;
	  case ('4-6'):
	   //tgt.title.text(graphinfo.data('defaults').title);
            //tgt.title.text(tgt.title.text()+': Age '+selVal);
            tgt.img.attr('src',source +'4-6.aspx');
            break;
	    case ('7-9'):
	    //tgt.title.text(graphinfo.data('defaults').title);
            //tgt.title.text(tgt.title.text()+': Age '+selVal);
            tgt.img.attr('src',source +'7-9.aspx');
            break;
	    case ('10-12'):
	    //tgt.title.text(graphinfo.data('defaults').title);
            //tgt.title.text(tgt.title.text()+': Age '+selVal);
            tgt.img.attr('src',source +'10-12.aspx');
            break;
	    case ('13-15'):
	    //tgt.title.text(graphinfo.data('defaults').title);
            //tgt.title.text(tgt.title.text()+': Age '+selVal);
            tgt.img.attr('src',source +'13-15.aspx');
            break;
	    case ('16-18'):
	    //tgt.title.text(graphinfo.data('defaults').title);
            //tgt.title.text(tgt.title.text()+': Age '+selVal);
            tgt.img.attr('src',source +'16-18.aspx');
            break;
	    case ('19+'):
	    //tgt.title.text(graphinfo.data('defaults').title);
            //tgt.title.text(tgt.title.text()+': Age '+selVal + ' or College Enrolled');
            tgt.img.attr('src',source +'19.aspx');
            break;
          default:
            tgt.title.text(graphinfo.data('defaults').title);
            tgt.img.attr('src',graphinfo.data('defaults').img);
            break;
        }
      });
    }
    
// Handle 'explore your options' jump list
    if ($('.explore-options,.explore-options-mini').length > 0) {
      // Detect change and perform actions
      $('.explore-options,.explore-options-mini').find('select').change(function(){
        var selVal = $(this).val();
        switch (selVal) {
          case ('Option 1'):
            window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/Public-Treasurers-Investment-Fund.aspx'
            break;
	    case ('Option 2'):
            window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/Age-Based-Growth.aspx'
            break;
	    case ('Option 3'):
            window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/Option-3.aspx'
            break;
	    case ('Option 4'):
            window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/Institutional-Index-Fund.aspx'
            break;
	    case ('Option 5'):
            window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/Total-Bond-Market-Index-Fund.aspx'
            break;
	    case ('Option 6'):
            window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/Equities-10-Total-International.aspx'
            break;
	    case ('Option 7'):
            window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/Age-Based-Aggressive-Growth.aspx'
            break;
	    case ('Option 8'):
            window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/Age-Based-Moderate.aspx'
            break;
	    case ('Option 9'):
            window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/Age-Based-Conservative.aspx'
            break;
	    case ('Option 10'):
            window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/Equities-30-Developed-International.aspx'
            break;
	    case ('Option 11'):
            window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/FDIC-Insured-Savings.aspx'
            break;
	    case ('Option 12'):
            window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/Customized-Static.aspx'
            break;
	    case ('Option 13'):
	    window.location.href = 'http://www.uesp.org/Investment-Info/Investment-Options/Customized-Age-Based.aspx'
          default:
            break;
        }
      });
    }
   
  
  });
  
})(this.jQuery);



// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};
