/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @return    The object (aka "this") that called hoverIntent, and the event object
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

//plugin
jQuery.fn.topLink = function(settings) {
		settings = jQuery.extend({
			min: 1,
			fadeSpeed: 200,
			ieOffset: 50
		}, settings);
		return this.each(function() {
			//listen for scroll
			var el = $(this);
			el.css('display','none'); //in case the user forgot
			$(window).scroll(function() {
				//stupid IE hack
				if(!jQuery.support.hrefNormalized) {
					el.css({
						'position': 'absolute',
						'top': $(window).scrollTop() + $(window).height() - settings.ieOffset
					});
				}
				if($(window).scrollTop() >= settings.min)
				{
					el.fadeIn(settings.fadeSpeed);
				}
				else
				{
					el.fadeOut(settings.fadeSpeed);
				}
			});
		});
	};




/* Smooth scrolling
   Changes links that link to other parts of this page to scroll
   smoothly to those links rather than jump to them directly, which
   can be a little disorienting.
   
   sil, http://www.kryogenix.org/
   
   v1.0 2003-11-11
   v1.1 2005-06-16 wrap it up in an object
*/

var ss = {
  fixAllLinks: function() {
    // Get a list of all links in the page
    var allLinks = document.getElementsByTagName('a');
    // Walk through the list
    for (var i=0;i<allLinks.length;i++) {
      var lnk = allLinks[i];
      if ((lnk.href && lnk.href.indexOf('#') != -1) && 
          ( (lnk.pathname == location.pathname) ||
	    ('/'+lnk.pathname == location.pathname) ) && 
          (lnk.search == location.search)) {
        // If the link is internal to the page (begins in #)
        // then attach the smoothScroll function as an onclick
        // event handler
        ss.addEvent(lnk,'click',ss.smoothScroll);
      }
    }
  },

  smoothScroll: function(e) {
    // This is an event handler; get the clicked on element,
    // in a cross-browser fashion
    if (window.event) {
      target = window.event.srcElement;
    } else if (e) {
      target = e.target;
    } else return;

    // Make sure that the target is an element, not a text node
    // within an element
    if (target.nodeName.toLowerCase() != 'a') {
      target = target.parentNode;
    }
  
    // Paranoia; check this is an A tag
    if (target.nodeName.toLowerCase() != 'a') return;
  
    // Find the <a name> tag corresponding to this href
    // First strip off the hash (first character)
    anchor = target.hash.substr(1);
    // Now loop all A tags until we find one with that name
    var allLinks = document.getElementsByTagName('a');
    var destinationLink = null;
    for (var i=0;i<allLinks.length;i++) {
      var lnk = allLinks[i];
      if (lnk.name && (lnk.name == anchor)) {
        destinationLink = lnk;
        break;
      }
    }
    if (!destinationLink) destinationLink = document.getElementById(anchor);

    // If we didn't find a destination, give up and let the browser do
    // its thing
    if (!destinationLink) return true;
  
    // Find the destination's position
    var destx = destinationLink.offsetLeft; 
    var desty = destinationLink.offsetTop;
    var thisNode = destinationLink;
    while (thisNode.offsetParent && 
          (thisNode.offsetParent != document.body)) {
      thisNode = thisNode.offsetParent;
      destx += thisNode.offsetLeft;
      desty += thisNode.offsetTop;
    }
  
    // Stop any current scrolling
    clearInterval(ss.INTERVAL);
  
    cypos = ss.getCurrentYPos();
  
    ss_stepsize = parseInt((desty-cypos)/ss.STEPS);
    ss.INTERVAL =
setInterval('ss.scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',10);
  
    // And stop the actual click happening
    if (window.event) {
      window.event.cancelBubble = true;
      window.event.returnValue = false;
    }
    if (e && e.preventDefault && e.stopPropagation) {
      e.preventDefault();
      e.stopPropagation();
    }
  },

  scrollWindow: function(scramount,dest,anchor) {
    wascypos = ss.getCurrentYPos();
    isAbove = (wascypos < dest);
    window.scrollTo(0,wascypos + scramount);
    iscypos = ss.getCurrentYPos();
    isAboveNow = (iscypos < dest);
    if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
      // if we've just scrolled past the destination, or
      // we haven't moved from the last scroll (i.e., we're at the
      // bottom of the page) then scroll exactly to the link
      window.scrollTo(0,dest);
      // cancel the repeating timer
      clearInterval(ss.INTERVAL);
      // and jump to the link directly so the URL's right
      location.hash = anchor;
    }
  },

  getCurrentYPos: function() {
    if (document.body && document.body.scrollTop)
      return document.body.scrollTop;
    if (document.documentElement && document.documentElement.scrollTop)
      return document.documentElement.scrollTop;
    if (window.pageYOffset)
      return window.pageYOffset;
    return 0;
  },

  addEvent: function(elm, evType, fn, useCapture) {
    // addEvent and removeEvent
    // cross-browser event handling for IE5+,  NS6 and Mozilla
    // By Scott Andrew
    if (elm.addEventListener){
      elm.addEventListener(evType, fn, useCapture);
      return true;
    } else if (elm.attachEvent){
      var r = elm.attachEvent("on"+evType, fn);
      return r;
    } else {
      alert("Handler could not be removed");
    }
  } 
}

ss.STEPS = 25;

ss.addEvent(window,"load",ss.fixAllLinks);


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



/*
	jQuery Text Resizer plugin.
	
	Author: Mario J Vargas (angstrey at hotmail dot com)
	Website: http://angstrey.com/
	Documentation: http://angstrey.com/index.php/projects/jquery-text-resizer-plugin/
	
	Version: 1.0
	Revision History:
		* 2009-09-03: Version 1.0. Initial Release
*/
(function($) {
	var DEBUG_MODE = false;
	
	$.fn.textresizer = function( options ) 
	{
	    if( DEBUG_MODE )
		    debug( this );
		
		// Stop plugin execution if no matched elements
		if( this.size() == 0 )
			return;

		// Default font sizes based on number of resize buttons.
		// "this" refers to current jQuery object
		var defaultSizes = buildDefaultFontSizes( this.size() );
	
		// Set up main options before element iteration
		var settings = $.extend( { selector: $(this).selector, sizes: defaultSizes, selectedIndex: -1 }, $.fn.textresizer.defaults, options );

		// Ensure that the number of defined sizes is suitable
		// for number of resize buttons.
		if( this.size() > settings.sizes.length )
		{
		    if( DEBUG_MODE )
		    {
			    debug( 
				    "ERROR: Number of defined sizes incompatible with number of buttons => elements: " + this.size() 
				    + "; defined sizes: " + settings.sizes.length
				    + "; target: " + settings.target );
            }
               			
			return;	// Stop execution of the plugin
		}

		loadPreviousState( settings );
	
		// Iterate and bind click event function to each element
		return this.each( function( i ) {
			var $this = $(this);	// Current resize button
		
			var currSizeValue = settings.sizes[ i ];	// Size corresponding to this resize button
			
			// Mark this button as active if necessary
			if( settings.selectedIndex == i )
				$(this).addClass( "textresizer-active" );
			
			// Apply the font size to target element when its 
			// corresponding resize button is clicked
			$this.bind( "click", { index: i }, function( e ) {		
				settings.selectedIndex = e.data.index;
				
				applyFontSize( currSizeValue, settings );
				saveState( currSizeValue, settings );

				markActive( this, settings );
			});
		});
	}
	
	// Default options of textresizer plugin
	$.fn.textresizer.defaults = {
		type  : "fontSize",	/* Available options: fontSize, css, cssClass */
		target: "body"		/* The HTML element to which the new font size will be applied */
	};

	function applyFontSize( newSize, settings )
	{
	    if( DEBUG_MODE )
		    debug( [ "target: " + settings.target, "newSize: " + newSize, "type: " + settings.type ].join( ", " ) );

		var targetElm = $( settings.target );
		switch( settings.type )
		{
			case "css":
				// Apply new inline CSS properties
				targetElm.css( newSize );
				break;

			case "cssClass":
				// Remove previously assigned CSS class from
				// target element. Iterating through matched
				// elements ensures the class is removed
				var cssClasses = settings.sizes;
				$.each( cssClasses, function( i, value ) {
					targetElm.each( function() {
						if( $(this).hasClass( value ) )
							$(this).removeClass( value );
					});
				});
				
				// Now apply the new CSS class
				targetElm.addClass( newSize );
				break;

			default:
				// Apply new font size
				targetElm.css( "font-size", newSize );
				break;
		}		
	}
	
	function markActive( sizeButton, settings )
	{
		// Deactivate previous button
		$(settings.selector).removeClass( "textresizer-active" );
		
		// Mark this button as active
		$(sizeButton).addClass( "textresizer-active" );
	}
	
	function buildCookieID( selector, target, prop )
	{
	    return "JQUERY.TEXTRESIZER[" + selector + "," + target + "]." + prop;
	}
	
	function getCookie( selector, target, prop )
	{
		var id = buildCookieID( selector, target, prop );
		
		var cookieValue = $.cookie( id );
		
		if( $.cookie( id + ".valueType" ) == "dict" && cookieValue )
		{
			var dict = {};
			var dictValues = cookieValue.split( "|" );
			
			for( var i = 0; i < dictValues.length; i++ )
			{
				// Separate key/value pair and assign to dictionary
				var keyValuePair = dictValues[ i ].split( "=" );
				dict[ keyValuePair[ 0 ] ] = unescape( keyValuePair[ 1 ] );
			}
			
			// Now that the object is finished, return it
			return dict;
		}
		
		return cookieValue;
    }
    
    function setCookie( selector, target, prop, value )
    {
		var id = buildCookieID( selector, target, prop );

		// Cookie expires in 1 year (365 days/year)
		var cookieOpts = { expires: 365, path: "/" };
		
		// Serialize value if it's an object
		if( typeof( value ) == "object" )
		{
		    // TODO: I think I wrote a JavaScript dictionary object serializer somewhere... Have to find it...
		    
			// Store type of value so we can convert it back 
			// to a dictionary object
			$.cookie( id + ".valueType", "dict", cookieOpts );

			var dict = value;	// (Assigning reference to variable dict for readability)
			var dictValues = new Array();
			for( var key in dict )
			{
				dictValues.push( key + "=" + escape( dict[ key ] ) );
			}

			var serializedVals = dictValues.join( "|" );
			$.cookie( id, serializedVals, cookieOpts );
			
			if( DEBUG_MODE )
			    debug( "In setCookie: Cookie: " + id + ": " + serializedVals );
		}
		else
		{
			$.cookie( id, value, cookieOpts );

            if( DEBUG_MODE )
			    debug( "In setCookie: Cookie: " + id + ": " + value );
		}
	}
	
	function loadPreviousState( settings )
	{
		// Determine if jquery.cookie is installed
		if( $.cookie )
		{
		    if( DEBUG_MODE )
			    debug( "In loadPreviousState(): jquery.cookie: INSTALLED" );

			var selectedIndex = getCookie( settings.selector, settings.target, "selectedIndex" );
			if( DEBUG_MODE )
			    debug( "In loadPreviousState: selectedIndex: " + selectedIndex + "; type: " + typeof(selectedIndex) );
			if( selectedIndex )
				settings.selectedIndex = selectedIndex;

			var prevSize = getCookie( settings.selector, settings.target, "size" );
			if( DEBUG_MODE )
			    debug( "In loadPreviousState: prevSize: " + prevSize + "; type: " + typeof(prevSize) );
			if( prevSize )
				applyFontSize( prevSize, settings );
		}
		else
		{
		    if( DEBUG_MODE )
			    debug( "In loadPreviousState(): jquery.cookie: NOT INSTALLED" );
		}
	}
	
	function saveState( newSize, settings )
	{
		// Determine if jquery.cookie is installed
		if( $.cookie )
		{
			if( DEBUG_MODE )
			    debug( "In saveState(): jquery.cookie: INSTALLED" );
			
			setCookie( settings.selector, settings.target, "size", newSize );
			setCookie( settings.selector, settings.target, "selectedIndex", settings.selectedIndex );
		}
		else
		{
			if( DEBUG_MODE )
			    debug( "In saveState(): jquery.cookie: NOT INSTALLED" );
		}
	}
	
	function debug( $obj )
	{
		if( window.console && window.console.log )
		{
			if( typeof( $obj ) == "string" )
				window.console.log( "jquery.textresizer => " + $obj );
			else	// Assumes $obj is jQuery object
				window.console.log( "jquery.textresizer => selection count: " + $obj.size() );
		}
	}
	
	function buildDefaultFontSizes( numElms )
	{
		var size0 = 8;				/* Initial size, measured in pixels */
		
		var mySizes = new Array();
		
		if( DEBUG_MODE )
		    debug( "In buildDefaultFontSizes: numElms = " + numElms );
		
		if( DEBUG_MODE )
		{
		    for( var i = 0; i < numElms; i++ )
		    {
			    // Append elements in increments of 2 units
			    var value = (size0 + (i * 2)) / 10;
			    mySizes.push( value + "em" );	
    			
			    if( DEBUG_MODE )
			        debug( "In buildDefaultFontSizes: mySizes[" + i + "] = " + mySizes[ i ] );
		    }
		}
		else
		{
		    for( var i = 0; i < numElms; i++ )
		    {
			    // Append elements in increments of 2 units
			    var value = (size0 + (i * 2)) / 10;
			    mySizes.push( value + "em" );	
		    }
		}
		
		return mySizes;
	}
})(jQuery);

//Plugin Style Switcher//

(function($){
    $.fn.switcher = function(options){
        var def_cookie;
        $('link').each(function(){	
            if($(this).attr('title') != undefined){
                if ($(this).attr('title').length != 0){
                    def_cookie = $(this).attr('title');
                    return false;
                }	
            }
        });
        var cookie = jQuery.cookie('jquery_default_stylesheet');
        if(cookie == null){
            chooser(this,def_cookie);
        }
        else{
            chooser(this,cookie);
        }
        clicker(this);
    };

    function clicker($obj){
        $('#' + $obj.attr('id') + ' a').click(function(){
            var target = $(this).attr('href').substring(1,$(this).attr('href').length);
            chooser($obj,target);
            return false;
        });	
    };

    function chooser($obj,$target){
        $('link').each(function(){	
            if($(this).attr('title') != undefined){
                if ($(this).attr('title').length != 0) {
                    $stylesheet = $(this);
                    $stylesheet.attr('disabled', true);
                    $('#' + $obj.attr('id') + ' a[href!=#' + $target + ']').removeClass('on');
                    if ($stylesheet.attr('title') == $target) {
                        $stylesheet.attr('disabled', false);
                        $.cookie('jquery_default_stylesheet', $target, {
                            expires: 365,
                            path: '/'
                        });
                        $('#' + $obj.attr('id') + ' a[href=#' + $target + ']').addClass("on");
                    }
                }
            }
        });

    };
})(jQuery);
