/* global scripts go here */

/*****  used to show or not show the special logo to the left of the csuc signature */
function showSpecialLogo() {
    $('#header #special').html("<a href='http://www.csuchico.edu/125/'><img src='http://www.csuchico.edu/125/_assets/images/125-logo.jpg' alt='125 logo, click to go to the 125th anniversary website' height='89' /></a>");
}

function rotatingContent(_sel) {
  /* TODO: the hope is that this hides all images before loading to make it less jarring of a UEX;
       This method should be tested further, though. It would be nice to not load the images at all */
  $(_sel).find('img').css({
    display: 'none'
  });

  /* this assumes a document higherarchy of 'div.rotating-content > div > content' */
  showSingleChild($(_sel));
}

// helper for rotatingContent()


function showSingleChild(_sel) {
  $(_sel).each(function (i, obj) {
    $(obj).children().hide()
    var r = Math.ceil(Math.random() * $(obj).children().length)
    $(obj).children(':nth-child(' + r + ')').css({
      'visibility': 'visible'
    })
    $(obj).children(':nth-child(' + r + ')').css({
      'display': 'block'
    })
    $(obj).children(':nth-child(' + r + ')').find('img').show()
  })
}

// search box clearing


function searchBox(boxid) {
  if (boxid) {
    var searchbox = boxid.find("input[type=text]");
    var searchbox_value = $(searchbox).attr("value");
    $(searchbox).bind({
      focus: function () {
        if (escape($(this).attr('value')) == escape(searchbox_value)) {
          $(this).attr({
            value: ""
          });
        }
      },
      blur: function () {
        if ($(this).attr("value") == '') {
          $(this).attr({
            value: searchbox_value
          });
        }
      }
    });
  }
}

// Drop Downify Function
// This function takes the string of an ID of a UL and adds
// a mouseover event to add the "over" 


function dropDownify(str) {
  if ($.browser.msie && $.browser.version == "6.0") {
    if (str) {
      str.children().each(function () {
        $(this).bind('mouseenter mouseleave', function () {
          $(this).toggleClass('over');
        })
      });
    }
  }
}


// It's the light switch!
;
(function ($) {
  $.fn.lightswitch = function ($options) {
    // bring the options to the phototour object
    for (var i in $options) {
      $.lightswitch[i] = $options[i];
    }

    $(this).css({
      'position': 'relative',
      // won't work without explicit position type
      'background-color': '#fff',
      'display': 'block',
      'z-index': '20'
    })

    var overlay = $(document.createElement('div')).attr('id', 'lb-bg').css({
      'background-color': '#000',
      'filter': 'alpha(opacity=85)',
      '-moz-opacity': '0.85',
      'opacity': '0.85',
      'height': '100%',
      'width': '100%',
      'position': 'fixed',
      'top': '0',
      'left': '0',
      'z-index': '15'
    });
    $('body').prepend(overlay);
    $(overlay).hide() // initially hidden
    $($.lightswitch.flipper).bind('click', function () {
      if ($('#lb-bg').is(':hidden')) {
        $("div#lb-bg:hidden:first").fadeIn("slow");
        $(this).addClass('raise')
        $(this).removeClass('dim')
        return false;
      } else {
        $("div#lb-bg").fadeOut("slow");
        $(this).addClass('dim')
        $(this).removeClass('raise')
        return false;
      }
    });
  };
  $.extend({
    lightswitch: {
      current: ''
    }
  });

  // it's the lightbox!
  $.fn.lightbox = function ($options) {
    // bring the options to the lightbox object
    for (var i in $options) {
      $.lightbox[i] = $options[i];
    }
    if (!$('#lb-bg').length) { // might be there already
      var overlay = $(document.createElement('div')).attr('id', 'lb-bg').css({
        'background-color': '#000',
        'filter': 'alpha(opacity=85)',
        '-moz-opacity': '0.85',
        'opacity': '0.85',
        'height': '100%',
        'width': '100%',
        'position': 'fixed',
        'top': '0',
        'left': '0',
        'z-index': '15'
      });
      $('body').prepend(overlay);
      $(overlay).hide() // initially hidden
    }
    var wrapper = $(document.createElement('div')).css({
      'width': '100%',
      'position': 'absolute',
      'top': '0',
      'left': '0',
      'z-index': '16'
    });
    $($.lightbox.container).wrap(wrapper);
    $($.lightbox.container).addClass('pkg');
    $($.lightbox.container).hide();

    // Bind the event
    $(this).bind('click', function () {
      $.lightbox.show()
      return false;
    });
    $($.lightbox.container).find('.close').each(function (i, item) {
      $(item).bind('click', function () {
        $.lightbox.hide();
        return false;
      });
    });
    // everyone likes keyboard shortcuts
    $(document).bind('keydown', function (e) {
      // key codes - C:67 X:88 esc:27
      if (e.which == 67 || e.which == 88 || e.which == 27) {
        $.lightbox.hide()
      }
    });
  };

  // getPageScroll() by quirksmode.com


  function ___getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) { // all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    arrayPageScroll = new Array(xScroll, yScroll);
    return arrayPageScroll;
  };

  $.extend({
    lightbox: {
      container: '',
      show: function () {
        if ($('#lb-bg').is(':hidden')) {
          var arr_scroll = ___getPageScroll();
          $($.lightbox.container).parent().css({
            top: arr_scroll[1] + 75 // 75 px from the top no matter what
            // left: arrPageScroll[0]
          });

          $('div#lb-bg').fadeIn('slow');
          $($.lightbox.container).fadeIn('slow')
        }
      },
      hide: function () {
        if ($('#lb-bg').is(':visible')) {
          $('div#lb-bg').fadeOut('slow');
          $($.lightbox.container).fadeOut('slow')
        }
      }
    }
  });


  /* Callout
        This is only (at the time of writing) used on the home page, but it's extensible enought to be reused */
  $.fn.callout = function ($options) {
    for (var i in $options) {
      $.callout[i] = $options[i];
    }

    $(this).css({
      'position': 'relative'
    })

    var black = $(document.createElement('div')).attr('class', 'black_callout');
    var white = $(document.createElement('div')).attr('class', 'white_callout');

    $($.callout.flyout).wrap(black).wrap(white);
    $.callout.flyout = $('.black_callout');
    $($.callout.flyout).hide();


    $(this).bind('click', function () {
      if ($($.callout.flyout).is(':hidden')) {
        $($.callout.flyout).fadeIn("fast");
        $(document).bind('click', function () {
          $($.callout.flyout).fadeOut("fast");
          $(document).unbind('click');
        });
        return false;
      } else {
        $($.callout.flyout).fadeOut("fast");
        return false;
      }
    });
    $('#close').bind('click', function () {
      $($.callout.flyout).fadeOut("fast");
      return false;
    });
  };
  $.extend({
    callout: {
      flyout: '#callout'
    }
  });


  /**
   * jQuery (PNG Fix) v1.2
   * Microsoft Internet Explorer 24bit PNG Fix
   *
   * The MIT License
   * 
   * Copyright (c) 2007 Paul Campbell (pauljamescampbell.co.uk)
   * 
   **/

  $.fn.pngfix = function (options) {

    // Review the Microsoft IE developer library for AlphaImageLoader reference 
    // http://msdn2.microsoft.com/en-us/library/ms532969(VS.85).aspx
    // ECMA scope fix
    var elements = this;
    var settings = $.extend({
      imageFixSrc: false,
      sizingMethod: false
    },
    options);

    if (!$.browser.msie || ($.browser.msie && $.browser.version >= 7)) {
      return (elements);
    }

    function setFilter(el, path, mode) {
      var fs = el.attr("filters");
      var alpha = "DXImageTransform.Microsoft.AlphaImageLoader";
      if (fs[alpha]) {
        fs[alpha].enabled = true;
        fs[alpha].src = path;
        fs[alpha].sizingMethod = mode;
      } else {
        el.css("filter", 'progid:' + alpha + '(enabled="true", sizingMethod="' + mode + '", src="' + path + '")');
      }
    }

    function setDOMElementWidth(el) {
      if (el.css("width") == "auto" & el.css("height") == "auto") {
        el.css("width", el.attr("offsetWidth") + "px");
      }
    }

    return (
    elements.each(function () {

      // Scope
      var el = $(this);

      if (el.attr("tagName").toUpperCase() == "IMG" && (/\.png/i).test(el.attr("src"))) {
        if (!settings.imageFixSrc) {

          // Wrap the <img> in a <span> then apply style/filters, 
          // removing the <img> tag from the final render 
          el.wrap("<span></span>");
          var par = el.parent();
          par.css({
            height: el.height(),
            width: el.width(),
            display: "inline-block"
          });
          setFilter(par, el.attr("src"), "scale");
          el.remove();
        } else if ((/\.gif/i).test(settings.imageFixSrc)) {

          // Replace the current image with a transparent GIF
          // and apply the filter to the background of the 
          // <img> tag (not the preferred route)
          setDOMElementWidth(el);
          setFilter(el, el.attr("src"), "image");
          el.attr("src", settings.imageFixSrc);
        }

      } else {
        var bg = new String(el.css("backgroundImage"));
        var matches = bg.match(/^url\("(.*)"\)$/);
        if (matches && matches.length) {

          // Elements with a PNG as a backgroundImage have the
          // filter applied with a sizing method relevant to the 
          // background repeat type
          setDOMElementWidth(el);
          el.css("backgroundImage", "none");

          // Restrict scaling methods to valid MSDN defintions (or one custom)
          var sc = "crop";
          if (settings.sizingMethod) {
            sc = settings.sizingMethod;
          }
          setFilter(el, matches[1], sc);

          // Fix IE peek-a-boo bug for internal links
          // within that DOM element
          el.find("a").each(function () {
            $(this).css("position", "relative");
          });
        }
      }

    }));
  }



  /**
   * jQuery.timers - Timer abstractions for jQuery
   * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
   * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
   * Date: 2009/10/16
   *
   * @author Blair Mitchelmore
   * @version 1.2
   *
   **/

  jQuery.fn.extend({
    everyTime: function (interval, label, fn, times) {
      return this.each(function () {
        jQuery.timer.add(this, interval, label, fn, times);
      });
    },
    oneTime: function (interval, label, fn) {
      return this.each(function () {
        jQuery.timer.add(this, interval, label, fn, 1);
      });
    },
    stopTime: function (label, fn) {
      return this.each(function () {
        jQuery.timer.remove(this, label, fn);
      });
    }
  });

  jQuery.extend({
    timer: {
      global: [],
      guid: 1,
      dataKey: "jQuery.timer",
      regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
      powers: {
        // Yeah this is major overkill...
        'ms': 1,
        'cs': 10,
        'ds': 100,
        's': 1000,
        'das': 10000,
        'hs': 100000,
        'ks': 1000000
      },
      timeParse: function (value) {
        if (value == undefined || value == null) return null;
        var result = this.regex.exec(jQuery.trim(value.toString()));
        if (result[2]) {
          var num = parseFloat(result[1]);
          var mult = this.powers[result[2]] || 1;
          return num * mult;
        } else {
          return value;
        }
      },
      add: function (element, interval, label, fn, times) {
        var counter = 0;

        if (jQuery.isFunction(label)) {
          if (!times) times = fn;
          fn = label;
          label = interval;
        }

        interval = jQuery.timer.timeParse(interval);

        if (typeof interval != 'number' || isNaN(interval) || interval < 0) return;

        if (typeof times != 'number' || isNaN(times) || times < 0) times = 0;

        times = times || 0;

        var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});

        if (!timers[label]) timers[label] = {};

        fn.timerID = fn.timerID || this.guid++;

        var handler = function () {
          if ((++counter > times && times !== 0) || fn.call(element, counter) === false) jQuery.timer.remove(element, label, fn);
        };

        handler.timerID = fn.timerID;

        if (!timers[label][fn.timerID]) timers[label][fn.timerID] = window.setInterval(handler, interval);

        this.global.push(element);

      },
      remove: function (element, label, fn) {
        var timers = jQuery.data(element, this.dataKey),
          ret;

        if (timers) {

          if (!label) {
            for (label in timers)
            this.remove(element, label, fn);
          } else if (timers[label]) {
            if (fn) {
              if (fn.timerID) {
                window.clearInterval(timers[label][fn.timerID]);
                delete timers[label][fn.timerID];
              }
            } else {
              for (var fn in timers[label]) {
                window.clearInterval(timers[label][fn]);
                delete timers[label][fn];
              }
            }

            for (ret in timers[label]) break;
            if (!ret) {
              ret = null;
              delete timers[label];
            }
          }

          for (ret in timers) break;
          if (!ret) jQuery.removeData(element, this.dataKey);
        }
      }
    }
  });

  jQuery(window).bind("unload", function () {
    jQuery.each(jQuery.timer.global, function (index, item) {
      jQuery.timer.remove(item);
    });
  });


})(jQuery);

