/*
 * wac.library 1.2
 *
 * contains all jquery plugins and extensions used by web-à-la-carte core components
 *
 * requires jquery 1.2.1 or above
 *
 * 
*/ 

/*------------------------------------------------------------------------------------------------------------------
 *
 * core technologies
 *
 *------------------------------------------------------------------------------------------------------------------*/
/* jquery.hoverIntent.js
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
*	interval: 50,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 100,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @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) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			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; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);

/* jquery.dimensions.js
 *
 * Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-09-11 02:38:31 +0000 (Tue, 11 Sep 2007) $
 * $Rev: 3238 $
 *
*/

(function($){
	
$.dimensions = {
	version: '@VERSION'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
	
	// innerHeight and innerWidth
	$.fn[ 'inner' + name ] = function() {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		return this[ name.toLowerCase() ]() + num(this, 'padding' + torl) + num(this, 'padding' + borr);
	};
	
	// outerHeight and outerWidth
	$.fn[ 'outer' + name ] = function(options) {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		options = $.extend({ margin: false }, options || {});
		
		return this[ name.toLowerCase() ]()
				+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
				+ num(this, 'padding' + torl) + num(this, 'padding' + borr)
				+ (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
	};
});

// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
	$.fn[ 'scroll' + name ] = function(val) {
		if (!this[0]) return;
		
		return val != undefined ?
		
			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo( 
						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
					) :
					this[ 'scroll' + name ] = val;
			}) :
			
			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
					$.boxModel && document.documentElement[ 'scroll' + name ] ||
					document.body[ 'scroll' + name ] :
				this[0][ 'scroll' + name ];
	};
});

$.fn.extend({
	position: function() {
		var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
		
		if (elem) {
			// Get *real* offsetParent
			offsetParent = this.offsetParent();
			
			// Get correct offsets
			offset       = this.offset();
			parentOffset = offsetParent.offset();
			
			// Subtract element margins
			offset.top  -= num(elem, 'marginTop');
			offset.left -= num(elem, 'marginLeft');
			
			// Add offsetParent borders
			parentOffset.top  += num(offsetParent, 'borderTopWidth');
			parentOffset.left += num(offsetParent, 'borderLeftWidth');
			
			// Subtract the two offsets
			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}
		
		return results;
	},
	
	offsetParent: function() {
		var offsetParent = this[0].offsetParent;
		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return $(offsetParent);
	}
});

var num = function(el, prop) {
	return parseInt($.css(el.jquery?el[0]:el,prop))||0;
};

})(jQuery);

/* jquery.cookie.js
 * 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 Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built In easIng capabilities added In jQuery 1.1
 * to offer multiple easIng options
 *
 * Copyright (c) 2007 George Smith
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 * jQuery UI Stars v1.1
 *
 * Copyright (c) 2008 Orkan (orkans@gmail.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Depends:
 *	ui.core.js
 *
 */
(function($) {

	$.widget("ui.stars", {
		init: function() {
      var self = this, o = this.options;
      o.isSelect = o.inputType == "select";
      
      this.$selec = o.isSelect ? $("select", this.element) : null;
      this.$rboxs = o.isSelect ? $("option", this.$selec) : $(":radio", this.element);

      this.$stars = this.$rboxs.map(function(i) {
        if(i==0) {
          o.split = typeof o.split != "number" ? 0 : o.split;
          o.val2id = [];
          o.id2val = [];
          o.id2title = [];
          o.name = o.isSelect ? self.$selec.get(0).name : this.name;
          o.disabled = o.disabled || (o.isSelect ? $(self.$selec).attr('disabled') : $(this).attr('disabled'));
          o.items = 0;
        }
        o.items++;

        o.val2id[this.value] = i;
        o.id2val[i] = this.value;
        o.id2title[i] = (o.isSelect ? this.text : this.title) || this.value;

        if(o.selected==i || (o.selected==-1 && (o.isSelect ? this.defaultSelected : this.defaultChecked) )) {
          o.checked = i;
          o.value = o.id2val[i];
          o.title = o.id2title[i];
        }

        var $s = $("<div/>").addClass(o.starClass);
        var $a = $('<a/>').attr("title", o.showTitles ? o.id2title[i] : "").text(this.value);
        
        // Prepare division settings
        if(o.split) {
          var oddeven = (i % o.split);
          var stwidth = Math.floor(o.starWidth / o.split);
          $s.width(stwidth);
          $a.css("margin-left", "-"+(oddeven*stwidth)+"px");
        }

        return $s.append($a).get(0);
      });
      
      this.$cancel = $("<div/>").addClass(o.cancelClass).append( $("<a/>").attr("title", o.showTitles ? o.cancelTitle : "").text(o.cancelValue) );
      this.$value = $('<input type="hidden" name="'+o.name+'" value="'+o.value+'" />');

      o.cancelShow &= !o.disabled && !o.oneVoteOnly;

      // Stars interface
      if(o.cancelShow) this.element.append(this.$cancel);
      this.element.append(this.$stars);
      this.element.append(this.$value);
      
      // Replace content
      o.isSelect ? this.$selec.remove() : this.$rboxs.remove();

      // Initial selection
      if(o.checked === undefined) {
          o.checked = -1;
          o.value = o.cancelValue;
          o.title = "";
          if(o.cancelShow) this._disableCancel();
      }
      else {
        fillTo(o.checked, false);
      }

      if(o.disabled) this.disable();


      // Clean up to avoid memory leaks in certain versions of IE 6
      $(window).bind("unload", function(){
        self.$cancel.unbind(".stars");
        self.$stars.unbind(".stars");
        self.$selec = self.$rboxs = self.$stars = self.$value = self.$cancel = null;
      });

      // Remove selection
      function fillNone() {
          self.$stars.removeClass([o.starOnClass, o.starHoverClass].join(' '));
          self._showCap("");
      }
      
      // Fill stars to the current index
      function fillTo(index, hover) {
        if(index != -1) {
          var addClass = hover ? o.starHoverClass : o.starOnClass;
          var remClass = hover ? o.starOnClass : o.starHoverClass;
          self.$stars.eq(index).prevAll("."+o.starClass).andSelf().removeClass(remClass).addClass(addClass);
          self.$stars.eq(index).nextAll("."+o.starClass).removeClass([o.starHoverClass, o.starOnClass].join(' '));
          self._showCap(o.id2title[index]);
        }
        else fillNone();
      }

      // Attach star event handler
      this.$stars.bind("click.stars", function() {
          if(!o.forceSelect && o.disabled) return false;
          
          var i = self.$stars.index(this);
          o.checked = i;
          o.value = o.id2val[i];
          o.title = o.id2title[i];
          self.$value.attr({disabled: o.disabled ? "disabled" : "", value: o.value});

          fillTo(i, false);
          self._disableCancel();

          if(!o.forceSelect) {
            //self.disable();
            self.callback("star");
          }
        })
        .bind("mouseover.stars", function() {
          if(o.disabled) return false;
          var i = self.$stars.index(this);
          fillTo(i, true);
        })
        .bind("mouseout.stars", function() {
          if(o.disabled) return false;
          fillTo(self.options.checked, false);
        });

      this.$cancel.bind("click.stars", function() {
          if( !o.forceSelect && (o.disabled || (o.value == o.cancelValue)) ) return false;
          
          o.checked = -1;
          o.value = o.cancelValue;
          o.title = "";
          self.$value.attr({value: o.value, disabled: "disabled"});
          
          fillNone();
          self._disableCancel();
          
          if(!o.forceSelect) {
            //self.disable();
            self.callback("cancel");
          }
        })
        .bind("mouseover.stars", function() {
          if(self._disableCancel()) return false;
          self.$cancel.addClass(o.cancelHoverClass);
          fillNone();
          self._showCap(o.cancelTitle);
        })
        .bind("mouseout.stars", function() {
          if(self._disableCancel()) return false;
          self.$cancel.removeClass(o.cancelHoverClass);
          self.$stars.triggerHandler("mouseout.stars");
        });

		},
		select: function(val) {
      var o = this.options;
      o.forceSelect = true;
      if(val==o.cancelValue) this.$cancel.triggerHandler("click.stars");
      else                   this.$stars.eq(o.val2id[val]).triggerHandler("click.stars");
      o.forceSelect = false;
		},
		selectID: function(id) {
      var o = this.options;
      o.forceSelect = true;
      if(id==-1)  this.$cancel.triggerHandler("click.stars");
      else        this.$stars.eq(id).triggerHandler("click.stars");
      o.forceSelect = false;
		},
  	enable: function() {
			this.options.disabled = false;
      this._disableAll();
		},
		disable: function() {
			this.options.disabled = true;
      this._disableAll();
		},
		_disableCancel: function() {
        var o = this.options, disabled = o.disabled || o.oneVoteOnly || (o.value == o.cancelValue);
        if(disabled)  this.$cancel.removeClass(o.cancelHoverClass).addClass(o.cancelDisabledClass);
        else          this.$cancel.removeClass(o.cancelDisabledClass);
        this.$cancel.css("opacity", disabled ? 0.5 : 1);
        return disabled;
		},
		_disableAll: function() {
      var o = this.options;
      this._disableCancel();
      if(o.disabled)  this.$stars.filter("div").addClass(o.starDisabledClass);
      else            this.$stars.filter("div").removeClass(o.starDisabledClass);
		},
		_showCap: function(s) {
      var o = this.options;
			if(o.captionEl) o.captionEl.text(s);
		},
    destroy: function() {
      this.options.isSelect ? this.$selec.appendTo(this.element) : this.$rboxs.appendTo(this.element);
      this.$cancel.unbind('.stars').remove();
      this.$stars.unbind('.stars').remove();
      this.$value.remove();
      this.element.unbind('.stars').removeData('stars');
    },
    callback: function(type) {
      var o = this.options;
      o.callback(this, type, o.value);
      if(o.oneVoteOnly && !o.disabled) this.disable();
    }
  });


	$.ui.stars.defaults = {
    inputType: "radio", // radio|select
		split: 0,
    selected: -1,
    disabled: false,
    cancelTitle: "Cancel Rating",
		cancelValue: 0,
    cancelShow: true,
    oneVoteOnly: false,
    showTitles: false,
    captionEl: null,
    callback: function(el,type,value){},

    // CSS classes
    starWidth: 16,
    cancelClass: 'ui-stars-cancel',
		starClass: 'ui-stars-star',
		starOnClass: 'ui-stars-star-on',
		starHoverClass: 'ui-stars-star-hover',
		starDisabledClass: 'ui-stars-star-disabled',
		cancelHoverClass: 'ui-stars-cancel-hover',
		cancelDisabledClass: 'ui-stars-cancel-disabled'
  };

})(jQuery);

/* ui.tabs.js
 *
 * Tabs 3 - New Wave Tabs
 *
 * Copyright (c) 2007 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 */

(function($) {

    // if the UI scope is not availalable, add it
    $.ui = $.ui || {};

    // tabs initialization
    $.fn.tabs = function(initial, options) {
        if (initial && initial.constructor == Object) { // shift arguments
            options = initial;
            initial = null;
        }
        options = options || {};

        initial = initial && initial.constructor == Number && --initial || 0;

        return this.each(function() {
            new $.ui.tabs(this, $.extend(options, { initial: initial }));
        });
    };

    // other chainable tabs methods
    $.each(['Add', 'Remove', 'Enable', 'Disable', 'Click', 'Load'], function(i, method) {
        $.fn['tabs' + method] = function() {
            var args = arguments;
            return this.each(function() {
                var instance = $.ui.tabs.getInstance(this);
                instance[method.toLowerCase()].apply(instance, args);
            });
        };
    });
    $.fn.tabsSelected = function() {
        var selected = -1;
        if (this[0]) {
            var instance = $.ui.tabs.getInstance(this[0]),
                $lis = $('>li', this);
            selected = $lis.index( $lis.filter('.' + instance.options.selectedClass)[0] );
        }
        return selected >= 0 ? ++selected : -1;
    };

    // tabs class
    $.ui.tabs = function(el, options) {

        this.source = el;

        this.options = $.extend({

            // basic setup
            //initial: 0,
            event: 'click',
            disabled: [],
            // TODO bookmarkable: $.ajaxHistory ? true : false,
            unselected: false,
            unselect: options.unselected ? true : false,

            // Ajax
            spinner: '<img src="/images/tabs-loader.gif" border="0" />',
            cache: false,
            idPrefix: 'tab-',

            // animations
            /*fxFade: null,
            fxSlide: null,
            fxShow: null,
            fxHide: null,*/
            fxSpeed: 'normal',
            /*fxShowSpeed: null,
            fxHideSpeed: null,*/

            // callbacks
            add: function() {},
            remove: function() {},
            enable: function() {},
            disable: function() {},
            click: function() {},
            hide: function() {},
            show: function() {},
            load: function() {},

            // CSS classes
            navClass: 'ui-tabs-nav',
            selectedClass: 'ui-tabs-selected',
            disabledClass: 'ui-tabs-disabled',
            containerClass: 'ui-tabs-container',
            hideClass: 'ui-tabs-hide',
            loadingClass: 'ui-tabs-loading'

        }, options);

        this.tabify(true);

        // save instance for later
        var uuid = 'tabs' + $.ui.tabs.prototype.count++;
        $.ui.tabs.instances[uuid] = this;
        $.data(el, 'tabsUUID', uuid);

    };

    // static
    $.ui.tabs.instances = {};
    $.ui.tabs.getInstance = function(el) {
        return $.ui.tabs.instances[$.data(el, 'tabsUUID')];
    };

    // instance methods
    $.extend($.ui.tabs.prototype, {
        count: 0,
        tabify: function(init) {

            this.$tabs = $('>li>a[target!=_top]', this.source);
            this.$containers = $([]);

            var self = this, o = this.options;
            
            this.$tabs.each(function(i, a) {
                // inline tab
                if (a.hash && a.hash.replace('#', '')) { // safari 2 reports '#' for an empty hash
                    self.$containers = self.$containers.add(a.hash);
                }
                // remote tab
                else {
                    $.data(a, 'href', a.href);
                    var id = a.target && a.target.replace(/\s/g, '_') || o.idPrefix + (self.count + 1) + '-' + (i + 1);
                    a.href = '#' + id;
                    self.$containers = self.$containers.add(
                        $('#' + id)[0] || $('<div id="' + id + '" class="' + o.containerClass + '"></div>')
                            .insertAfter( self.$containers[i - 1] || self.source )
                    );
                }
            });

            if (init) {

                // Try to retrieve initial tab from fragment identifier in url if present,
                // otherwise try to find selected class attribute on <li>.
                this.$tabs.each(function(i, a) {
                    if (location.hash) {
                        if (a.hash == location.hash) {
	                        //alert(location.hash) ;
                            o.initial = i;
                            // prevent page scroll to fragment
                            //if (($.browser.msie || $.browser.opera) && !o.remote) {
                            if ($.browser.msie || $.browser.opera) {
                                var $toShow = $(location.hash), toShowId = $toShow.attr('id');
                                $toShow.attr('id', '');
                                setTimeout(function() {
                                    $toShow.attr('id', toShowId); // restore id
                                }, 500);
                            }
                            scrollTo(0, 0);

                            return false; // break
                        }
                    } else if ( $(a).parents('li:eq(0)').is('li.' + o.selectedClass) ) { 
                        o.initial = i;
                        return false; // break
                    }
                });

                // attach necessary classes for styling if not present
                $(this.source).is('.' + o.navClass) || $(this.source).addClass(o.navClass);
                this.$containers.each(function() {
                    var $this = $(this);
                    $this.is('.' + o.containerClass) || $this.addClass(o.containerClass);
                });

                // highlight tab
                var $lis = $('>li', this.source);
                this.$containers.addClass(o.hideClass);
                this.$containers.css("display",""); // added to address wrong CSS
                $lis.removeClass(o.selectedClass);
                if (!o.unselected && o.initial != null )  {
                    this.$containers.slice(o.initial, o.initial + 1).removeClass(o.hideClass).show();
                    var $selectedLi = $lis.slice(o.initial, o.initial + 1);
                    $selectedLi.addClass(o.selectedClass);
					// added by Robert Ernens to handle initial selection of anchor
                    var $selectedA = $(">a", $selectedLi).get(0);
                    $($selectedA).addClass( $($selectedA).attr("rev") );
                }

                // load if remote tab
                if(o.initial != null ) {
                	if ($.data(this.$tabs[o.initial], 'href')) {
                    	this.load(o.initial + 1, $.data(this.$tabs[o.initial], 'href'));
                    	if (o.cache) {
                        	$.removeData(this.$tabs[o.initial], 'href'); // if loaded once do not load them again
                    	}
					}
                }

                // disabled tabs
                for (var i = 0, position; position = o.disabled[i]; i++) {
                    this.disable(position);
                }

            }

            // setup animations
            var showAnim = {}, showSpeed = o.fxShowSpeed || o.fxSpeed,
                hideAnim = {}, hideSpeed = o.fxHideSpeed || o.fxSpeed;
            if (o.fxSlide || o.fxFade) {
                if (o.fxSlide) {
                    showAnim['height'] = 'show';
                    hideAnim['height'] = 'hide';
                }
                if (o.fxFade) {
                    showAnim['opacity'] = 'show';
                    hideAnim['opacity'] = 'hide';
                }
            } else {
                if (o.fxShow) {
                    showAnim = o.fxShow;
                } else { // use some kind of animation to prevent browser scrolling to the tab
                    showAnim['min-width'] = 0; // avoid opacity, causes flicker in Firefox
                    showSpeed = 1; // as little as 1 is sufficient
                }
                if (o.fxHide) {
                    hideAnim = o.fxHide;
                } else { // use some kind of animation to prevent browser scrolling to the tab
                    hideAnim['min-width'] = 0; // avoid opacity, causes flicker in Firefox
                    hideSpeed = 1; // as little as 1 is sufficient
                }
            }

            // reset some styles to maintain print style sheets etc.
            var resetCSS = { display: '', overflow: '', height: '' };
            if (!$.browser.msie) { // not in IE to prevent ClearType font issue
                resetCSS['opacity'] = '';
            }

            // Hide a tab, animation prevents browser scrolling to fragment,
            // $show is optional.
            function hideTab(clicked, $hide, $show) {
                $hide.animate(hideAnim, hideSpeed, function() { //
                    $hide.addClass(o.hideClass).css(resetCSS); // maintain flexible height and accessibility in print etc.
                    if ($.browser.msie) {
                        $hide[0].style.filter = '';
                    }
                    o.hide(clicked, $hide[0], $show && $show[0] || null);
                    if ($show) {
                        showTab(clicked, $show, $hide);
                    }
                });
            }

            // Show a tab, animation prevents browser scrolling to fragment,
            // $hide is optional
            function showTab(clicked, $show, $hide) {
                if (!(o.fxSlide || o.fxFade || o.fxShow)) {
                    $show.css('display', 'block'); // prevent occasionally occuring flicker in Firefox cause by gap between showing and hiding the tab containers
                }
                $show.animate(showAnim, showSpeed, function() {
//                    $show.removeClass(o.hideClass).css(resetCSS); // maintain flexible height and accessibility in print etc.
                    $show.removeClass(o.hideClass) ;
                    if ($.browser.msie) {
                        $show[0].style.filter = '';
                    }
                    o.show(clicked, $show[0], $hide && $hide[0] || null);
                });
            }

            // switch a tab
            function switchTab(clicked, $hide, $show) {
                /*if (o.bookmarkable && trueClick) { // add to history only if true click occured, not a triggered click
                    $.ajaxHistory.update(clicked.hash);
                }*/
                var $clicked = $(clicked);
                var $parents = $clicked.parents('li:eq(0)');
                $parents.addClass(o.selectedClass) ;
                var $siblings = $parents.siblings();
                $siblings.removeClass(o.selectedClass);
                hideTab(clicked, $hide, $show);
            }

            // tab click handler 
            function tabFreeze(e) {
                 return false;
            }

            function tabClick(e) {

                //var trueClick = e.clientX; // add to history only if true click occured, not a triggered click
                var $li = $(this).parents('li:eq(0)'),
                    $hide = self.$containers.not("."+ o.hideClass),
                    $show = $(this.hash);

                // If tab is already selected and not unselectable or tab disabled or click callback returns false stop here.
                // Check if click handler returns false last so that it is not executed for a disabled tab!
                if (($li.is('.' + o.selectedClass) && !o.unselect) || $li.is('.' + o.disabledClass)
                    || o.click(this, $show[0], $hide[0]) === false) {
                    this.blur();
                    return false;
                }
                    
                // if tab may be closed
                if (o.unselect) {
                    if ($li.is('.' + o.selectedClass)) {
                        $li.removeClass(o.selectedClass);
                        self.$containers.stop();
                        hideTab(this, $hide);
                        this.blur();
                        return false;
                    } else if (!$hide.length) {
                        $li.addClass(o.selectedClass);
                        self.$containers.stop();
                        showTab(this, $show);
                        this.blur();
                        return false;
                    }
                }

                // stop possibly running animations
                self.$containers.stop();

                // show new tab
                if ($show.length) {

                    // prevent scrollbar scrolling to 0 and than back in IE7, happens only if bookmarking/history is enabled
                    /*if ($.browser.msie && o.bookmarkable) {
                        var showId = this.hash.replace('#', '');
                        $show.attr('id', '');
                        setTimeout(function() {
                            $show.attr('id', showId); // restore id
                        }, 0);
                    }*/

                    if ($.data(this, 'href')) { // remote tab
                        var a = this;
                        self.load(self.$tabs.index(this) + 1, $.data(this, 'href'), function() {
                            switchTab(a, $hide, $show);
                        });
                        if (o.cache) {
                            $.removeData(this, 'href'); // if loaded once do not load them again
                        }
                    } else {
                        switchTab(this, $hide, $show);
                    }

                    // Set scrollbar to saved position - need to use timeout with 0 to prevent browser scroll to target of hash
                    /*var scrollX = window.pageXOffset || document.documentElement && document.documentElement.scrollLeft || document.body.scrollLeft || 0;
                    var scrollY = window.pageYOffset || document.documentElement && document.documentElement.scrollTop || document.body.scrollTop || 0;
                    setTimeout(function() {
                        scrollTo(scrollX, scrollY);
                    }, 0);*/  

                } else {
                    throw 'jQuery UI Tabs: Mismatching fragment identifier.';
                }

                this.blur(); // prevent IE from keeping other link focussed when using the back button

                //return o.bookmarkable && !!trueClick; // convert trueClick == undefined to Boolean required in IE
                return false;

            }

            // attach event handler, avoid duplicates from former tabifying
            this.$tabs.unbind(o.event, tabClick).bind(o.event, tabClick);

            // attach click event, if event is mouseover to prevent scroll to fragment
            if(o.event == "mouseover") {
            this.$tabs.unbind("click", tabFreeze).bind("click", tabFreeze);
			}

        },
        add: function(url, text, position) {
            if (url && text) {
                var o = this.options;
                position = position || this.$tabs.length; // append by default
                if (position >= this.$tabs.length) {
                    var method = 'insertAfter';
                    position = this.$tabs.length;
                } else {
                    var method = 'insertBefore';
                }
                if (url.indexOf('#') == 0) { // ajax container is created by tabify automatically
                    var $container = $(url);
                    // try to find an existing element before creating a new one
                    ($container.length && $container || $('<div id="' + url.replace('#', '') + '" class="' + o.containerClass + ' ' + o.hideClass + '"></div>'))
                        [method](this.$containers[position - 1]);
                }
                $('<li><a href="' + url + '"><span>' + text + '</span></a></li>')
                    [method](this.$tabs.slice(position - 1, position).parents('li:eq(0)'));
                this.tabify();
                o.add(this.$tabs[position - 1], this.$containers[position - 1]); // callback
            } else {
                throw 'jQuery UI Tabs: Not enough arguments to add tab.';
            }
        },
        remove: function(position) {
            if (position && position.constructor == Number) {
                var $removedTab = this.$tabs.slice(position - 1, position).parents('li:eq(0)').remove();
                var $removedContainer = this.$containers.slice(position - 1, position).remove();
                this.tabify();
                this.options.remove($removedTab[0], $removedContainer[0]); // callback
            }
        },
        enable: function(position) {
            var $li = this.$tabs.slice(position - 1, position).parents('li:eq(0)'), o = this.options;
            $li.removeClass(o.disabledClass);
            if ($.browser.safari) { // fix disappearing tab after enabling in Safari... TODO check Safari 3
                $li.animate({ opacity: 1 }, 1, function() {
                    $li.css({ opacity: '' });
                });
            }
            o.enable(this.$tabs[position - 1], this.$containers[position - 1]); // callback
        },
        disable: function(position) {
            var $li = this.$tabs.slice(position - 1, position).parents('li:eq(0)'), o = this.options;
            if ($.browser.safari) { // fix opacity of tab after disabling in Safari... TODO check Safari 3
                $li.animate({ opacity: 0 }, 1, function() {
                   $li.css({ opacity: '' });
                });
            }
            $li.addClass(this.options.disabledClass);
            o.disable(this.$tabs[position - 1], this.$containers[position - 1]); // callback
        },
        click: function(position) {
            this.$tabs.slice(position - 1, position).trigger('click');
        },
        load: function(position, url, callback) {
            var self = this,
                o = this.options,
                $a = this.$tabs.slice(position - 1, position).addClass(o.loadingClass),
                $span = $('span', $a),
                text = $span.html();

            // shift arguments
            if (url && url.constructor == Function) {
                callback = url;
            }

            // set new URL
            if (url) {
                $.data($a[0], 'href', url);
            }

            // load
            if (o.spinner) {
//                $span.html('<em>' + o.spinner + '</em>');
                  spanDisplay = $span.css("display");
                  spanWidth = $span.width();
                  $span.css({display: "block", width: spanWidth+"px"}).html(o.spinner);
            }
            setTimeout(function() { // timeout is again required in IE, "wait" for id being restored 
                var hasParms = url.match("=");
                url += hasParms ? "&_=" : "?_="
                $($a[0].hash).load(url, function() {
                    if (o.spinner) { 
                        $span.css({display: spanDisplay});
                        $span.html(text);
                    }
                    $a.removeClass(o.loadingClass);
                    // This callback is required because the switch has to take place after loading
                    // has completed.
                    if (callback && callback.constructor == Function) {
                        callback();
                    }
                    o.load(self.$tabs[position - 1], self.$containers[position - 1]); // callback
                });
            }, 0);
        }
    });

})(jQuery);

/* ui.accordion.js
 *
 * Accordion 1.6pre - jQuery menu widget
 * 
 * Based on implementation by Frank Marcia
 *
 * Copyright (c) 2007 JÃ¶rn Zaefferer
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-accordion/
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.accordion.js 4296 2007-12-21 10:05:52Z joern.zaefferer $
 *
*/

;(function($) {

$.ui = $.ui || {};

$.ui.accordion = {};
$.extend($.ui.accordion, {
	defaults: {
		selectedClass: "selected",
		alwaysOpen: true,
		animated: 'slide',
		event: "click",
		header: "a",
		autoheight: false
	},
	animations: {
		slide: function(settings, additions) {
			settings = $.extend({
				easing: "swing",
				duration: 300
			}, settings, additions);
			if ( !settings.toHide.size() ) {
				settings.toShow.animate({height: "show"}, settings);
				return;
			}
			var hideHeight = settings.toHide.height(),
				showHeight = settings.toShow.height(),
				difference = showHeight / hideHeight;
			settings.toShow.css({ height: 0, overflow: 'hidden' }).show();
			settings.toHide.filter(":hidden").each(settings.complete).end().filter(":visible").animate({height:"hide"},{
				step: function(now){
					settings.toShow.height((hideHeight - (now)) * difference );
				},
				duration: settings.duration,
				easing: settings.easing,
				complete: settings.complete
			});
		},
		bounceslide: function(settings) {
			this.slide(settings, {
				easing: settings.down ? "bounceout" : "swing",
				duration: settings.down ? 1000 : 200
			});
		},
		easeslide: function(settings) {
			this.slide(settings, {
				easing: "easeinout",
				duration: 700
			})
		}
	}
});

$.fn.extend({
	accordion: function(settings) {
		if ( !this.length )
			return this;
	
		// setup configuration
		settings = $.extend({}, $.ui.accordion.defaults, settings);
		
		if ( settings.navigation ) {
			var current = this.find("a").filter(function() { return this.href == location.href; });
			if ( current.length ) {
				if ( current.filter(settings.header).length ) {
					settings.active = current;
				} else {
					settings.active = current.parent().parent().prev();
					current.addClass("current");
				}
			}
		}
		
		// calculate active if not specified, using the first header
		var headers = this.find(settings.header),
			active = findActive(settings.active),
			running = 0;

		if ( settings.fillSpace ) {
			var maxHeight = this.parent().height();
			headers.each(function() {
				maxHeight -= $(this).outerHeight();
			});
			var maxPadding = 0;
			headers.next().each(function() {
				maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height());
			}).height(maxHeight - maxPadding);
		} else if ( settings.autoheight ) {
			var maxHeight = 0;
			headers.next().each(function() {
				maxHeight = Math.max(maxHeight, $(this).outerHeight());
			}).height(maxHeight);
		}

		headers
			.not(active || "")
			.next()
			.hide();
		active.parent().andSelf().addClass(settings.selectedClass);
		
		
		function findActive(selector) {
			return selector != undefined
				? typeof selector == "number"
					? headers.filter(":eq(" + selector + ")")
					: headers.not(headers.not(selector))
				: selector === false
					? $([])
					: headers.filter(":eq(0)");
		}
		
		function toggle(toShow, toHide, data, clickedActive, down) {
			var complete = function(cancel) {
				running = cancel ? 0 : --running;
				if ( running )
					return;
				if ( settings.clearStyle ) {
					toShow.add(toHide).css({
						height: "",
						overflow: ""
					});
				}
				// trigger custom change event
				$(this).trigger("change", data);
			};
			
			// count elements to animate
			running = toHide.size() == 0 ? toShow.size() : toHide.size();
			
			if ( settings.animated ) {
				if ( !settings.alwaysOpen && clickedActive ) {
					toShow.slideToggle(settings.animated);
					complete(true);
				} else {
					$.ui.accordion.animations[settings.animated]({
						toShow: toShow,
						toHide: toHide,
						complete: complete,
						down: down
					});
				}
			} else {
				if ( !settings.alwaysOpen && clickedActive ) {
					toShow.toggle();
				} else {
					toHide.hide();
					toShow.show();
				}
				complete(true);
			}
		}
		
		function clickHandler(event) {
			// called only when using activate(false) to close all parts programmatically
			if ( !event.target && !settings.alwaysOpen ) {
				active.parent().andSelf().toggleClass(settings.selectedClass);
				var toHide = active.next();
				var toShow = active = $([]);
				toggle.call(this, toShow, toHide );
				return false;
			}
			// get the click target
			var clicked = $(event.target);
			
			// due to the event delegation model, we have to check if one
			// of the parent elements is our actual header, and find that
			if ( clicked.parents(settings.header).length )
				while ( !clicked.is(settings.header) )
					clicked = clicked.parent();
			
			var clickedActive = clicked[0] == active[0];
			
			// if animations are still active, or the active header is the target, ignore click
			if(running || (settings.alwaysOpen && clickedActive) || !clicked.is(settings.header))
				return false;

			// switch classes
			active.parent().andSelf().toggleClass(settings.selectedClass);
			if ( !clickedActive ) {
				clicked.parent().andSelf().addClass(settings.selectedClass);
			}

			// find elements to show and hide
			var toShow = clicked.next(),
				toHide = active.next(),
				data = [clicked, active, toShow, toHide],
				down = headers.index( active[0] ) > headers.index( clicked[0] );
			
			active = clickedActive ? $([]) : clicked;
			toggle.call(this, toShow, toHide, data, clickedActive, down );

			return false;
		};
		function activateHandler(event, index) {
			// IE manages to call activateHandler on normal clicks
			if ( arguments.length == 1 )
				return;
			// call clickHandler with custom event
			clickHandler({
				target: findActive(index)[0]
			});
		};

		return this
			.bind(settings.event || "", clickHandler)
			.bind("activate", activateHandler);
	},
	activate: function(index) {
		return this.trigger('activate', [index]);
	},
	unaccordion: function() {
		return this.find("*").andSelf().unbind().end().end();
	}
});

})(jQuery);
  

/*------------------------------------------------------------------------------------------------------------------
 *
 * form and ajax plugins
 *
 *------------------------------------------------------------------------------------------------------------------*/
/* ajaxManager
 * @author alexander.farkas
 * @version 1.01 
 */
(function($){
    $.extend({
        manageAjax: function(o){
            o = $.extend({
                manageType: 'normal',
                maxReq: 0,
                blockSameRequest: false,
				global: true
            }, o);
            return new $.ajaxManager(o);
        },
        ajaxManager: function(o){
            this.opt = o;
            this.queue = [];
        }
    });
    $.extend($.ajaxManager.prototype, {
        add: function(o){
            var quLen = this.queue.length, s = this.opt, q = this.queue, self = this, i, j;
            var cD = (o.data && typeof o.data != "string") ? $.param(o.data) : o.data;
            if (s.blockSameRequest) {
                var toPrevent = false;
                for (i = 0; i < quLen; i++) {
                    if (q[i] && q[i].data === cD && q[i].url === o.url && q[i].type === o.type) {
                        toPrevent = true;
                        break;
                    }
                }
                if (toPrevent) {
                    return false;
                }
            }
            q[quLen] = {
                fnError: o.error,
                fnSuccess: o.success,
                fnComplete: o.complete,
                fnAbort: o.abort,
                error: [],
                success: [],
                complete: [],
                done: false,
                queued: false,
                data: cD,
                url: o.url,
                type: o.type,
                xhr: null
            };

            o.error = function(){
                if (q[quLen]) {
                    q[quLen].error = arguments;
                }
            };
            o.success = function(){
                if (q[quLen]) {
                    q[quLen].success = arguments;
                }
            };
            o.abort = function(){
                if (q[quLen]) {
                    q[quLen].abort = arguments;
                }
            };
            function startCallbacks(num){
                if (q[num].fnError) {
                    q[num].fnError.apply($, q[num].error);
                }
                if (q[num].fnSuccess) {
                    q[num].fnSuccess.apply($, q[num].success);
                }
                if (q[num].fnComplete) {
                    q[num].fnComplete.apply($, q[num].complete);
                }
                self.abort(num, true);
            }

            o.complete = function(){
                if (!q[quLen]) {
                    return;
                }
                q[quLen].complete = arguments;
                q[quLen].done = true;
                switch (s.manageType) {
                    case 'sync':
                        if (quLen === 0 || !q[quLen - 1]) {
                            var curQLen = q.length;
                            for (i = quLen; i < curQLen; i++) {
                                if (q[i]) {
                                    if (q[i].done) {
                                        startCallbacks(i);
                                    }
                                    else {
                                        break;
                                    }
                                }

                            }
                        }
                        break;
                    case 'queue':
                        if (quLen === 0 || !q[quLen - 1]) {
                            var curQLen = q.length;
                            for (i = 0, j = 0; i < curQLen; i++) {
                                if (q[i] && q[i].queued) {
                                    q[i].xhr = jQuery.ajax(q[i].xhr);
                                    q[i].queued = false;
                                    break;
                                }
                            }
                        }
                        startCallbacks(quLen);
                        break;
                    case 'abortOld':
                        startCallbacks(quLen);
                        for (i = quLen; i >= 0; i--) {
                            if (q[i]) {
                                self.abort(i);
                            }
                        }
                        break;
                    default:
                        startCallbacks(quLen);
                        break;
                }
            };

            if (s.maxReq) {
                if (s.manageType != 'queue') {
                    for (i = quLen, j = 0; i >= 0; i--) {
                        if (j >= s.maxReq) {
                            this.abort(i);
                        }
                        if (q[i]) {
                            j++;
                        }
                    }
                }
                else {
                    for (i = 0, j = 0; i <= quLen && !q[quLen].queued; i++) {
                        if (q[i] && !q[i].queued) 
                            j++;
                        if (j > s.maxReq) 
                            q[quLen].queued = true;
                    }
                }
            }
            q[quLen].xhr = (q[quLen].queued) ? o : jQuery.ajax(o);
            return quLen;
        },
        cleanUp: function(){
            this.queue = [];
        },
        abort: function(num, completed){
            var qLen = this.queue.length, s = this.opt, q = this.queue, self = this, i;
            function del(num){
                if (!q[num]) {
                    return;
                }
                (!completed && q[num].fnAbort) && q[num].fnAbort.apply($, [num]);
                if (!q[num]) {
                    return;
                }
                if (q[num].xhr) {
                    if (typeof q[num].xhr.abort != 'undefined') {
                        q[num].xhr.abort();
                    }
                    if (typeof q[num].xhr.close != 'undefined') {
                        q[num].xhr.close();
                    }
                    q[num].xhr = null;
                }
				// Handle the global AJAX counter

				if ( s.global && $.active && ! --$.active){
					$.event.trigger( "ajaxStop" );
				}
                q[num] = null;
            }
            if (!num && num !== 0) {
                for (i = 0; i < qLen; i++) {
                    del(i);
                }
                this.cleanUp();
            }
            else {
                del(num);
                var allowCleaning = true;
                for (i = qLen; i >= 0; i--) {
                    if (q[i]) {
                        allowCleaning = false;
                        break;
                    }
                }
                if (allowCleaning) {
                    this.cleanUp();
                }
            }
        }
    });
})(jQuery);

/*
 * jQuery Form Plugin
 * version: 2.16 (17-OCT-2008)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.form.js 5718 2008-06-07 15:02:19Z malsup $
 */
;(function($) {

/*
    Usage Note:  
    -----------
    Do not use both ajaxSubmit and ajaxForm on the same form.  These
    functions are intended to be exclusive.  Use ajaxSubmit if you want
    to bind your own submit handler to the form.  For example,

    $(document).ready(function() {
        $('#myForm').bind('submit', function() {
            $(this).ajaxSubmit({
                target: '#output'
            });
            return false; // <-- important!
        });
    });

    Use ajaxForm when you want the plugin to manage all the event binding
    for you.  For example,

    $(document).ready(function() {
        $('#myForm').ajaxForm({
            target: '#output'
        });
    });
        
    When using ajaxForm, the ajaxSubmit function will be invoked for you
    at the appropriate time.  
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting 
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }

    if (typeof options == 'function')
        options = { success: options };

    options = $.extend({
        url:  this.attr('action') || window.location.toString(),
        type: this.attr('method') || 'GET'
    }, options || {});

    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
   }

    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data) {
          if(options.data[n] instanceof Array) {
            for (var k in options.data[n])
              a.push( { name: n, value: options.data[n][k] } )
          }  
          else
             a.push( { name: n, value: options.data[n] } );
        }
    }

    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSubmit callback');
        return this;
    }    

    // fire vetoable 'validate' event
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
        return this;
    }    

    var q = $.param(a);

    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'

    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            $(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i].apply(options, [data, status, $form]);
    };

    // are there files to upload?
    var files = $('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;

    // options.iframe allows user to force iframe mode
   if (options.iframe || found) { 
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if ($.browser.safari && options.closeKeepAlive)
           $.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $.ajax(options);

    // fire 'notify' event
    this.trigger('form-submit-notify', [this, options]);
    return this;


    // private function for handling file uploads (hat tip to YAHOO!)
    function fileUpload() {
        var form = $form[0];
        
        if ($(':input[name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }
        
        var opts = $.extend({}, $.ajaxSettings, options);
        var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" />');
        var io = $io[0];

        if ($.browser.msie || $.browser.opera) 
            io.src = 'javascript:false;document.write("");';
        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            aborted: 0,
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {},
            abort: function() { 
                this.aborted = 1; 
                $io.attr('src','about:blank'); // abort op in progress
            }
        };

        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! $.active++) $.event.trigger("ajaxStart");
        if (g) $.event.trigger("ajaxSend", [xhr, opts]);

        if (s.beforeSend && s.beforeSend(xhr, s) === false) {
           s.global && jQuery.active--;
           return;
        }
        if (xhr.aborted)
            return;
        
        var cbInvoked = 0;
        var timedOut = 0;

        // add submitting element to data if we know it
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }

        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');
            $form.attr({
                target:   id,
                method:   'POST',
                action:   opts.url
            });
            
            // ie borks in some cases when setting encoding
            if (! options.skipEncodingOverride) {
                $form.attr({
                    encoding: 'multipart/form-data',
                    enctype:  'multipart/form-data'
                });
            }

            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);
            
                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
                $form.attr('action', a);
                t ? $form.attr('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);

        function cb() {
            if (cbInvoked++) return;
            
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            var operaHack = 0;
            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;

                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
                
                if (doc.body == null && !operaHack && $.browser.opera) {
                    // In Opera 9.2.x the iframe DOM is not always traversable when
                    // the onload callback fires so we give Opera 100ms to right itself
                    operaHack = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }
                
                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };

                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }

            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

            // clean up
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };

        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *    is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *    used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */ 
$.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var form = this.form;
            form.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    form.clk_x = e.offsetX;
                    form.clk_y = e.offsetY;
                } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = $(this).offset();
                    form.clk_x = e.pageX - offset.left;
                    form.clk_y = e.pageY - offset.top;
                } else {
                    form.clk_x = e.pageX - this.offsetLeft;
                    form.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
        });
    });
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $(":submit,input:image", this).unbind('click.form-plugin');
    });

};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                // extra pain for IE...
                var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) { 
    if (b == undefined) b = true;
    return this.each(function() { 
        this.disabled = !b 
    });
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
    if (select == undefined) select = true;
    return this.each(function() { 
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').selected(false);
            }
            this.selected = select;
        }
    });
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
    if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

})(jQuery);


/* jquery.jframe.js 
 * used for dynamically loading content in blocks
 *
 * jFrame
 * $Revision: 1.80 $
 * Author: Frederic de Zorzi
 * Contact: fredz@_nospam_pimentech.net
 * Revision: $Revision: 1.80 $
 * Date: $Date: 2007/11/08 15:17:18 $
 * Copyright: 2007 PimenTech SARL
 *
*/


jQuery.fn.waitingJFrame = function () {
	// Overload this function in your code to place a waiting event 
	// message, like : 	
	$(this).html("<span><img src='/images/ajax-loader.gif' border='0' class='WAC-ajaxLoader' /></span>");
}


jQuery.fn.getJFrameTarget = function () {
    // Returns first parent jframe element, if exists
    var div = jQuery(this).parents("div[src]").get(0);
    if (div) {
        var target = jQuery(this).attr("target");
        if (target) {
            if ( target.indexOf("_",0) != 1 )  {
                return jQuery("#" + target);
            } else {
                return [];
            }
        } else {
	    return [];
        }
    }
    return jQuery(div);
};


jQuery.fn.loadJFrame = function(url, callback) {
    // like ajax.load, for jFrame. the onload attribute is supported
    var this_callback = jQuery(this).attr("onload");
    callback = callback || function(){};
    url = url || jQuery(this).attr("src");
    if (url && url != "#") {
      jQuery(this).waitingJFrame();
      jQuery(this).load(url,
          function() { 
              jQuery(this).attr("src", url);
              jQuery(this).activateJFrame(); 
              jQuery(this)
              .find("div[src]")
              .each(function(i) {
                    jQuery(this).loadJFrame();
                  } );
              eval(this_callback);
              callback();
           });
    } else {
      jQuery(this).activateJFrame(); 
    }
};

jQuery.fn.activateJFrame = function() {
    // Add an onclick event on all <a> and <input type="submit"> tags
    jQuery(this)
    .find("a")
    .not('[jframe="no"]')
    .unbind("click")
    .click(function() { 
            var target = jQuery(this).getJFrameTarget();
            if (target.length) {
                var href = jQuery(this).attr("href");
                if (href && href.indexOf('javascript:') != 0) {
                    target.loadJFrame(href);
                    return false;
                }
            }
            return true;
        } );

    jQuery(this).find("input[type=submit], input[type=image], button[type=submit]")
    .not("[jframe='no']")
    .unbind("click")
    .click(function() {
            var input = this;
            var target = jQuery(input).getJFrameTarget();
            if (target.length) {
                var form = input.form;
                if (form.onsubmit && form.onsubmit()==false) {
                    return false;
                }
                target.waitingJFrame();
                jQuery(form).ajaxSubmit({ 
                        target: target,
                        beforeSubmit: function(formArray) { 
                            formArray.push({ 
                                name:"submit", 
                                value: jQuery(input).attr("value") 
                            }); 
                        },
                        success: function() { 
                            target.attr("src", jQuery(form).attr("action"));
                            eval(target.attr("onload"));
                            target.activateJFrame();
                            target.find("div[src]").each(function(i) {
                                  jQuery(this).loadJFrame();  
                            });
                        }
                    });
                return false;
            }
            return true;
        } );

	var myForms =jQuery(this).find("form").not("form.GMaps-Search");
    myForms
    .unbind("submit")
    .submit(function() {
       this.find("input[type='submit'], button[type='submit']")[0].click();
    } ); 
};


jQuery(document).ready(function() { 
    jQuery(document).find("div[src]").each(function(i) { 
       jQuery(this).loadJFrame(); 
       if (jQuery(this).attr("src") && jQuery(this).attr("src") != "#") {
       }
    });
} );

/* jquery.ajaxContent.js
 *
 * used to dynamically load content in blocks in the data portion of wac when batches are needed
 *
 * ajaxContent - jQuery plugin for accessible, unobtrusive and easy ajax behaviour.
 * @Version 2.0
 * 
 * @requires jQuery v 1.0.1+
 * 
 * http://www.andreacfm.com/jquery-plugins
 *
 * Copyright (c) 2007 Andrea Campolonghi (andreacfm.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
 //make $ surely available inside the PI as jQuery shortcut
(function($) {
	//call teh method with options arguments
	$.fn.ajaxContent = function(options) {
		//extend to defaults
		var defaults = $.extend({}, $.fn.ajaxContent.defaults, options);
			// debug if required		
			if(defaults.debug == 'true'){
				debug(this);
			};
			//Initilaize any instance looping on the match element
			return this.each(function(){
				//set local variables and extend to the metadata plugin if loaded
				var $obj = $(this);
				// added by Robert Ernens to avoid confict with jFrame when laoded dynamically
				$obj.attr("jframe","no") ;
				var o = $.meta ? $.extend({}, defaults, $obj.data()) : defaults;
				//make defaults local variables to prevent to be overwrite from next plugin calls
				var url = $obj.attr('href');
				var $target = $(o.target);
				// added by Robert Ernens to prevent to be overwrite from next plugin calls
				var callBack = o.success;

			//bind the event
				$obj.bind(o.event, function(){
				// added by Robert Ernens if preamble specifield execute it
					if (typeof o.preamble == 'function') {
						o.preamble();
					}
				// add loader if required
					if(o.loader == 'true'){
						if(o.loaderType == 'img'){
							o.loadingMsg = '<img class=\"WAC-ajaxLoader\" src=\"' + o.loadingImg + '\"/>';
						}
						$target.html(o.loadingMsg);
					}	
					//remove add current class
					$('a.' + o.currentClass).removeClass(o.currentClass);								
					$obj.addClass(o.currentClass);
					// make the call
					$.ajax({ 
  						type: o.type, 
  						url: url,
  						success: function(msg){ 
    						$target.html(msg);
    						//if a callback exist pass arguments ( object,target and receive message)
							// changed by Robert Ernens to prevent to be overwriten from next plugin calls
    						//if(typeof o.success == 'function'){
							if(typeof callBack == 'function'){
								//o.success($obj,$target,msg);
    							callBack($obj,$target,msg);
    							}  						
    						},
							error: function(){
								$target.html("<p>" + o.errorMsg + "</p>");
								if(typeof o.error == 'function'){
    							o.error($target);
    							}  						
    					 
						}
					});
				return false;
			});
		});
	};	
  	function debug($obj) {
    if (window.console && window.console.log)
     window.console.log('selection count: ' + $obj.size() + '  with class:' + $obj.attr('class'));
  };
		
})(jQuery);

$.fn.ajaxContent.defaults = {
		target: '#ajaxContent',
		type:'get',
		event:'click',
		loader:'true',
		loaderType:'text',
		loadingMsg:'Loading...',
		loadingImg: '/images/ajax-loader.gif',
		errorMsg:'An error occured during the page requesting process!',
		currentClass:'selected',
		preamble: '',
		success:'',
		error:'',
		debug:'false'
};

/*------------------------------------------------------------------------------------------------------------------
 *
 * User interface plugins - currently not belonging to ui.jquery
 *
 *------------------------------------------------------------------------------------------------------------------*/

/**
 * cust_select_plugin.js
 * Copyright (c) 2009 myPocket technologies (www.mypocket-technologies.com)

 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * View the GNU General Public License <http://www.gnu.org/licenses/>.

 * @author Darren Mason (djmason9@gmail.com)
 * @date 1/22/2009
 * @projectDescription Replaces the standard HTML form selectbox with a custom looking selectbox. Allows for disable, multiselect, scrolling, and very customizable.
 * @version 2.1.0
 * 
 * @requires jquery.js (tested with 1.3.1)
 * 
 * @param isscrolling: 		false,				//scrolls long lists
 * @param scrollminitems:	15,					//items before scrolling
 * @param scrollheight:		150,				//height of scrolling window
 * @param preopenselect:	true,				//opens prechecked select boxes
 * @param hoverstyle:		"hover",			//css hover style name
 * @param openspeed:		"normal",			//selectbox open speed "slow","normal","fast" or numbers 1000
 * @param alldisabled:		false,				//disables all the selectbox
 * @param selectwidth:		"auto",				//set width of selectbox
 * @param wrappername:		".select_wrap"		//class name of the wrapper tag
*/
(function($) {

	$.fn.custSelectBox = function(options){

		//css names
		var classselectbox = "selectbox";
		var selectbox = "." + classselectbox;
		var selectboxoptions_wrap = ".selectboxoptions_wrap";
		var hideitem = "hideitem";
		var classselected = "selected";
		var classselectboxopen = "selectboxopen";
		var classselectboxfoot ="selectboxfoot";
		var selectboxfoot = "." +classselectboxfoot;
		var elmValue = ".elmValue";

		var defaults = {
				isscrolling: 	true,				//scrolls long lists
				scrollminitems:	15,					//items before scrolling
				scrollheight:	150,				//height of scrolling window
				preopenselect:	true,				//opens prechecked select boxes
				hoverstyle:		"hover",			//css hover style name
				openspeed:		"normal",			//selectbox open speed "slow","normal","fast" or numbers 1000
				alldisabled:	false,				//disables the selectbox
				selectwidth:	"auto",				//set width of selectbox
				wrappername:	".select_wrap"
			};
		//override defaults
		var opts = $.extend(defaults, options);

		return this.each(function() { 

		/** FUNCTIONS **/
		$.fn.disable = function(thisElm){
			//loop through items
			for(var i=0;i<$(thisElm).find("ul").find("li").length;i++)
			{
				if($($(thisElm).find("ul").find("li").get(i)).hasClass(classselected))
				{
					$($(thisElm).find("ul").find("li").get(i)).addClass("selected_disable");
				}
				$($(thisElm).find("ul").find("li").get(i)).unbind();
				$($(thisElm).find("ul").get(i)).find("input").attr("disabled","disabled");
			}				
		};

		//adds form elements to the selectbox
		$.fn.addformelms = function(thisElm){

				var currElm = thisElm ;
				var boxtype = $(currElm).find(selectboxoptions_wrap+ " ul").attr("class");

				if(boxtype.indexOf("selectboxoptions_radio") >-1)
				{
					var radioVal = $(currElm).find("."+classselected+" span").text();
					$(currElm).find(selectboxoptions_wrap).find("span").append("<input type=\"hidden\" id=\""+$(currElm).attr("id")+"\" name=\""+$(currElm).attr("id")+"\" value=\""+radioVal+"\">");
				}
				else
				{
					for(var i=0;i<$(currElm).find(selectboxoptions_wrap + " li").length;i++)
					{
						var currInnerElm = $(currElm).find(selectboxoptions_wrap + " li").get(i);
						if($(currInnerElm).hasClass(classselected))
						{  
							$(currInnerElm).append("<input type=\"hidden\" id=\""+$(currElm).attr("id") +"_"+ i+"\" name=\""+ select_name +"\" value=\"\">"); 
							var checkVal = $(currInnerElm).find("span").text();
							$($(currElm).find(selectboxoptions_wrap + " li").get(i)).find("input").val(checkVal);
						}
					}
				}
		};

		//opens selectboxs if they have pre selected options
		$.fn.openSelectBoxsThatArePrePopulated = function()
		{
				var boxtype = $(selectbox).parent().find(selectboxoptions_wrap+ " ul").attr("class");

				if($(selectbox).parent().find("." +boxtype).find("li").hasClass(classselected))
				{
					$(selectbox).addClass(classselectboxopen);
					$(selectbox).parent().find(selectboxoptions_wrap).slideDown("normal");
					$(selectbox).parent().find("." +boxtype).find("li").addClass(hideitem);
				}
		};

		$.fn.scrolling = function (theElm, isOpen)
		{
			if(isOpen)
			{
				if($(theElm).parent().find(selectboxoptions_wrap+ " ul li").length >= opts.scrollminitems){
					$(theElm).parent().find(selectboxoptions_wrap+ " ul").css("height",opts.scrollheight).addClass("setScroll");
				}
			}
			else{
				$(theElm).parent().find(selectboxoptions_wrap+ " ul").css("height","auto").removeClass("setScroll");
			}
		};
		/** FUNCTIONS **/

		//BUILD HTML TO CREATE CUSTOM SELECT BOX
		var main_currElm = $(this);
		var select_name = $(this).attr("name");
		var wrapperElm = $(main_currElm).parent();
		var name = "";
		var select_options = $(main_currElm).find("option");
		var opts_str="";
		var isDisabled = $(main_currElm).attr("disabled");
		var isMulti = $(main_currElm).attr("multiple");
		var boxtype = "selectboxoptions_radio";
		var disabled = "";

		if(isMulti){boxtype = "selectboxoptions_check";}
		if(isDisabled){disabled="disabled";}
		//loop through options
		for(var i=0;i<select_options.length;i++)
		{
			var checked="";
			var currOption = $(select_options).get(i);

			if(i===0){
				name =$(currOption).text();
			}
			else
			{
				if($(currOption).attr("selected")){checked ="selected";}

				opts_str = opts_str + "<li class=\""+checked +" "+disabled+"\"><span class=\"elmValue\">"+$(currOption).val()+"</span>"+$(currOption).text()+"</li>";
			}
		}

		$(wrapperElm).addClass("select_wrap").html("<div class=\"selectbox\"><ul><li>"+name+"</li></ul></div><div class=\"selectboxoptions_wrap\"></div>");
		$(wrapperElm).find(selectboxoptions_wrap).html("<ul class=\""+boxtype+"\" rev=\""+select_name+"\" >"+opts_str+"</ul>");
		$(wrapperElm).find(selectboxoptions_wrap +" ul").after("<div class=\""+classselectboxfoot+"\"><div></div></div>"); //add footer

		if("auto" != opts.selectwidth)
		{
			$(wrapperElm).find(selectbox + " ul").css({width:opts.selectwidth});
			$(wrapperElm).find(selectboxoptions_wrap + " ul").attr("class",boxtype).css({width:(opts.selectwidth+57) + "px"});
			$(wrapperElm).find(selectboxfoot + " div").css({width:opts.selectwidth + "px"});
		}else
		{
			$(wrapperElm).find(selectboxoptions_wrap + " ul").attr("class",boxtype).css({width:($(wrapperElm).find(selectbox + " ul").width()+57) + "px"});
			$(wrapperElm).find(selectboxfoot + " div").css({width:$(wrapperElm).find(selectbox + " ul").width() + "px"});
		}

		if(isDisabled){$.fn.disable($(wrapperElm).find(selectboxoptions_wrap));}

//		var thisElement = $(opts.wrappername);
		var thisElement = wrapperElm;

		//bind item clicks
		$(selectboxoptions_wrap+ " ul li").unbind().click( function() {

			if($(this).attr("class").indexOf("disabled") < 0)
			{
				var id;
				var boxtype = $(this).parent().attr("class");

				if(boxtype.indexOf("selectboxoptions_radio") >-1)
				{
					if(!$(this).hasClass(classselected))
					{
						id = $(this).find(elmValue).text();
						$(this).parent().find("." + classselected).removeClass(classselected);
						$(this).addClass(classselected);
						$(this).parent().parent().find("input").val($(this).find(elmValue).text());
					}
					else
					{
						$(this).parent().find("." + classselected).removeClass(classselected);
						$(this).parent().parent().find("input").val("");
					}
				}
				else //checkbox
				{
					if($(this).hasClass(classselected))
					{
						//turn off the checkbox
						$(this).removeClass(classselected);
						//remove hiidend field
						$(this).find("input").remove();
					}
					else
					{
						//gets the value of the element
						id = $(this).find(elmValue).text();			
						$(this).addClass(classselected);
						var var_name = $(this).parent().attr("rev");
						$(this).append("<input type=\"hidden\" name=\""+ var_name +"\" value=\""+ id +"\" />");
					}
				}
			}
		}).mouseover(function(){
			$(this).addClass(opts.hoverstyle);
		}).mouseout(function(){
			$(this).removeClass(opts.hoverstyle);
		});

		//bind sliding open
		$(thisElement).find(selectbox).unbind().toggle(
			function() {
				if(opts.isscrolling){$.fn.scrolling($(this),true);}
				//unhide li
				$(this).parent().find(selectboxoptions_wrap+ " ul li").removeClass(hideitem);
				//makes the arrow go up or down
				$(this).removeClass(classselectbox).addClass(classselectboxopen);
				//slides the options down
				$(this).parent().find(selectboxoptions_wrap).slideDown(opts.openspeed);
			},
			function() {
				var boxtype = $(this).parent().find(selectboxoptions_wrap+ " ul").attr("class");
				if($(this).parent().find(selectboxoptions_wrap+ " ul li").hasClass(classselected))
				{
					$(this).parent().find(selectboxoptions_wrap+ " ul li").addClass(hideitem);
				}	
				else
				{
					//makes the arrows go up or down
					$(this).removeClass(classselectboxopen).addClass(classselectbox);
					//slides the options up
					$(this).parent().find(selectboxoptions_wrap).slideUp("normal");
				}

				if(opts.isscrolling){$.fn.scrolling($(this),false);}
			});


			$.fn.addformelms(thisElement);
			if(opts.preopenselect){ $.fn.openSelectBoxsThatArePrePopulated();}
			if(opts.alldisabled){$.fn.disable($(thisElement));}
		});

	};

})(jQuery);



/* jquery.jAnimate.js`
 *
 * jAnimate - Riding carousels with jQuery
 *   http://sorgalla.com/jAnimate/
 *
 * Copyright (c) 2006 Robert Ernens 
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Jan Sorgalla
 *   http://sorgalla.com/jAnimate/
 */

jQuery.fn.extend({

    /**
     * Creates an animation for all matched elements.
     *
     * @example $("#myAnimation").jAnimate();
     * @before <ul id="myAnimation"><li>First item</li><li>Second item</li></ul>
     * @result
     * <div class="jAnimate-scope">
     *   <button disabled="disabled" class="jAnimate-prev jAnimate-prev-disabled">&lt;-</button>
     *   <button class="jAnimate-next">-&gt;</button>
     *   <div class="jAnimate-clip">
     *     <ul id="myAnimation" class="jAnimate-list">
     *       <li class="jAnimate-item-1">First item</li>
     *       <li class="jAnimate-item-2">Second item</li>
     *     </ul>
     *   </div>
     * </div>
     *
     * @name jAnimate
     * @type jQuery
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat jAnimate
     */
    jAnimate: function(o) {
        return this.each(function() {
            new jQuery.jAnimate(this, o);
        });
    }
});

jQuery.extend({
    /**
     * The jAnimate object.
     *
     * @constructor
     * @private
     * @name jQuery.jAnimate
     * @param Object e The element to create the carousel for.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat jAnimate
     */
    jAnimate: function(e, o) {

        // Public api of the jAnimate object passed to the
        // handler callback functions.
        var publ = this;

        /**
         * Returns the scope of the carousel which is the outer
         * <div> element containing the required markup (<ul> list,
         * prev/next buttons etc.).
         *
         * @name scope
         * @type Element
         * @cat jAnimate
         */
        publ.scope = function() { return priv.scope; };

        /**
         * Returns the list.
         *
         * @name list
         * @type Element
         * @cat jAnimate
         */
        publ.list = function() { return priv.list; };

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @name get
         * @type jQuery
         * @param Number idx The index of the element.
         * @cat jAnimate
         */
        publ.get = function(idx) { return priv.get(idx); };

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @name add
         * @type jQuery
         * @param Number idx The index of the element.
         * @param String html The innerHTML of the element.
         * @cat jAnimate
         */
        publ.add = function(idx, html) { return priv.add(idx, html); };

        /**
         * Returns true if all elements in the given range already exist,
         * false otherwise.
         *
         * @name available
         * @type Boolean
         * @param Number first The first index of the element range.
         * @param Number last The last index of the element range.
         * @cat jAnimate
         */
        publ.available = function(first, last) { return priv.available(first, last); };

        /**
         * Notifies the carousel object that updating of the carousel elements
         * has been finished. Must be called from the loadItemHandler callback
         * function after adding items with publ.add().
         *
         * @name loaded
         * @type undefined
         * @cat jAnimate
         */
        publ.loaded = function() { priv.loaded(); };

        /**
         * Moves the carousel forwards.
         *
         * @name next
         * @type undefined
         * @cat jAnimate
         */
        publ.next = function() { priv.next(); };

        /**
         * Moves the carousel backwards.
         *
         * @name prev
         * @type undefined
         * @cat jAnimate
         */
        publ.prev = function() { priv.prev(); };


        // Private methods/variables

        var priv = {
            o: {
				kind: 'scroll',
				sequence: 'sequential',
                orientation: 'horizontal',
                itemVisible: 3,
                itemScroll: null,
                animationSpeed: 0,
                auto: 0,
                autoStopOnInteract: 'hover',
                wrap: false,
                itemWidth: null,
                itemHeight: null,
                noButtons: false,
                buttonNextHTML: '<button type="button">&gt;&gt;</button>',
				buttonNextClass: 'jAnimateButton-next',
				buttonNextDisabledClass: 'jAnimateButton-disabled',
                buttonPrevHTML: '<button type="button">&lt;&lt;</button>',
				buttonPrevClass: 'jAnimateButton-prev',
				buttonPrevDisabledClass: 'jAnimateButton-disabled',
				scopeClass: 'jAnimate-scope',
				clipClass: 'jAnimate-clip',
				listClass: 'jAnimate-list',
				itemClass: 'jAnimate-item',
				loadItemHandler: null,
                nextButtonStateHandler: null,
                prevButtonStateHandler: null,
                itemFirstInHandler: null,
                itemFirstOutHandler: null,
                itemLastInHandler: null,
                itemLastOutHandler: null,
                itemVisibleInHandler: null,
                itemVisibleOutHandler: null
            },

            size: 0,
            end: 0,
            first: 0,
            prevFirst: 0,
            last: 0,
            prevLast: 0,
            inAnimation: false,
            autoTimer: null,
            nextClick: function() { priv.next(); },
            prevClick: function() { priv.prev(); },
            itemFormat: {
                "float": "left",
                "styleFloat": "left",
                "overflow": "hidden",
                "listStyle": "none"
            },

            init: function(e, o) {
                if (o)
                    jQuery.extend(priv.o, o);

                priv.o.horiz = priv.o.orientation == "vertical" ? false : true;
                priv.o.itemScroll = priv.o.itemScroll || priv.o.itemVisible;

                if (priv.o.itemWidth)
                    priv.itemFormat.width  = priv.o.itemWidth + "px";

                if (priv.o.itemHeight)
                     priv.itemFormat.height = priv.o.itemHeight + "px";

                priv.prepare(e);
                priv.calc();
                priv.resize();
				priv.setup();
                priv.buttons(false, false);
                priv.load(1, priv.o.itemVisible);
                priv.scroll(1);
                priv.startAuto();
                if(jDisplay == "none") {$(priv.scope).hide()};
            },

            get: function(idx) {
                return jQuery("." + priv.o.itemClass + "-" + idx, priv.list);
            },

            add: function(idx, s) {
                var item = priv.get(idx);

                if (item.size() == 0) {
                    var item = priv.format(document.createElement("li"), idx);
                    jQuery(priv.list).append(item);
                    priv.size++;
                    priv.resize();
                }

                return item.html(s);
            },

            available: function(first, last) {
                if (priv.end >= last) return true;

                priv.end = last;
                return false;
            },

            load: function(first, last) {
                priv.buttons(false, false);

                if (priv.o.loadItemHandler != null)
                    priv.o.loadItemHandler(publ, first, last, priv.available(first, last));
                else
                    priv.loaded();
            },

            loaded: function() {
                if (priv.first > 1 && priv.last < priv.size) {
                    priv.buttons(true, true);
                } else if (priv.first == 1 && priv.last < priv.size) {
                    priv.buttons(true, false);
                } else if (priv.first > 1 && priv.last >= priv.size) {
                    priv.buttons(priv.o.wrap, true);
                }
            },

            next: function() {
                priv.stopAuto();

                if (priv.o.autoStopOnInteract)
                    priv.disableAuto();

                priv.doNext();
            },

            doNext: function() {
                priv.scroll((priv.o.wrap && priv.last == priv.size) ? 1 : priv.first + priv.o.itemScroll);

                if (priv.o.wrap || priv.last < priv.size)
                    priv.startAuto();
            },

            prev: function() {
                priv.stopAuto();

                if (priv.o.autoStopOnInteract)
                    priv.disableAuto();

                priv.doPrev();
            },

            doPrev: function() {
                priv.scroll(priv.first - priv.o.itemScroll);
                priv.startAuto();
            },

            scroll: function(idx) {
                if (priv.inAnimation) return;
                priv.inAnimation = false;

                priv.prevFirst = priv.first;
                priv.prevLast  = priv.last;

				if ( priv.o.sequence == "random" ) {
					idx = priv.prevFirst ;
					while (	idx == priv.prevFirst ) {
						idx = Math.floor ( Math.random ( ) * ( priv.size + 1) );
						idx = idx < 1 ? 1 : idx;
					}
				}
					
                idx = idx < 1 ? 1 : idx;

                var last = idx + priv.o.itemVisible - 1;
                last = (last > priv.size) ? priv.size : last;

                var first = last - priv.o.itemVisible + 1;
                first = (first < 1) ? 1 : first;

                last = first + priv.o.itemVisible - 1;

                priv.first = first;
                priv.last  = last;

                priv.animate();
            },

            animate: function() {
	
				if (priv.o.kind == "scroll") {
                	var pos = priv.dimension * (priv.first - 1) * -1;

	                if (priv.o.animationSpeed) {
	                    priv.inAnimation = true;
	                    jQuery(priv.list).animate(priv.o.horiz ? {"left": pos} : {"top": pos}, priv.o.animationSpeed, function() { priv.scrolled(); });
	                } else {
	                    jQuery(priv.list)[priv.o.horiz ? "left" : "top"](pos + "px");
	                    priv.scrolled();
	                }
				}
				
				if (priv.o.kind == "fade") {
					priv.inAnimation = true;
					var next = jQuery("li", priv.scope).get(priv.first - 1);
					if (priv.prevFirst != 0) {
	                	var current = jQuery("li", priv.scope).get(priv.prevFirst - 1);
						jQuery(current).fadeOut(priv.o.animationSpeed);
					}
					jQuery(next).fadeIn(priv.o.animationSpeed, function() {priv.scrolled(); });
				}
				
				if (priv.o.kind == "slide") {
					priv.inAnimation = true;
					var next = jQuery("li", priv.scope).get(priv.first - 1);
					if (priv.prevFirst != 0) {
	                	var current = jQuery("li", priv.scope).get(priv.prevFirst - 1);
						jQuery(current).slideUp(priv.o.animationSpeed);
					} 
					jQuery(next).slideDown(priv.o.animationSpeed, function() { priv.scrolled();});
				}
            },

            scrolled: function() {
                if (priv.first == 1 & priv.o.kind == "slide")
                    jQuery(priv.list).css({ top:priv.top + "px", left: priv.left + "px"});

                priv.inAnimation = false;
                priv.notify(priv.prevFirst, priv.prevLast, priv.first, priv.last);
                priv.load(priv.last + 1, priv.last + priv.o.itemScroll);
            },

            notify: function(prevFirst, prevLast, first, last) {
                if (prevFirst != first) {
                    if (priv.o.itemFirstOutHandler != null)
                        priv.get(prevFirst).each(function() { priv.o.itemFirstOutHandler(publ, this, prevFirst); });

                    if (priv.o.itemFirstInHandler != null)
                        priv.get(first).each(function() { priv.o.itemFirstInHandler(publ, this, first); });
                }

                if (prevLast != last) {
                    if (priv.o.itemLastOutHandler != null)
                        priv.get(prevLast).each(function() { priv.o.itemLastOutHandler(publ, this, prevLast); });

                    if (priv.o.itemLastInHandler != null)
                        priv.get(last).each(function() { priv.o.itemLastInHandler(publ, this, last); });
                }

                if (priv.o.itemVisibleInHandler != null) {
                    for (var i = first; i <= last; i++) {
                        if (!(i >= prevFirst && i <= prevLast))
                            priv.get(i).each(function() { priv.o.itemVisibleInHandler(publ, this, i); });
                    }
                }

                if (priv.o.itemVisibleOutHandler != null) {
                    for (var i = prevFirst; i <= prevLast; i++) {
                        if (!(i >= first && i <= last))
                            priv.get(i).each(function() { priv.o.itemVisibleOutHandler(publ, this, i); });
                    }
                }
            },

            buttons: function(next, prev) {
                if (priv.o.noButtons) return;

                if (priv.o.nextButtonStateHandler != null)
                    jQuery("." + priv.o.buttonNextClass, priv.scope).each(function() { priv.o.nextButtonStateHandler(publ, this, next); });

                if (priv.o.prevButtonStateHandler != null)
                    jQuery("." + priv.o.buttonPrevClass, priv.scope).each(function() { priv.o.prevButtonStateHandler(publ, this, prev); });

                jQuery("." + priv.o.buttonNextClass, priv.scope)[next ? "bind" : "unbind"]("click", priv.nextClick)[next ? "removeClass" : "addClass"](priv.o.buttonNextDisabledClass)[next ? "removeAttr" : "attr"]("disabled", true);
                jQuery("." + priv.o.buttonPrevClass, priv.scope)[prev ? "bind" : "unbind"]("click", priv.prevClick)[prev ? "removeClass" : "addClass"](priv.o.buttonPrevDisabledClass)[prev ? "removeAttr" : "attr"]("disabled", true);
            },

            startAuto: function() {
                if (priv.o.auto > 0)
                    priv.autoTimer = setTimeout(function() { priv.doNext(); }, priv.o.auto * 1000);
            },

            stopAuto: function() {
                if (priv.autoTimer != null) {
                    clearTimeout(priv.autoTimer);
                    priv.autoTimer = null;
                }
            },

            disableAuto: function() {
                priv.stopAuto();
                priv.o.auto = 0;
            },

            resize: function() {
                if (priv.size == 0) return;

                if (priv.o.horiz)
                    jQuery(priv.list).css({ width :priv.size * priv.dimension + 100 + "px"});
                else
                    jQuery(priv.list).css({ height: priv.size * priv.dimension + 100 + "px"});
            },

            format: function(item, idx) {
                return jQuery(item).css(priv.itemFormat).addClass(priv.o.itemClass + "-" + idx);
            },

            margin: function(e, p) {
                if (p == "marginRight" && jQuery.browser.safari) {
                    var old = {"display": "block", "float": "none", "width": "auto"}, oWidth, oWidth2;

                    jQuery.swap(e, old, function() { oWidth = e.offsetWidth; });

                    old["marginRight"] = 0;
                    jQuery.swap(e, old, function() { oWidth2 = e.offsetWidth; });

                    return oWidth2 - oWidth;
                }

                return priv.intval(jQuery.css(e, p));
            },

            calc: function() {
                priv.size = jQuery("li", priv.list).size();
                priv.end = priv.size;

                if (priv.size == 0) {
                    var dummy = priv.format(document.createElement("li"), 1).get(0);
                    priv.list.appendChild(dummy);
                } else {
                    var idx = 1;
                    jQuery("li", priv.list).each(function() { priv.format(this, idx++); });
                }

                var i = jQuery("li", priv.list).get(0);

                var itemWidth  = jQuery(i).outerWidth({margin: true}) ;
                itemWidth = ( itemWidth == 0 ) ? priv.o.itemWidth : itemWidth
                
                var itemHeight = jQuery(i).outerHeight({margin: true}) ;
                itemHeight = ( itemHeight == 0 ) ? priv.o.itemHeight : itemHeight

                if (priv.o.horiz) {
                    priv.dimension = itemWidth;
                    var clipW  = itemWidth * priv.o.itemVisible - priv.margin(i, "marginRight");
                    var clipH  = itemHeight;
                } else {
                    priv.dimension = itemHeight;
                    var clipW  = itemWidth;
                    var clipH  = itemHeight * priv.o.itemVisible - priv.margin(i, "marginBottom");
                }

                jQuery("." + priv.o.clipClass, priv.scope).css({
                    "zIndex": 2,
                    "padding": 0,
                    "margin": 0,
                    "width":  clipW + "px",
                    "height": clipH + "px",
                    "overflow": "hidden",
                    "position": "relative"
                });

                priv.top  = priv.intval(jQuery(priv.list).css("top"));
                priv.left = priv.intval(jQuery(priv.list).css("left"));

                jQuery(priv.list).css({
                    "zIndex": 1,
                    "position": "relative",
                    "top": priv.top + "px",
                    "left": priv.left + "px",
                    "margin": 0,
                    "padding": 0
                });

                if (dummy != undefined)
                    priv.list.removeChild(dummy);
            },

            prepare: function(e) {
                if (e.nodeName == "UL" || e.nodeName == "OL") {
                    priv.list = e;
                    var scope = jQuery(priv.list).parent().get(0);

                    if (jQuery.className.has(scope, priv.o.clipClass)) {
                        if (!jQuery.className.has(jQuery(scope).parent().get(0), priv.o.scopeClass))
                            scope = jQuery(scope).wrap('<div class="' + priv.o.scopeClass + '"></div>');

                        scope = jQuery(scope).parent().get(0);
                    } else if (!jQuery.className.has(scope, priv.o.scopeClass))
                        scope = jQuery(priv.list).wrap('<div class="' + priv.o.scopeClass + '"></div>').parent().get(0);

                    priv.scope = scope;
                } else {
                    priv.scope = e;
                    priv.list = jQuery("ul", priv.scope).get(0) || jQuery("ol", priv.scope).get(0);
                }

                if (!jQuery.className.has(jQuery(priv.list).parent().get(0), priv.o.clipClass))
                    jQuery(priv.list).wrap('<div class="' + priv.o.clipClass + '"></div>');

                if (!priv.o.noButtons) {
                    if (jQuery("." + priv.o.buttonPrevClass, priv.scope).size() == 0) {
                        var dummy = jQuery(document.createElement("div")).html(priv.o.buttonPrevHTML).get(0);
                        jQuery("." + priv.o.clipClass, priv.scope).before(jQuery(dummy.firstChild).addClass(priv.o.prevClass));
                    }

                    if (jQuery("." + priv.o.buttonNextClass, priv.scope).size() == 0) {
                        var dummy = jQuery(document.createElement("div")).html(priv.o.buttonNextHTML).get(0);
                        jQuery("." + priv.o.clipClass, priv.scope).before(jQuery(dummy.firstChild).addClass(priv.o.nextClass));
                    }

                    jQuery("." + priv.o.buttonPrevClass, priv.scope).css({"zIndex": 3});
                    jQuery("." + priv.o.buttonNextClass, priv.scope).css({"zIndex": 3});
                }

                jQuery(priv.list).addClass(priv.o.listClass).css("position","relative");
                jQuery(priv.scope).addClass(priv.o.scopeClass);
                jDisplay = jQuery(priv.scope).css("display");
                if (jDisplay == "none") { jQuery(priv.scope).show() };
            },

            setup: function() {
				if(!priv.o.noButtons) {
					var temp = jQuery(priv.scope).find("td:hidden")
					jQuery(priv.scope).find(":hidden").show();
					if ( jQuery(temp).size() != 0) {
						jQuery(temp).hide();
					}
				} ;
				
				if (priv.o.kind == "fade") {
					jQuery("li", priv.list).css({"position": "absolute", "top": "0px", "left": "0px"});
				} ;
				
				if (priv.o.kind != "scroll") {
					jQuery("li", priv.list).hide();
					var temp = jQuery("li", priv.list).get(0);
					jQuery(temp).show();
				} ;
            },

            intval: function(v) {
                v = parseInt(v);
                return isNaN(v) ? 0 : v;
            }
        };

        // Initialize the carousel
        priv.init(e, o);
    }
});

/* jquery.lightbox.js
 *
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.4.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.4m
 * @date November 17, 2007
 * @category jQuery plugin
 * @copyright (c) 2007 Leandro Vieira Pinho (leandrovieira.com)
 * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin 
 * @modfied by Robert Ernens to handle large images and div scroller showing through
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias 

(function($) {
	/**
	 * $ is an alias to jQuery object
	 *
	 */
	$.fn.lightBox = function(settings) {
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#000',		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
			overlayOpacity:			0.8,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
			// Configuration related to images
			imageLoading:			'images/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
			imageBtnPrev:			'images/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
			imageBtnNext:			'images/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
			imageBtnClose:			'images/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
			imageBlank:				'images/lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
			// Configuration related to container image box
			containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
			containerResizeSpeed:	400,		// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
			// Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
			txtImage:				'Image',	// (string) Specify text "Image"
			txtOf:					'of',		// (string) Specify text "of"
			// Configuration related to keyboard navigation
			keyToClose:				'c',		// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
			keyToPrev:				'p',		// (string) (p = previous) Letter to show the previous image
			keyToNext:				'n',		// (string) (n = next) Letter to show the next image.
			// Don´t alter these variables in any way
			imageArray:				[],
			activeImage:			0
		},settings);
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		/**
		 * Initializing the plugin calling the start function
		 *
		 * @return boolean false
		 */
		function _initialize() {
			_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
			return false; // Avoid the browser following the link
		}
		/**
		 * Start the jQuery lightBox plugin
		 *
		 * @param object objClicked The object (link) whick the user have clicked
		 * @param object jQueryMatchedObj The jQuery object with all elements matched
		 */
		function _start(objClicked,jQueryMatchedObj) {
			// Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'hidden' });
			// Call the function to create the markup structure; style some elements; assign events in some elements.
			_set_interface();
			// Unset total images in imageArray
			settings.imageArray.length = 0;
			// Unset image active information
			settings.activeImage = 0;
			// We have an image set? Or just an image? Let´s see it.
			if ( jQueryMatchedObj.length == 1 ) {
				settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));
			} else {
				// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references		
				for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
					settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));
				}
			}
			while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
				settings.activeImage++;
			}
			// Call the function that prepares image exibition
			_set_image_to_view();
		}
		/**
		 * Create the jQuery lightBox plugin interface
		 *
		 * The HTML markup will be like that:
			<div id="jquery-overlay"></div>
			<div id="jquery-lightbox">
				<div id="lightbox-container-image-box">
					<div id="lightbox-container-image">
						<img src="../fotos/XX.jpg" id="lightbox-image">
						<div id="lightbox-nav">
							<a href="#" id="lightbox-nav-btnPrev"></a>
							<a href="#" id="lightbox-nav-btnNext"></a>
						</div>
						<div id="lightbox-loading">
							<a href="#" id="lightbox-loading-link">
								<img src="../images/lightbox-ico-loading.gif">
							</a>
						</div>
					</div>
				</div>
				<div id="lightbox-container-image-data-box">
					<div id="lightbox-container-image-data">
						<div id="lightbox-image-details">
							<span id="lightbox-image-details-caption"></span>
							<span id="lightbox-image-details-currentNumber"></span>
						</div>
						<div id="lightbox-secNav">
							<a href="#" id="lightbox-secNav-btnClose">
								<img src="../images/lightbox-btn-close.gif">
							</a>
						</div>
					</div>
				</div>
			</div>
		 *
		 */
		function _set_interface() {
			// Apply the HTML markup into body tag 
			// mod 0.4m - 11/23/07 - R. Ernens : added iframe to address overflow: autod div showing scroller through overlay and image
			$('body').append('<iframe id="jquery-hideselect"></iframe><div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.imageLoading + '"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>');	
			// Get page sizes
			var arrPageSizes = ___getPageSize();
			// Style overlay and show it
			$('#jquery-overlay').css({
				backgroundColor:	settings.overlayBgColor,
				opacity:			settings.overlayOpacity,
				width:				arrPageSizes[0],
				height:				arrPageSizes[1]
			}).fadeIn();
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			// Calculate top and left offset for the jquery-lightbox div object and show it
			$('#jquery-lightbox').css({
				top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
				left:	arrPageScroll[0]
			}).show();
			// Assigning click events in elements to close overlay
			$('#jquery-overlay,#jquery-lightbox').click(function() {
				_finish();									
			});
			// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
			$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
				_finish();
				return false;
			});
			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				// Get page sizes
				var arrPageSizes = ___getPageSize();
				// Style hideselect iframe and show it
				$('#jquery-hideselect').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
				// Style overlay and show it
				$('#jquery-overlay').css({
					width:		arrPageSizes[0],
					height:		arrPageSizes[1]
				});
				// Get page scroll
				var arrPageScroll = ___getPageScroll();
				// Calculate top and left offset for the jquery-lightbox div object and show it
				$('#jquery-lightbox').css({
					top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
					left:	arrPageScroll[0]
				});
			});
		}
		/**
		 * Prepares image exibition; doing a image´s preloader to calculate it´s size
		 *
		 */
		function _set_image_to_view() { // show the loading
			// Show the loading
			$('#lightbox-loading').show();
			// Hide some elements
			$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			// Image preload process
			var objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]); 
				// mod 0.4m - 11/23/2007 - R. Ernens : Resizing large images 
				var arrPageSizes = ___getPageSize();
				var x = arrPageSizes[2] - 150;
				var y = arrPageSizes[3] - 150;
				var imageWidth = objImagePreloader.width;
				var imageHeight = objImagePreloader.height;
				if (imageWidth > x) {
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x; 
					if (imageHeight > y) { 
						imageWidth = imageWidth * (y / imageHeight); 
						imageHeight = y; 
					}
				} else if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
					if (imageWidth > x) { 
						imageHeight = imageHeight * (x / imageWidth); 
						imageWidth = x;
					}
				}
				$('#lightbox-image').css({
					width:		imageWidth,
					height:		imageHeight
				});
				// Perfomance an effect in the image container resizing it
				_resize_container_image_box(imageWidth,imageHeight);
				// mod 0.4m - 11/23/2007 - R. Ernens : End Resizing 
				//	clear onLoad, IE behaves irratically with animated gifs otherwise
				objImagePreloader.onload=function(){};
			}
			objImagePreloader.src = settings.imageArray[settings.activeImage][0];
		};
		/**
		 * Perfomance an effect in the image container resizing it
		 *
		 * @param integer intImageWidth The image´s width that will be showed
		 * @param integer intImageHeight The image´s height that will be showed
		 */
		function _resize_container_image_box(intImageWidth,intImageHeight) {
			// Get current width and height
			var intCurrentWidth = $('#lightbox-container-image-box').width();
			var intCurrentHeight = $('#lightbox-container-image-box').height();
			// Get the width and height of the selected image plus the padding
			var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image´s width and the left and right padding value
			var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the image´s height and the left and right padding value
			// Diferences
			var intDiffW = intCurrentWidth - intWidth;
			var intDiffH = intCurrentHeight - intHeight;
			// Perfomance the effect
			$('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { _show_image(); });
			if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
				if ( $.browser.msie ) {
					___pause(250);
				} else {
					___pause(100);	
				}
			}
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) }); 
			$('#lightbox-container-image-data-box').css({ width: intImageWidth });
		};
		/**
		 * Show the prepared image
		 *
		 */
		function _show_image() {
			$('#lightbox-loading').hide();
			$('#lightbox-image').fadeIn(function() {
				_show_image_data();
				_set_navigation();
			});
			_preload_neighbor_images();
		};
		/**
		 * Show the image information
		 *
		 */
		function _show_image_data() {
			$('#lightbox-container-image-data-box').slideDown('fast');
			$('#lightbox-image-details-caption').hide();
			if ( settings.imageArray[settings.activeImage][1] ) {
				$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
			}
			// If we have a image set, display 'Image X of X'
			if ( settings.imageArray.length > 1 ) {
				$('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
			}		
		}
		/**
		 * Display the button navigations
		 *
		 */
		function _set_navigation() {
			$('#lightbox-nav').show();

			// Instead to define this configuration in CSS file, we define here. And it´s need to IE. Just.
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });

			// Show the prev button, if not the first image in set
			if ( settings.activeImage != 0 ) {
				// Show the images button for Next buttons
				$('#lightbox-nav-btnPrev').unbind().hover(function() {
					$(this).css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' });
				},function() {
					$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
				}).show().bind('click',function() {
					settings.activeImage = settings.activeImage - 1;
					_set_image_to_view();
					return false;
				});
			}

			// Show the next button, if not the last image in set
			if ( settings.activeImage != ( settings.imageArray.length -1 ) ) {
				// Show the images button for Next buttons
				$('#lightbox-nav-btnNext').unbind().hover(function() {
					$(this).css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' });
				},function() {
					$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
				}).show().bind('click',function() {
					settings.activeImage = settings.activeImage + 1;
					_set_image_to_view();
					return false;
				});
			}
			// Enable keyboard navigation
			_enable_keyboard_navigation();
		}
		/**
		 * Enable a support to keyboard navigation
		 *
		 */
		function _enable_keyboard_navigation() {
			$(document).keydown(function(objEvent) {
				_keyboard_action(objEvent);
			});
		}
		/**
		 * Disable the support to keyboard navigation
		 *
		 */
		function _disable_keyboard_navigation() {
			$(document).unbind();
		}
		/**
		 * Perform the keyboard actions
		 *
		 */
		function _keyboard_action(objEvent) {
			// To ie
			if ( objEvent == null ) {
				keycode = event.keyCode;
				escapeKey = 27;
			// To Mozilla
			} else {
				keycode = objEvent.keyCode;
				escapeKey = objEvent.DOM_VK_ESCAPE;
			}
			// Get the key in lower case form
			key = String.fromCharCode(keycode).toLowerCase();
			// Verify the keys to close the ligthBox
			if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
				_finish();
			}
			// Verify the key to show the previous image
			if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) {
				// If we´re not showing the first image, call the previous
				if ( settings.activeImage != 0 ) {
					settings.activeImage = settings.activeImage - 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
			// Verify the key to show the next image
			if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) {
				// If we´re not showing the last image, call the next
				if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) {
					settings.activeImage = settings.activeImage + 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
		}
		/**
		 * Preload prev and next images being showed
		 *
		 */
		function _preload_neighbor_images() {
			if ( (settings.imageArray.length -1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = settings.imageArray[settings.activeImage + 1][0];
			}
			if ( settings.activeImage > 0 ) {
				objPrev = new Image();
				objPrev.src = settings.imageArray[settings.activeImage -1][0];
			}
		}
		/**
		 * Remove jQuery lightBox plugin HTML markup
		 *
		 */
		function _finish() {
			$('#jquery-lightbox').remove();
			$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
			$('#jquery-hideselect').remove();
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}
		/**
		 / THIRD FUNCTION
		 * getPageSize() by quirksmode.com
		 *
		 * @return Array Return an array with page width, height and window width, height
		 */
		function ___getPageSize() {
			var xScroll, yScroll;
			if (window.innerHeight && window.scrollMaxY) {	
				xScroll = window.innerWidth + window.scrollMaxX;
				yScroll = window.innerHeight + window.scrollMaxY;
			} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
				xScroll = document.body.scrollWidth;
				yScroll = document.body.scrollHeight;
			} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
				xScroll = document.body.offsetWidth;
				yScroll = document.body.offsetHeight;
			}
			var windowWidth, windowHeight;
			if (self.innerHeight) {	// all except Explorer
				if(document.documentElement.clientWidth){
					windowWidth = document.documentElement.clientWidth; 
				} else {
					windowWidth = self.innerWidth;
				}
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowWidth = document.documentElement.clientWidth;
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers
				windowWidth = document.body.clientWidth;
				windowHeight = document.body.clientHeight;
			}	
			// for small pages with total height less then height of the viewport
			if(yScroll < windowHeight){
				pageHeight = windowHeight;
			} else { 
				pageHeight = yScroll;
			}
			// for small pages with total width less then width of the viewport
			if(xScroll < windowWidth){	
				pageWidth = xScroll;		
			} else {
				pageWidth = windowWidth;
			}
			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
			return arrayPageSize;
		};
		/**
		 / THIRD FUNCTION
		 * getPageScroll() by quirksmode.com
		 *
		 * @return Array Return an array with x,y page scroll values.
		 */
		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;
		};
		 /**
		  * Stop the code execution from a escified time in milisecond
		  *
		  */
		 function ___pause(ms) {
			var date = new Date(); 
			curDate = null;
			do { var curDate = new Date(); }
			while ( curDate - date < ms);
		 };
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery); // Call and execute the function immediately passing the jQuery object

/* jquery.clueTips.js
 *
 * jQuery clueTip plugin
 * Version 0.9.4  (11/14/2007)
 * @requires jQuery v1.1.1+
 * @requires Dimensions plugin 
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
(function($) { 
/*
 * @name clueTip
 * @type jQuery
 * @cat Plugins/tooltip
 * @return jQuery
 * @author Karl Swedberg
 *
 * @credit Inspired by Cody Lindley's jTip (http://www.codylindley.com)
 * @credit Thanks to Shelane Enos for the feature ideas 
 * @credit Thanks to the following people for their expert advice, code enhancements, bug fixes, etc.:
      Glen Lipka, Hector Santos, Torben Schreiter, Dan G. Switzer, Jörn Zaefferer 
 * @credit Thanks to Jonathan Chaffer, as always, for help with the hard parts. :-)
 */

 /**
 * 
 * Displays a highly customizable tooltip when the user hovers (default) or clicks (optional) the matched element. 
 * By default, the clueTip plugin loads a page indicated by the "rel" attribute via ajax and displays its contents.
 * If a "title" attribute is specified, its value is used as the clueTip's heading.
 * The attribute to be used for both the body and the heading of the clueTip is user-configurable. 
 * Optionally, the clueTip's body can display content from an element on the same page.
 * * Just indicate the element's id (e.g. "#some-id") in the rel attribute.
 * Optionally, the clueTip's body can display content from the title attribute, when a delimiter is indicated. 
 * * The string before the first instance of the delimiter is set as the clueTip's heading.
 * * All subsequent strings are wrapped in separate DIVs and placed in the clueTip's body.
 * The clueTip plugin allows for many, many more options. Pleasee see the examples and the option descriptions below...
 * 
 * 
 * @example $('#tip).cluetip();
 * @desc This is the most basic clueTip. It displays a 275px-wide clueTip on mouseover of the element with an ID of "tip." On mouseout of the element, the clueTip is hidden.
 *
 *
 * @example $('a.clue').cluetip({
 *  hoverClass: 'highlight',
 *  sticky: true,
 *  closePosition: 'bottom',
 *  closeText: '<img src="cross.png" alt="close" />',
 *  truncate: 60,
 *  ajaxSettings: {
 *    type: 'POST'
 *  }
 * });
 * @desc Displays a clueTip on mouseover of all <a> elements with class="clue". The hovered element gets a class of "highlight" added to it (so that it can be styled appropriately. This is esp. useful for non-anchor elements.). The clueTip is "sticky," which means that it will not be hidden until the user either clicks on its "close" text/graphic or displays another clueTip. The "close" text/graphic is set to diplay at the bottom of the clueTip (default is top) and display an image rather than the default "Close" text. Moreover, the body of the clueTip is truncated to the first 60 characters, which are followed by an ellipsis (...). Finally, the clueTip retrieves the content using POST rather than the $.ajax method's default "GET."
 * 
 * More examples can be found at http://plugins.learningjquery.com/cluetip/demo/
 *
 * @param Object defaults (optional) Customize your clueTips
 * @option Integer width: default is 275. The width of the clueTip
 * @option Integer|String height: default is 'auto'. The height of the clueTip. Setting a specific height also sets  <div id="cluetip-outer"> to overflow:auto
 * @option Integer cluezIndex: default is 97; sets the z-index style property of the clueTip.
 * @option String positionBy: default is 'auto'. Available options: 'auto', 'mouse', 'bottomTop', 'fixed'. Change to 'mouse' if you want to override positioning by element and position the clueTip based on where the mouse is instead. Change to 'bottomTop' if you want positioning to begin below the mouse when there is room or above if not -- rather than right or left of the elemnent and flush with element's top Change to 'fixed' if you want the clueTip to appear in exactly the same location relative to the linked element no matter where it appears on the page. Use 'fixed' at your own risk.
 * @option Integer topOffset: number of pixels to offset the clueTip from the top of the linked element. For positionBy "auto", "mouse", and "bottomTop" the number will be added to the clueTip's "top" value if the clueTip appears below the linked element and subtracted from it if the clueTip appears above. For positionBy "fixed", the number will be added to the "top" value, offsetting the clueTip from the top of the linked element.
 * @option Integer leftOffset: number of pixels to offset the cluetip horizontally from the linked element. For positionBy "auto", "mouse", and "bottomTop" the number will be added to clueTip's "left" value if the clueTip appears to the right of the linked element and subtracted if the clueTip appears to the left. For positionBy "fixed", the number will be added to the "left" value of the clueTip, offsetting it from the right-most part of the linked element. 
 * @option Boolean local: default is false. Whether to use content from the same page (using ID) for clueTip body
 * @option Boolean hideLocal: default is true. If local option is set to true, determine whether local content to be shown in clueTip should be hidden at its original location. 
 * @option String attribute default is 'rel'. The attribute to be used for the URL of the ajaxed content
 * @option Boolean showtitle: default is true. Shows the title bar of the clueTip, whether a title attribute has been set or not. Change this to false to hide the title bar.
 * @option String cluetipClass: default is 'default'; this adds a class to the outermost clueTip div with a class name in the form of 'cluetip-' + clueTipClass. It also adds "clue-left-default" or "clue-right-default" to the same div, depending on whether the clueTip is to the left or to the right of the link element. This allows you to create your own clueTip theme in a separate CSS file or use one of the three pre-packaged themes: default, jtip, or rounded.
 * @option String titleAttribute: default is 'title'. The attribute to be used for the clueTip's heading, if the attribute exists for the hovered element.
 * @option String splitTitle: default is '' (empty string). A character used to split the title attribute into the clueTip title and divs within the clueTip body; if used, the clueTip will be populated only by the title attribute, 
 * @option String hoverClass: default is empty string. designate one to apply to the hovered element
 * @option String closePosition: default is 'top'. Set to 'bottom' to put the closeText at the bottom of the clueTip body
 * @option String closeText: default is 'Close'. This determines the text to be clicked to close a clueTip when sticky is set to true.
 * @option Number truncate: default is 0. Set to some number greater than 0 to truncate the text in the body of the clueTip. This also removes all HTML/images from the clueTip body.
 * @option Boolean waitImage: default is true. Set to false to avoid having the plugin try to show/hide the image.
 * @option Boolean arrows: Default is false. Set to true to display an arrow at the appropriate side of the cluetip and lined vertically with the hovered element.
 * @option Boolean dropShadow: default is true; set it to false if you do not want the drop-shadow effect on the clueTip
 * @option Integer dropShadowSteps: default is 6; change this number to adjust the size of the drop shadow
 * @option Boolean sticky: default is false. Set to true to keep the clueTip visible until the user either closes it manually by clicking on the CloseText or display another clueTip.
 * @option Object fx: default is: {open: 'show', openSpeed: ''}. Change these to apply one of jQuery's effects when opening the clueTip
 * @option String activation: default is 'hover'. Set to 'toggle' to force the user to click the element in order to activate the clueTip.
 * @option Object hoverIntent: default is {sensitivity: 3, interval: 50, timeout: 0}. If jquery.hoverintent.js plugin is included in <head>, hoverIntent() will be used with these settings instead of hover(). Set to false if for some reason you have the hoverintent plugin included but don't want to use it. For info on hoverIntent options, see http://cherne.net/brian/resources/jquery.hoverIntent.html
 * @option Function onShow: default is function (ct, c){} ; allows you to pass in your own function once the clueTip has shown.
 * @option Boolean ajaxCache: Default is true; caches the results of the ajax request to avoid unnecessary hits to the server. When set to false, the script will make an ajax request every time the clueTip is shown, which allows for dynamic content to be loaded.
 * @option Object ajaxProcess: Default is function(data) { data = $(data).not('style, meta, link, script, title); return data; } . When getting clueTip content via ajax, allows processing of it before it's displayed. The default value strips out elements typically found in the <head> that might interfere with current page.
 * @option Object ajaxSettings: allows you to pass in standard $.ajax() parameters, not including error, complete, success, and url. Default is { dataType: 'html'}
 *
 */
  var $cluetip, $cluetipInner, $cluetipOuter, $cluetipTitle, $cluetipArrows, $dropShadow, imgCount;
  $.fn.cluetip = function(options) {
    var defaults = {  // set up default options
      width:            200,
      height:           'auto',
      cluezIndex:       97,
      positionBy:       'auto',
      topOffset:        15,
      leftOffset:       15,
      local:            false,
      hideLocal:        true,
      attribute:        'rel',
      titleAttribute:   'title',
      splitTitle:       '',
      showTitle:        true,
      cluetipClass:     'default',
      hoverClass:       '',
      waitImage:        true,
      cursor:           'help',
      arrows:           false, 
      dropShadow:       true,
      dropShadowSteps:  6,
      sticky:           false,
      mouseOutClose:    false,
      activation:       'hover',
      closePosition:    'top',
      closeText:        'Close',
      truncate:         0,
      fx: {             
                        open:       'fadeIn',
                        openSpeed:  ''
      },                
      hoverIntent: {    
                        sensitivity:  3,
                			  interval:     50,
                			  timeout:      0
      },                
      onActivate:       function(e) {return true;},
      onShow:           function(ct, c){},
      ajaxCache:        true,  
      ajaxProcess:      function(data) {
                          data = $(data).not('style, meta, link, script, title');
                          return data;
      },                
      ajaxSettings: {   
                        dataType: 'html'
      }
    };
    
    if (options && options.ajaxSettings) {
      $.extend(defaults.ajaxSettings, options.ajaxSettings);
      delete options.ajaxSettings;
    }
    if (options && options.fx) {
      $.extend(defaults.fx, options.fx);
      delete options.fx;
    }
    if (options && options.hoverIntent) {
      $.extend(defaults.hoverIntent, options.hoverIntent);
      delete options.hoverIntent;
    }
    $.extend(defaults, options);
    
    return this.each(function() {
      // start out with no contents (for ajax activation)
      var cluetipContents = false;
      var cluezIndex = parseInt(defaults.cluezIndex, 10)-1;
      var isActive = false;
      
      // create the cluetip divs
      if (!$cluetip) {
        $cluetipInner = $('<div id="cluetip-inner"></div>');
        $cluetipTitle = $('<h3 id="cluetip-title"></h3>');        
        $cluetipOuter = $('<div id="cluetip-outer"></div>').append($cluetipInner).prepend($cluetipTitle);
        $cluetip = $('<div></div>').attr({'id': 'cluetip'}).css({zIndex: defaults.cluezIndex})
        .append($cluetipOuter).append('<div id="cluetip-extra"></div>')[insertionType](insertionElement).hide();
        $('<div id="cluetip-waitimage"></div>').css({position: 'absolute', zIndex: cluezIndex-1})
        .insertBefore('#cluetip').hide();
        $cluetip.css({position: 'absolute', zIndex: cluezIndex});
        $cluetipOuter.css({position: 'relative', zIndex: cluezIndex+1});
        $cluetipArrows = $('<div id="cluetip-arrows" class="cluetip-arrows"></div>').css({zIndex: cluezIndex+1}).appendTo('#cluetip');
      }
      var dropShadowSteps = (defaults.dropShadow) ? +defaults.dropShadowSteps : 0;
      if (!$dropShadow) {
        $dropShadow = $([]);
        for (var i=0; i < dropShadowSteps; i++) {
          $dropShadow = $dropShadow.add($('<div></div>').css({zIndex: cluezIndex-i-1, opacity:.1, top: 1+i, left: 1+i}));
        };
        $dropShadow.css({position: 'absolute', backgroundColor: 'silver'})
        .prependTo($cluetip);
      }
      var $this = $(this);      
      var tipAttribute = $this.attr(defaults.attribute), ctClass = defaults.cluetipClass;
      if (!tipAttribute && !defaults.splitTitle) return true;
      // if hideLocal is set to true, on DOM ready hide the local content that will be displayed in the clueTip
      if (defaults.local && defaults.hideLocal) { $(tipAttribute + ':first').hide(); }
      var tOffset = parseInt(defaults.topOffset, 10), lOffset = parseInt(defaults.leftOffset, 10);
      // vertical measurement variables
      var tipHeight, wHeight;
      var defHeight = isNaN(parseInt(defaults.height, 10)) ? 'auto' : (/\D/g).test(defaults.height) ? defaults.height : defaults.height + 'px';
      var sTop, linkTop, posY, tipY, mouseY;
      // horizontal measurement variables
      var tipWidth = parseInt(defaults.width, 10) + parseInt($cluetip.css('paddingLeft')) + parseInt($cluetip.css('paddingRight')) + dropShadowSteps;
      if( isNaN(tipWidth) ) tipWidth = 275;
      var linkWidth = this.offsetWidth;
      var linkLeft, posX, tipX, mouseX, winWidth;
            
      // parse the title
      var tipParts;
      var tipTitle = (defaults.attribute != 'title') ? $this.attr(defaults.titleAttribute) : '';
      if (defaults.splitTitle && tipTitle) {
        tipParts = tipTitle.split(defaults.splitTitle);
        if (defaults.showTitle) {
          tipTitle = tipParts.shift();
        } else {
          tipTitle = '';
        }
      }
      var localContent;

/***************************************      
* ACTIVATION
****************************************/
    
//activate clueTip
    var activate = function(event) {
      if (!defaults.onActivate($this)) {
        return false;
      }
      isActive = true;
      $cluetip.removeClass().css({width: defaults.width});
      if (tipAttribute == $this.attr('href')) {
        $this.css('cursor', defaults.cursor);
      }
      $this.attr('title','');
      if (defaults.hoverClass) {
        $this.addClass(defaults.hoverClass);
      }
      linkTop = posY = $this.offset().top;
      linkLeft = $this.offset().left;
      mouseX = event.pageX;
      mouseY = event.pageY;
      if ($this[0].tagName.toLowerCase() != 'area') {
        sTop = $(document).scrollTop();
        winWidth = $(window).width();
      }
// position clueTip horizontally
      if (defaults.positionBy == 'fixed') {
        posX = linkWidth + linkLeft + lOffset;
        $cluetip.css({left: posX});
      } else {
        posX = (linkWidth > linkLeft && linkLeft > tipWidth)
          || linkLeft + linkWidth + tipWidth + lOffset > winWidth 
          ? linkLeft - tipWidth - lOffset 
          : linkWidth + linkLeft + lOffset;
        if ($this[0].tagName.toLowerCase() == 'area' || defaults.positionBy == 'mouse' || linkWidth + tipWidth > winWidth) { // position by mouse
          if (mouseX + 20 + tipWidth > winWidth) {  
            posX = (mouseX - tipWidth - lOffset) >= 0 ? mouseX - tipWidth - lOffset :  mouseX - (tipWidth/2);
          } else {
            posX = mouseX + lOffset;
          }
//          var pY = posX < 0 ? event.pageY + tOffset : event.pageY;
        }
        $cluetip.css({left: (posX > 0 && defaults.positionBy != 'bottomTop') ? posX : (mouseX + (tipWidth/2) > winWidth) ? winWidth/2 - tipWidth/2 : Math.max(mouseX - (tipWidth/2),0)});
      }  
      var pY = posX < 0 ? event.pageY + tOffset : event.pageY;
      wHeight = $(window).height();

/***************************************
* load the title attribute only (or user-selected attribute). 
* clueTip title is the string before the first delimiter
* subsequent delimiters place clueTip body text on separate lines
***************************************/
      if (tipParts) {
        for (var i=0; i < tipParts.length; i++){
          if (i == 0) {
            $cluetipInner.html(tipParts[i]);
          } else { 
            $cluetipInner.append('<div class="split-body">' + tipParts[i] + '</div>');
          }            
        };
        cluetipShow(pY);
      }
/***************************************
* discard if no tipAttrubute          
***************************************/
      else if (!tipAttribute) {
      }
/***************************************
* load external file via ajax          
***************************************/
      else if (!defaults.local && tipAttribute.indexOf('#') != 0) {
        if (cluetipContents && defaults.ajaxCache) {
          $cluetipInner.html(cluetipContents);
          cluetipShow(pY);
        }
        else {
          var ajaxSettings = defaults.ajaxSettings;
          ajaxSettings.url = tipAttribute;
          ajaxSettings.beforeSend = function() {
            $cluetipOuter.children().empty();
            if (defaults.waitImage) {
              $('#cluetip-waitimage')
              .css({top: mouseY-10, left: parseInt(posX+(tipWidth/2),10)})
              .show();
            }
          };
         ajaxSettings.error = function() {
            if (isActive) {
              $cluetipInner.html('<i>sorry, the contents could not be loaded</i>');
            }
          };
          ajaxSettings.success = function(data) {
            cluetipContents = defaults.ajaxProcess(data);
            if (isActive) {
              $cluetipInner.html(cluetipContents);
            }
          };
          ajaxSettings.complete = function() {
          	imgCount = $('#cluetip-inner img').length;
        		if (imgCount) {
        		  $('#cluetip-inner img').load( function(){
          			imgCount--;
          			if (imgCount<1) {
          				$('#cluetip-waitimage').hide();
          			  if (isActive) cluetipShow(pY);
          			}
        		  }); 
        		} else {
      				$('#cluetip-waitimage').hide();
        		  if (isActive) cluetipShow(pY);    
        		} 
          };
          $.ajax(ajaxSettings);
        }

/***************************************
* load an element from the same page
***************************************/
      } else if (defaults.local){
        var $localContent = $(tipAttribute + ':first');
        var localCluetip = $.fn.wrapInner ? $localContent.wrapInner('<div></div>').children().clone(true) : $localContent.html();
        $.fn.wrapInner ? $cluetipInner.empty().append(localCluetip) : $cluetipInner.html(localCluetip);
        cluetipShow(pY);
      }
    };

// get dimensions and options for cluetip and prepare it to be shown
    var cluetipShow = function(bpY) {
      $cluetip.addClass('cluetip-' + ctClass);
      
      if (defaults.truncate) { 
        var $truncloaded = $cluetipInner.text().slice(0,defaults.truncate) + '...';
        $cluetipInner.html($truncloaded);
      }
      function doNothing() {}; //empty function
      tipTitle ? $cluetipTitle.show().html(tipTitle) : (defaults.showTitle) ? $cluetipTitle.show().html('&nbsp;') : $cluetipTitle.hide();
      if (defaults.sticky) {
        var $closeLink = $('<div id="cluetip-close"><a href="#">' + defaults.closeText + '</a></div>');
        (defaults.closePosition == 'bottom') ? $closeLink.appendTo($cluetipInner) : (defaults.closePosition == 'title') ? $closeLink.prependTo($cluetipTitle) : $closeLink.prependTo($cluetipInner);
        $closeLink.click(function() {
          cluetipClose();
          return false;
        });
        if (defaults.mouseOutClose) {
          $cluetip.hover(function() {doNothing(); }, 
          function() {$closeLink.trigger('click'); });
        } else {
          $cluetip.unbind('mouseout');
        }
      }
// now that content is loaded, finish the positioning 
      var direction = '';
      $cluetipOuter.css({overflow: defHeight == 'auto' ? 'visible' : 'auto', height: defHeight});
      tipHeight = defHeight == 'auto' ? $cluetip.outerHeight() : parseInt(defHeight,10);   
      tipY = posY;      
      if (defaults.positionBy == 'fixed') {
        tipY = posY - defaults.dropShadowSteps + tOffset;
      } else if ( (posX < mouseX && Math.max(posX, 0) + tipWidth > mouseX) || defaults.positionBy == 'bottomTop') {
        if (posY + tipHeight + tOffset > sTop + wHeight && mouseY - sTop > tipHeight + tOffset) { 
          tipY = mouseY - tipHeight - tOffset;
          direction = 'top';
        } else { 
          tipY = mouseY + tOffset;
          direction = 'bottom';
        }
      } else if ( posY + tipHeight + tOffset > sTop + wHeight ) {
        tipY = (tipHeight >= wHeight) ? sTop : sTop + wHeight - tipHeight - tOffset;
      } else if ($this.css('display') == 'block' || $this[0].tagName.toLowerCase() == 'area' || defaults.positionBy == "mouse") {
        tipY = bpY - tOffset;
      } else {
        tipY = posY - defaults.dropShadowSteps;
      }
      if (direction == '') {
        posX < linkLeft ? direction = 'left' : direction = 'right';
      }
      $cluetip.css({top: tipY + 'px'}).removeClass().addClass('clue-' + direction + '-' + ctClass).addClass(' cluetip-' + ctClass);
      if (defaults.arrows) { // set up background positioning to align with element
        var bgY = (posY - tipY - defaults.dropShadowSteps);
        $cluetipArrows.css({top: (/(left|right)/.test(direction) && posX >=0 && bgY > 0) ? bgY + 'px' : /(left|right)/.test(direction) ? 0 : ''}).show();
      } else {
        $cluetipArrows.hide();
      }

// (first hide, then) ***SHOW THE CLUETIP***
      $dropShadow.hide();
      $cluetip.hide()[defaults.fx.open](defaults.fx.open != 'show' && defaults.fx.openSpeed);
      if (defaults.dropShadow) $dropShadow.css({height: tipHeight, width: defaults.width}).show();
      // trigger the optional onShow function
      defaults.onShow($cluetip, $cluetipInner);
    };

/***************************************
   =INACTIVATION
-------------------------------------- */
    var inactivate = function() {
      isActive = false;
      $('#cluetip-waitimage').hide();
      if (!defaults.sticky) {
        cluetipClose();
      };
      if (defaults.hoverClass) {
        $this.removeClass(defaults.hoverClass);
      }
    };
// close cluetip and reset some things
    var cluetipClose = function() {
      $cluetipOuter 
      .parent().hide().removeClass().end()
      .children().empty();
      if (tipTitle) {
        $this.attr('title', tipTitle);
      }
      $this.css('cursor','');
      if (defaults.arrows) $cluetipArrows.css({top: ''});
    };

/***************************************
   =BIND EVENTS
-------------------------------------- */
  // activate by click
      if (defaults.activation == 'click'||defaults.activation == 'toggle') {
        $this.click(function(event) {
          if ($cluetip.is(':hidden')) {
            activate(event);
          } else {
            inactivate(event);
          }
          this.blur();
          return false;
        });
  // activate by hover
    // clicking is returned false if cluetip url is same as href url
      } else {
        $this.click(function() {
          if (tipAttribute == $this.attr('href')) {
            return false;
          }
        });
        if ($.fn.hoverIntent && defaults.hoverIntent) {
          $this.hoverIntent({
            sensitivity: defaults.hoverIntent.sensitivity,
            interval: defaults.hoverIntent.interval,  
            over: function(event) {activate(event);}, 
            timeout: defaults.hoverIntent.timeout,  
            out: function(event) {inactivate(event);}
          });           
        } else {
          $this.hover(function(event) {
            activate(event);
          }, function(event) {
            inactivate(event);
          });
        }
      }
    });
  };
  
/*
 * Global defaults for clueTips. Apply to all calls to the clueTip plugin.
 *
 * @example $.cluetip.setup({
 *   insertionType: 'prependTo',
 *   insertionElement: '#container'
 * });
 * 
 * @property
 * @name $.cluetip.setup
 * @type Map
 * @cat Plugins/tooltip
 * @option String insertionType: Default is 'appendTo'. Determines the method to be used for inserting the clueTip into the DOM. Permitted values are 'appendTo', 'prependTo', 'insertBefore', and 'insertAfter'
 * @option String insertionElement: Default is 'body'. Determines which element in the DOM the plugin will reference when inserting the clueTip.
 *
 */
   
  var insertionType = 'appendTo', insertionElement = 'body';
  $.cluetip = {};
  $.cluetip.setup = function(options) {
    if (options && options.insertionType && (options.insertionType).match(/appendTo|prependTo|insertBefore|insertAfter/)) {
      insertionType = options.insertionType;
    }
    if (options && options.insertionElement) {
      insertionElement = options.insertionElement;
    }
  };
})(jQuery); 

/*
 * jQuery corner plugin
 *
 * version 1.92 (12/18/2007)
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

/**
 * The corner() method provides a simple way of styling DOM elements.  
 *
 * corner() takes a single string argument:  $().corner("effect corners width")
 *
 *   effect:  The name of the effect to apply, such as round or bevel. 
 *            If you don't specify an effect, rounding is used.
 *
 *   corners: The corners can be one or more of top, bottom, tr, tl, br, or bl. 
 *            By default, all four corners are adorned. 
 *
 *   width:   The width specifies the width of the effect; in the case of rounded corners this 
 *            will be the radius of the width. 
 *            Specify this value using the px suffix such as 10px, and yes it must be pixels.
 *
 * For more details see: http://methvin.com/jquery/jq-corner.html
 * For a full demo see:  http://malsup.com/jquery/corner/
 *
 *
 * @example $('.adorn').corner();
 * @desc Create round, 10px corners 
 *
 * @example $('.adorn').corner("25px");
 * @desc Create round, 25px corners 
 *
 * @example $('.adorn').corner("notch bottom");
 * @desc Create notched, 10px corners on bottom only
 *
 * @example $('.adorn').corner("tr dog 25px");
 * @desc Create dogeared, 25px corner on the top-right corner only
 *
 * @example $('.adorn').corner("round 8px").parent().css('padding', '4px').corner("round 10px");
 * @desc Create a rounded border effect by styling both the element and its parent
 * 
 * @name corner
 * @type jQuery
 * @param String options Options which control the corner style
 * @cat Plugins/Corner
 * @return jQuery
 * @author Dave Methvin (dave.methvin@gmail.com)
 * @author Mike Alsup (malsup@gmail.com)
 */
(function($) { 

$.fn.corner = function(o) {
    var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);
    function sz(el, p) { return parseInt($.css(el,p))||0; };
    function hex2(s) {
        var s = parseInt(s).toString(16);
        return ( s.length < 2 ) ? '0'+s : s;
    };
    function gpc(node) {
        for ( ; node && node.nodeName.toLowerCase() != 'html'; node = node.parentNode ) {
            var v = $.css(node,'backgroundColor');
            if ( v.indexOf('rgb') >= 0 ) { 
                if ($.browser.safari && v == 'rgba(0, 0, 0, 0)')
                    continue;
                var rgb = v.match(/\d+/g); 
                return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
            }
            if ( v && v != 'transparent' )
                return v;
        }
        return '#ffffff';
    };
    function getW(i) {
        switch(fx) {
        case 'round':  return Math.round(width*(1-Math.cos(Math.asin(i/width))));
        case 'cool':   return Math.round(width*(1+Math.cos(Math.asin(i/width))));
        case 'sharp':  return Math.round(width*(1-Math.cos(Math.acos(i/width))));
        case 'bite':   return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
        case 'slide':  return Math.round(width*(Math.atan2(i,width/i)));
        case 'jut':    return Math.round(width*(Math.atan2(width,(width-i-1))));
        case 'curl':   return Math.round(width*(Math.atan(i)));
        case 'tear':   return Math.round(width*(Math.cos(i)));
        case 'wicked': return Math.round(width*(Math.tan(i)));
        case 'long':   return Math.round(width*(Math.sqrt(i)));
        case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
        case 'dog':    return (i&1) ? (i+1) : width;
        case 'dog2':   return (i&2) ? (i+1) : width;
        case 'dog3':   return (i&3) ? (i+1) : width;
        case 'fray':   return (i%2)*width;
        case 'notch':  return width; 
        case 'bevel':  return i+1;
        }
    };
    o = (o||"").toLowerCase();
    var keep = /keep/.test(o);                       // keep borders?
    var cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]);  // corner color
    var sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]);  // strip color
    var width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10; // corner width
    var re = /round|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dog/;
    var fx = ((o.match(re)||['round'])[0]);
    var edges = { T:0, B:1 };
    var opts = {
        TL:  /top|tl/.test(o),       TR:  /top|tr/.test(o),
        BL:  /bottom|bl/.test(o),    BR:  /bottom|br/.test(o)
    };
    if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
        opts = { TL:1, TR:1, BL:1, BR:1 };
    var strip = document.createElement('div');
    strip.style.overflow = 'hidden';
    strip.style.height = '1px';
    strip.style.backgroundColor = sc || 'transparent';
    strip.style.borderStyle = 'solid';
    return this.each(function(index){
        var pad = {
            T: parseInt($.css(this,'paddingTop'))||0,     R: parseInt($.css(this,'paddingRight'))||0,
            B: parseInt($.css(this,'paddingBottom'))||0,  L: parseInt($.css(this,'paddingLeft'))||0
        };

        if ($.browser.msie) this.style.zoom = 1; // force 'hasLayout' in IE
        if (!keep) this.style.border = 'none';
        strip.style.borderColor = cc || gpc(this.parentNode);
        var cssHeight = $.curCSS(this, 'height');

        for (var j in edges) {
            var bot = edges[j];
            // only add stips if needed
            if ((bot && (opts.BL || opts.BR)) || (!bot && (opts.TL || opts.TR))) {
                strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
                var d = document.createElement('div');
                $(d).addClass('jquery-corner');
                var ds = d.style;

                bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);

                if (bot && cssHeight != 'auto') {
                    if ($.css(this,'position') == 'static')
                        this.style.position = 'relative';
                    ds.position = 'absolute';
                    ds.bottom = ds.left = ds.padding = ds.margin = '0';
                    if ($.browser.msie)
                        ds.setExpression('width', 'this.parentNode.offsetWidth');
                    else
                        ds.width = '100%';
                }
                else if (!bot && $.browser.msie) {
                    if ($.css(this,'position') == 'static')
                        this.style.position = 'relative';
                    ds.position = 'absolute';
                    ds.top = ds.left = ds.right = ds.padding = ds.margin = '0';
                    
                    // fix ie6 problem when blocked element has a border width
                    var bw = 0;
                    if (ie6 || !$.boxModel)
                        bw = sz(this,'borderLeftWidth') + sz(this,'borderRightWidth');
                    ie6 ? ds.setExpression('width', 'this.parentNode.offsetWidth - '+bw+'+ "px"') : ds.width = '100%';
                }
                else {
                    ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : 
                                        (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';                
                }

                for (var i=0; i < width; i++) {
                    var w = Math.max(0,getW(i));
                    var e = strip.cloneNode(false);
                    e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
                    bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
                }
            }
        }
    });
};

$.fn.uncorner = function(o) { return $('.jquery-corner', this).remove(); };
    
})(jQuery);


/**
 * LavaLamp - A menu plugin for jQuery with cool hover effects.
 * @requires jQuery v1.1.3.1 or above
 *
 * http://gmarwaha.com/blog/?p=7
 *
 * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 0.1.0
 */

/**
 * Creates a menu with an unordered list of menu-items. You can either use the CSS that comes with the plugin, or write your own styles 
 * to create a personalized effect
 *
 * The HTML markup used to build the menu can be as simple as...
 *
 *       <ul class="lavaLamp">
 *           <li><a href="#">Home</a></li>
 *           <li><a href="#">Plant a tree</a></li>
 *           <li><a href="#">Travel</a></li>
 *           <li><a href="#">Ride an elephant</a></li>
 *       </ul>
 *
 * Once you have included the style sheet that comes with the plugin, you will have to include 
 * a reference to jquery library, easing plugin(optional) and the LavaLamp(this) plugin.
 *
 * Use the following snippet to initialize the menu.
 *   $(function() { $(".lavaLamp").lavaLamp({ fx: "backout", speed: 700}) });
 *
 * Thats it. Now you should have a working lavalamp menu. 
 *
 * @param an options object - You can specify all the options shown below as an options object param.
 *
 * @option fx - default is "linear"
 * @example
 * $(".lavaLamp").lavaLamp({ fx: "backout" });
 * @desc Creates a menu with "backout" easing effect. You need to include the easing plugin for this to work.
 *
 * @option speed - default is 500 ms
 * @example
 * $(".lavaLamp").lavaLamp({ speed: 500 });
 * @desc Creates a menu with an animation speed of 500 ms.
 *
 * @option click - no defaults
 * @example
 * $(".lavaLamp").lavaLamp({ click: function(event, menuItem) { return false; } });
 * @desc You can supply a callback to be executed when the menu item is clicked. 
 * The event object and the menu-item that was clicked will be passed in as arguments.
 */
(function($) {
$.fn.lavaLamp = function(o) {
    o = $.extend({ fx: "linear", speed: 500, click: function(){} }, o || {});

    return this.each(function() {
        var me = $(this), noop = function(){},
            $back = $('<li class="back"><div class="left"></div></li>').appendTo(me),
            $li = $("li", this), curr = $("li.current", this)[0] || $($li[0]).addClass("current")[0];

        $li.not(".back").hover(function() {
            move(this);
        }, noop);

        $(this).hover(noop, function() {
            move(curr);
        });

        $li.click(function(e) {
            setCurr(this);
            return o.click.apply(this, [e, this]);
        });

        setCurr(curr);

        function setCurr(a){ $back.css({"left":a.offsetLeft+"px","width":a.offsetWidth+"px"});curr=a};

		function move(a){
			$back.each(
				function(){
					$(this).dequeue()
					}).animate({width:a.offsetWidth,left:a.offsetLeft}, {duration:o.speed, easing:o.fx})
				};
		});
};
})(jQuery);

/* jquery.jdMenu.js
 * used in wac for chapters and menus when sub-menus are attached
 *
 * jdMenu 1.3.beta2 (2007-03-06)
 *
 * Copyright (c) 2006,2007 Jonathan Sharp (http://jdsharp.us)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://jdsharp.us/
 *
 * Built upon jQuery 1.1.1 (http://jquery.com)
 * This also requires the jQuery dimensions plugin
*/

(function($){
	// This will store an element list of all our menu objects
	var jdMenu = [];
	
	// Public methods
	$.fn.jdMenu = function(inSettings) {
		var settings = $.extend({}, arguments.callee.defaults, inSettings);
		return this.each(function() {
			jdMenu.push(this);
			$(this).addClass('jd_menu_flag_root');
			this.$settings = $.extend({}, settings, {isVerticalMenu: $(this).is('.jd_menu_vertical')});
			addEvents(this);
		});
	};
	$.fn.jdMenuShow = function() {
		return this.each(function() {
			showMenuLI.apply(this);
		});
	};
	$.fn.jdMenuHide = function() {
		return this.each(function() {
			hideMenuUL.apply(this);
		});
	};

	// Private methods and logic
	$(window)
		// Bind a click event to hide all visible menus when the document is clicked
		.bind('click', function(){
			$(jdMenu).find('ul:visible').jdMenuHide();
		})
		// Cleanup after ourself by nulling the $settings object
		.bind('unload', function() {
			$(jdMenu).each(function() {
				this.$settings = null;
			});
		});

	// These are our default settings for this plugin
	$.fn.jdMenu.defaults = {
		activateDelay: 750,
		showDelay: 150,
		hideDelay: 550,
		onShow: null,
		onHideCheck: null,
		onHide: null,
		onAnimate: null,
		onClick: null,
		offsetX: 4,
		offsetY: 2,
		iframe: $.browser.msie
	};
	
	// Our special parentsUntil method to get all parents up to and including the matched element
	$.fn.parentsUntil = function(match) {
		var a = [];
		$(this[0]).parents().each(function() {
			a.push(this);
			return !$(this).is(match);
		});
		return this.pushStack(a, arguments);
	};

	// Returns our settings object for this menu
	function getSettings(el) {
		return $(el).parents('ul.jd_menu_flag_root')[0].$settings;
	}

	// Unbind any events and then rebind them
	function addEvents(ul) {
		removeEvents(ul);
		$('> li', ul)
			.hover(hoverOverLI, hoverOutLI)
			.bind('click', itemClick)
			.find('> a.accessible')
				.bind('click', accessibleClick);
	};
	
	// Remove all events for this menu
	function removeEvents(ul) {
		$('> li', ul)
			.unbind('mouseover').unbind('mouseout')
			.unbind('click')
			.find('> a.accessible')
				.unbind('click');
	};
	
	function hoverOverLI() {
		var cls = 'jd_menu_hover' + ($(this).parent().is('.jd_menu_flag_root') ? '_menubar' : '');
		$(this).addClass(cls).find('> a').addClass(cls);
		
		if (this.$timer) {
			clearTimeout(this.$timer);
		}

		// Do we have a sub menu?
		if ($('> ul', this).size() > 0) {
			var settings = getSettings(this);
			
			// Which delay to use, the longer activate one or the shorter show delay if a menu is already visible
			var delay = ($(this).parents('ul.jd_menu_flag_root').find('ul:visible').size() == 0) 
							? settings.activateDelay : settings.showDelay;
			var t = this;
			this.$timer = setTimeout(function() {
				showMenuLI.apply(t);
			}, delay);
		}
	};
	
	function hoverOutLI() {
		// Remove both classes so we do not have to test which one we are
		$(this)	.removeClass('jd_menu_hover').removeClass('jd_menu_hover_menubar')
			.find('> a')
				.removeClass('jd_menu_hover').removeClass('jd_menu_hover_menubar');
		
		if (this.$timer) {
			clearTimeout(this.$timer);
		}

		// TODO: Possible bug with our test for visibility in that parent menus are hidden child menus are not

		// If we have a visible menu, hide it
		if ($(this).is(':visible') && $('> ul', this).size() > 0) {
			var settings = getSettings(this);
			var ul = $('> ul', this)[0];
			this.$timer = setTimeout(function() {
				hideMenuUL.apply(ul);
			}, settings.hideDelay);
		}
	};
	
	// "this" is a reference to the LI element that contains 
	// the UL that will be shown
	function showMenuLI() {
		var ul = $('> ul', this).get(0);
		// We are already visible, just return
		if ($(ul).is(':visible')) {
			return false;
		}

		// Clear our timer if it exists
		if (this.$timer) {
			clearTimeout(this.$timer);
		}

		// Get our settings object
		var settings = getSettings(this);

		// Call our callback
		if (settings.onShow != null && settings.onShow.apply(this) == false) {
			return false;
		}

		// Add hover classes, needed for accessible functionality
		var isRoot = $(this).parent().is('.jd_menu_flag_root');
		var c = 'jd_menu_active' + (isRoot ? '_menubar' : '');
		$(this).addClass(c).find('> a').addClass(c);

		if (!isRoot) {
			// Add the active class to the parent list item which maybe our menubar
			var c = 'jd_menu_active' + ($(this).parent().parent().parent().is('.jd_menu_flag_root') ? '_menubar' : '');
			$(this).parent().parent().addClass(c).find('> a').addClass(c);
		}

		// Hide any existing menues at the same level
		$(this).parent().find('> li > ul:visible').not(ul).each(function() {
			hideMenuUL.apply(this);
		});

		addEvents(ul);

		// Our range object is used in calculating menu positions
		var Range = function(x1, x2, y1, y2) {
			this.x1	= x1;
			this.x2 = x2;
			this.y1 = y1;
			this.y2 = y2;
		}
		Range.prototype.contains = function(range) {
			return 	(this.x1 <= range.x1 && range.x2 <= this.x2) 
					&& 
					(this.y1 <= range.y1 && range.y2 <= this.y2);
		}
		Range.prototype.transform = function(x, y) {
			return new Range(this.x1 + x, this.x2 + x, this.y1 + y, this.y2 + y);
		}
		Range.prototype.nudgeX = function(range) {
			if (this.x1 < range.x1) {
				return new Range(range.x1, range.x1 + (this.x2 - this.x1), this.y1, this.y2);
			} else if (this.x2 > range.x2) {
				return new Range(range.x2 - (this.x2 - this.x1), range.x2, this.y1, this.y2);
			}
			return this;
		}
		Range.prototype.nudgeY = function(range) {
			if (this.y1 < range.y1) {
				return new Range(this.x1, this.x2, range.y1, range.y1 + (this.y2 - this.y1));
			} else if (this.y2 > range.y2) {
				return new Range(this.x1, this.x2, range.y2 - (this.y2 - this.y1), range.y2);
			}
			return this;
		}

		// window width & scroll offset
		var sx = $(window).scrollLeft()
		var sy = $(window).scrollTop();
		var ww = $(window).width();
		var wh = $(window).height();

		var viewport = new Range(	sx, sx + ww, 
									sy, sy + wh);

		// "Show" our menu so we can calculate its width, set left and top so that it does not accidentally
		// go offscreen and trigger browser scroll bars
		$(ul).css({visibility: 'hidden', left: 0, top: 0}).show();

		var menuWidth		= $(ul).outerWidth();
		var menuHeight		= $(ul).outerHeight();

		// Get the LI parent UL outerwidth in case borders are applied to it
		var tp 				= $(this).parent();
		var thisWidth		= tp.outerWidth();
		var thisBorderWidth	= parseInt(tp.css('borderLeftWidth')) + parseInt(tp.css('borderRightWidth'));
		//var thisBorderTop 	= parseInt(tp.css('borderTopWidth'));
		var thisHeight		= $(this).outerHeight();
		var thisOffset 		= $(this).offset({border: false});

		$(ul).hide().css({visibility: ''});

		// We define a list of valid positions for our menu and then test against them to find one that works best
		var position = [];
	// Bottom Horizontal
		// Menu is directly below and left edges aligned to parent item
		position[0] = new Range(thisOffset.left, thisOffset.left + menuWidth, 
								thisOffset.top + thisHeight, thisOffset.top + thisHeight + menuHeight);
		// Menu is directly below and right edges aligned to parent item
		position[1] = new Range((thisOffset.left + thisWidth) - menuWidth, thisOffset.left + thisWidth,
								position[0].y1, position[0].y2);
		// Menu is "nudged" horizontally below parent item
		position[2] = position[0].nudgeX(viewport);

	// Right vertical
		// Menu is directly right and top edge aligned to parent item
		position[3] = new Range(thisOffset.left + thisWidth - thisBorderWidth, thisOffset.left + thisWidth - thisBorderWidth + menuWidth,
								thisOffset.top, thisOffset.top + menuHeight);
		// Menu is directly right and bottom edges aligned with parent item
		position[4] = new Range(position[3].x1, position[3].x2, 
								position[0].y1 - menuHeight, position[0].y1);
		// Menu is "nudged" vertically to right of parent item
		position[5] = position[3].nudgeY(viewport);

	// Top Horizontal
		// Menu is directly top and left edges aligned to parent item
		position[6] = new Range(thisOffset.left, thisOffset.left + menuWidth, 
								thisOffset.top - menuHeight, thisOffset.top);
		// Menu is directly top and right edges aligned to parent item
		position[7] = new Range((thisOffset.left + thisWidth) - menuWidth, thisOffset.left + thisWidth,
								position[6].y1, position[6].y2);
		// Menu is "nudged" horizontally to the top of parent item
		position[8] = position[6].nudgeX(viewport);
	
	// Left vertical
		// Menu is directly left and top edges aligned to parent item
		position[9] = new Range(thisOffset.left - menuWidth, thisOffset.left, 
								position[3].y1, position[3].y2);
		// Menu is directly left and bottom edges aligned to parent item
		position[10]= new Range(position[9].x1, position[9].x2, 
								position[4].y1 + thisHeight - menuHeight, position[4].y1 + thisHeight);
		// Menu is "nudged" vertically to left of parent item
		position[11]= position[10].nudgeY(viewport);

		// This defines the order in which we test our positions
		var order = [];
		if ($(this).parent().is('.jd_menu_flag_root') && !settings.isVerticalMenu) {
			order = [0, 1, 2, 6, 7, 8, 5, 11];
		} else {
			order = [3, 4, 5, 9, 10, 11, 0, 1, 2, 6, 7, 8];
		}

		// Set our default position (first position) if no others can be found
		var pos = order[0];
		for (var i = 0, j = order.length; i < j; i++) {
			// If this position for our menu is within the viewport of the browser, use this position
			if (viewport.contains(position[order[i]])) {
				pos = order[i];
				break;
			}
		}
		var menuPosition = position[pos];

		// Find if we are absolutely positioned or have an absolutely positioned parent
		$(this).add($(this).parents()).each(function() {
			if ($(this).css('position') == 'absolute') {
				var abs = $(this).offset();
				// Transform our coordinates to be relative to the absolute parent
				menuPosition = menuPosition.transform(-abs.left, -abs.top);
				return false;
			}
		});

		switch (pos) {
			case 3:
				menuPosition.y1 += settings.offsetY;
			case 4:
				menuPosition.x1 -= settings.offsetX;
				break;
			
			case 9:
				menuPosition.y1 += settings.offsetY;
			case 10:
				menuPosition.x1 += settings.offsetX;
				break;
		}

		if (settings.iframe) {
			$(ul).bgiframe();
		}

		if (settings.onAnimate) {
			$(ul).css({left: menuPosition.x1, top: menuPosition.y1});
			// The onAnimate method is expected to "show" the element it is passed
			settings.onAnimate.apply(ul, [true]);
		} else {
			$(ul).css({left: menuPosition.x1, top: menuPosition.y1}).show();
		}

		return true;
	}

	// "this" is a reference to a UL menu to be hidden
	function hideMenuUL(recurse) {
		if (!$(this).is(':visible')) {
			return false;
		}

		var settings = getSettings(this);

		// Test if this menu should get hidden
		if (settings.onHideCheck != null && settings.onHideCheck.apply(this) == false) {
			return false;
		}
		
		// Hide all of our child menus first
		$('> li ul:visible', this).each(function() {
			hideMenuUL.apply(this, [false]);
		});

		// If we are the root, do not hide ourself
		if ($(this).is('.jd_menu_flag_root')) {
			alert('We are root');
			return false;
		}

		var elms = $('> li', this).add($(this).parent());
		elms.removeClass('jd_menu_hover').removeClass('jd_menu_hover_menubar')
			.removeClass('jd_menu_active').removeClass('jd_menu_active_menubar')
			.find('> a')
				.removeClass('jd_menu_hover').removeClass('jd_menu_hover_menubar')
				.removeClass('jd_menu_active').removeClass('jd_menu_active_menubar');

		removeEvents(this);
		$(this).each(function() {
			if (settings.onAnimate != null) {
				settings.onAnimate.apply(this, [false]);
			} else {
				$(this).hide();
			}
		}).find('> .bgiframe').remove();
		// Our callback for after our menu is hidden
		if (settings.onHide != null) {
			settings.onHide.apply(this);
		}

		// Recursively hide our parent menus
		if (recurse == true) {
			$(this).parentsUntil('ul.jd_menu_flag_root')
					.removeClass('jd_menu_hover').removeClass('jd_menu_hover_menubar')
				.not('.jd_menu_flag_root').filter('ul')
					.each(function() {
						hideMenuUL.apply(this, [false]);
					});
		}

		return true;
	}

	// Prevent the default (usually following a link)
	function accessibleClick(e) {
		if ($(this).is('.accessible')) {
			// Stop the browser from the default link action allowing the 
			// click event to propagate to propagate to our LI (itemClick function)
			e.preventDefault();
		}
	}

	// Trigger a menu click
	function itemClick(e) {
		e.stopPropagation();

		var settings = getSettings(this);
		if (settings.onClick != null && settings.onClick.apply(this) == false) {
			return false;
		}

		if ($('> ul', this).size() > 0) {
			showMenuLI.apply(this);
		} else {
			if (e.target == this) {
				var link = $('> a', e.target).not('.accessible');
				if (link.size() > 0) {
					var a = link.get(0);
					if (!a.onclick) {
						window.open(a.href, a.target || '_self');
					} else {
						$(a).click();
					}
				}
			}
			
			hideMenuUL.apply($(this).parent(), [true]);
		}
	}
})(jQuery);

/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
      
var tb_pathToImage = "/images/loadingAnimation.gif";
/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/
//on page load call tb_init
$(document).ready(function(){   
  tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
  imgLoader = new Image();// preload image
  imgLoader.src = tb_pathToImage;
});
//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
  $(domChunk).click(function(){
  var t = this.title || this.name || null;
  var a = this.href || this.alt;
  var g = this.rel || false;
  tb_show(t,a,g);
  this.blur();
  return false;
  });
}
function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
  try {
    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
      $("body","html").css({height: "100%", width: "100%"});
      $("html").css("overflow","hidden");
      if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
        $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
        $("#TB_overlay").click(tb_remove);
      }
    }else{//all others
      if(document.getElementById("TB_overlay") === null){
        $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
        $("#TB_overlay").click(tb_remove);
      }
    }
    
    if(tb_detectMacXFF()){
      $("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
    }else{
      $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
    }
    
    if(caption===null){caption="";}
    $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
    $('#TB_load').show();//show loader
    
    var baseURL;
     if(url.indexOf("?")!==-1){ //ff there is a query string involved
      baseURL = url.substr(0, url.indexOf("?"));
     }else{ 
         baseURL = url;
     }
     
     var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
     var urlType = baseURL.toLowerCase().match(urlString);
    if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
        
      TB_PrevCaption = "";
      TB_PrevURL = "";
      TB_PrevHTML = "";
      TB_NextCaption = "";
      TB_NextURL = "";
      TB_NextHTML = "";
      TB_imageCount = "";
      TB_FoundURL = false;
      if(imageGroup){
        TB_TempArray = $("a[rel="+imageGroup+"]").get();
        for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
          var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
            if (!(TB_TempArray[TB_Counter].href == url)) {            
              if (TB_FoundURL) {
                TB_NextCaption = TB_TempArray[TB_Counter].title;
                TB_NextURL = TB_TempArray[TB_Counter].href;
                TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
              } else {
                TB_PrevCaption = TB_TempArray[TB_Counter].title;
                TB_PrevURL = TB_TempArray[TB_Counter].href;
                TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
              }
            } else {
              TB_FoundURL = true;
              TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);                      
            }
        }
      }
      imgPreloader = new Image();
      imgPreloader.onload = function(){    
      imgPreloader.onload = null;
        
      // Resizing large images - orginal by Christian Montoya edited by me.
      var pagesize = tb_getPageSize();
      var x = pagesize[0] - 150;
      var y = pagesize[1] - 150;
      var imageWidth = imgPreloader.width;
      var imageHeight = imgPreloader.height;
      if (imageWidth > x) {
        imageHeight = imageHeight * (x / imageWidth); 
        imageWidth = x; 
        if (imageHeight > y) { 
          imageWidth = imageWidth * (y / imageHeight); 
          imageHeight = y; 
        }
      } else if (imageHeight > y) { 
        imageWidth = imageWidth * (y / imageHeight); 
        imageHeight = y; 
        if (imageWidth > x) { 
          imageHeight = imageHeight * (x / imageWidth); 
          imageWidth = x;
        }
      }
      // End Resizing
      
      TB_WIDTH = imageWidth + 30;
      TB_HEIGHT = imageHeight + 60;
      $("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>");     
      
      $("#TB_closeWindowButton").click(tb_remove);
      
      if (!(TB_PrevHTML === "")) {
        function goPrev(){
          if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
          $("#TB_window").remove();
          $("body").append("<div id='TB_window'></div>");
          tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
          return false;  
        }
        $("#TB_prev").click(goPrev);
      }
      
      if (!(TB_NextHTML === "")) {    
        function goNext(){
          $("#TB_window").remove();
          $("body").append("<div id='TB_window'></div>");
          tb_show(TB_NextCaption, TB_NextURL, imageGroup);        
          return false;  
        }
        $("#TB_next").click(goNext);
        
      }
      document.onkeydown = function(e){   
        if (e == null) { // ie
          keycode = event.keyCode;
        } else { // mozilla
          keycode = e.which;
        }
        if(keycode == 27){ // close
          tb_remove();
        } else if(keycode == 190){ // display previous image
          if(!(TB_NextHTML == "")){
            document.onkeydown = "";
            goNext();
          }
        } else if(keycode == 188){ // display next image
          if(!(TB_PrevHTML == "")){
            document.onkeydown = "";
            goPrev();
          }
        }  
      };
      
      tb_position();
      $("#TB_load").remove();
      $("#TB_ImageOff").click(tb_remove);
      $("#TB_window").css({display:"block"}); //for safari using css instead of show
      };
      
      imgPreloader.src = url;
    }else{//code to show html
      
      var queryString = url.replace(/^[^\?]+\??/,'');
      var params = tb_parseQuery( queryString );
      TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
      TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
      ajaxContentW = TB_WIDTH - 30;
      ajaxContentH = TB_HEIGHT - 45;
      
      if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window    
          urlNoQuery = url.split('TB_');
          $("#TB_iframeContent").remove();
          if(params['modal'] != "true"){//iframe no modal
            $("#TB_window").append("<div id='TB_title' class='WAC_wTitle'><div id='TB_ajaxWindowTitle' class='WAC_Title'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' class='WAC_wClose'>X</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
          }else{//iframe modal
          $("#TB_overlay").unbind();
            $("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
          }
      }else{// not an iframe, ajax
          if($("#TB_window").css("display") != "block"){
            if(params['modal'] != "true"){//ajax no modal
            $("#TB_window").append("<div id='TB_title' class='WAC_wTitle'><div id='TB_ajaxWindowTitle' class='WAC_Title'>"+caption+"</div><div id='TB_closeAjaxWindow' ><a href='#' id='TB_closeWindowButton' class='WAC_wClose'>X</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
            }else{//ajax modal
            $("#TB_overlay").unbind();
            $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");  
            }
          }else{//this means the window is already up, we are just loading new content via ajax
            $("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
            $("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
            $("#TB_ajaxContent")[0].scrollTop = 0;
            $("#TB_ajaxWindowTitle").html(caption);
          }
      }
          
      $("#TB_closeWindowButton").click(tb_remove);
      
        if(url.indexOf('TB_inline') != -1){  
          $("#TB_ajaxContent").append($('#' + params['inlineId']).children());
          $("#TB_window").unload(function () {
            $('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
          });
          tb_position();
          $("#TB_load").remove();
          $("#TB_window").css({display:"block"}); 
        }else if(url.indexOf('TB_iframe') != -1){
          tb_position();
          if($.browser.safari){//safari needs help because it will not fire iframe onload
            $("#TB_load").remove();
            $("#TB_window").css({display:"block"});
          }
        }else{
          $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
            tb_position();
            $("#TB_load").remove();
            tb_init("#TB_ajaxContent a.thickbox");
            $("#TB_window").css({display:"block"});
          });
        }
      
    }
    if(!params['modal']){
      document.onkeyup = function(e){   
        if (e == null) { // ie
          keycode = event.keyCode;
        } else { // mozilla
          keycode = e.which;
        }
        if(keycode == 27){ // close
          tb_remove();
        }  
      };
    }
    
  } catch(e) {
    //nothing here
  }
}
//helper functions below
function tb_showIframe(){
  $("#TB_load").remove();
  $("#TB_window").css({display:"block"});
}
function tb_remove() {
   $("#TB_imageOff").unbind("click");
  $("#TB_closeWindowButton").unbind("click");
  $("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
  $("#TB_load").remove();
  if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
    $("body","html").css({height: "auto", width: "auto"});
    $("html").css("overflow","");
  }
  document.onkeydown = "";
  document.onkeyup = "";
  return false;
}
function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
  if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
    $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
  }
}
function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}
function tb_getPageSize(){
  var de = document.documentElement;
  var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
  var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
  arrayPageSize = [w,h];
  return arrayPageSize;
}
function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}

/*------------------------------------------------------------------------------------------------------------------
 *
 * other Widgets
 *
 *------------------------------------------------------------------------------------------------------------------*/ 
//----------------------------------------------------------------------------------------------------
// Flash Player Version Detection
//----------------------------------------------------------------------------------------------------
// v1.6    Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
// v1.6.1: Copyright 2008 Webunity, All rights reserved.
//         - Refactored the AC_Generateobj function to utilise the new AC_Generate function which is used by jQuery.uploader
//----------------------------------------------------------------------------------------------------

// Detect Client Browser type
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;


function AC_Generate(objAttrs, params, embedAttrs) {
    var str = '';

    if (isIE && isWin && !isOpera) {
  		str += '<object ';
  		for (var i in objAttrs)
  			str += i + '="' + objAttrs[i] + '" ';
  		str += '>';

  		for (var i in params)
  			str += '<param name="' + i + '" value="' + params[i] + '" />';

  		str += '</object>';
    } else {
  		str += '<embed ';

  		for (var i in embedAttrs)
  			str += i + '="' + embedAttrs[i] + '" ';

  		str += '> </embed>';
    }

    return str;
}

function AC_AddExtension(src, ext) {
	if (src.indexOf(ext) != -1)
		return src;
	return (src.indexOf('?') != -1) ? src.replace(/\?/, ext+'?') : src + ext;
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
	var ret = new Object();
	ret.embedAttrs = new Object();
	ret.params = new Object();
	ret.objAttrs = new Object();
	for (var i=0; i < args.length; i=i+2) {
		var currArg = args[i].toLowerCase();
		switch (currArg) {
			case "classid":
				break;
			case "pluginspage":
				ret.embedAttrs[args[i]] = args[i+1];
				break;
			case "src":
			case "movie":
				args[i+1] = AC_AddExtension(args[i+1], ext);
				ret.embedAttrs["src"] = args[i+1];
				ret.params[srcParamName] = args[i+1];
				break;
			case "onafterupdate":
			case "onbeforeupdate":
			case "onblur":
			case "oncellchange":
			case "onclick":
			case "ondblClick":
			case "ondrag":
			case "ondragend":
			case "ondragenter":
			case "ondragleave":
			case "ondragover":
			case "ondrop":
			case "onfinish":
			case "onfocus":
			case "onhelp":
			case "onmousedown":
			case "onmouseup":
			case "onmouseover":
			case "onmousemove":
			case "onmouseout":
			case "onkeypress":
			case "onkeydown":
			case "onkeyup":
			case "onload":
			case "onlosecapture":
			case "onpropertychange":
			case "onreadystatechange":
			case "onrowsdelete":
			case "onrowenter":
			case "onrowexit":
			case "onrowsinserted":
			case "onstart":
			case "onscroll":
			case "onbeforeeditfocus":
			case "onactivate":
			case "onbeforedeactivate":
			case "ondeactivate":
			case "type":
			case "codebase":
				ret.objAttrs[args[i]] = args[i+1];
				break;
			case "id":
			case "width":
			case "height":
			case "align":
			case "vspace":
			case "hspace":
			case "class":
			case "title":
			case "accesskey":
			case "name":
			case "tabindex":
				ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
				break;
			default:
				ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
		}
	}
	ret.objAttrs["classid"] = classid;

	if (mimeType)
		ret.embedAttrs["type"] = mimeType;

	return ret;
}

function AC_FL_GetContent(){
	var ret = AC_GetArgs(arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash");
	return AC_Generate(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_FL_RunContent(){
	document.write(AC_FL_GetContent(arguments));
}

function AC_SW_GetContent(){
	var ret = AC_GetArgs(arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000", null);
	return AC_Generate(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
	document.write(AC_SW_GetContent(arguments));
}


/*------------------------------------------------------------------------------------------------------------------
 *
 * browser related plugins
 *
 *------------------------------------------------------------------------------------------------------------------*/

/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-02-18 22:09:54 -0600 (Sun, 18 Feb 2007) $
 * $Rev: 1379 $
 */

/**
 * The bgiframe is chainable and applies the iframe hack to get 
 * around zIndex issues in IE6. It will only apply itself in IE 
 * and adds a class to the iframe called 'bgiframe'.
 * 
 * It does take borders into consideration but all values
 * need to be in pixels and the element needs to have
 * position relative or absolute.
 *
 * NOTICE: This plugin uses CSS expersions in order to work
 * with an element's borders, height and with and can result in poor 
 * performance when used on an element that changes properties 
 * like size and position a lot. Two of these expressions can be
 * removed if border doesn't matter and performance does.
 * See lines 39 and 40 below and set top: 0 and left: 0
 * instead of their current values.
 *
 * @example $('div').bgiframe();
 * @before <div><p>Paragraph</p></div>
 * @result <div><iframe class="bgiframe".../><p>Paragraph</p></div>
 *
 * @name bgiframe
 * @type jQuery
 * @cat Plugins/bgiframe
 * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 */
jQuery.fn.bgIframe = jQuery.fn.bgiframe = function() {
	// This is only for IE6
	if ( !(jQuery.browser.msie && typeof XMLHttpRequest == 'function') ) return this;
	var html = '<iframe class="bgiframe" src="javascript:false;document.write(\'\');" tabindex="-1" '
	 					+'style="display:block; position:absolute; '
						+'top: expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)  || 0) * -1) + \'px\'); '
						+'left:expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth) || 0) * -1) + \'px\'); ' 
						+'z-index:-1; filter:Alpha(Opacity=\'0\'); '
						+'width:expression(this.parentNode.offsetWidth + \'px\'); '
						+'height:expression(this.parentNode.offsetHeight + \'px\')"/>';
	return this.each(function() {
		if ( !jQuery('iframe.bgiframe', this)[0] )
			this.insertBefore( document.createElement(html), this.firstChild );
	});
};

 
/*------------------------------------------------------------------------------------------------------------------
 *
 * specific HCTBA extensions to be revisited
 *
 *------------------------------------------------------------------------------------------------------------------*/

/* jquery.calendar.js
 *
 * Plugin for jQuery 1.1.2+ to build Calendars from JSON data
 * @author Robert ERNENS
 *
 */

jQuery.fn.extend ({
	calendar: function(o){
		return this.each(function(){
			new jQuery.calendar(this, o);
		});   
	}
});

jQuery.extend ({

	calendar: function(e, o){ 

 		var priv = {

			o: {
				data: {dates: []},
				url: "/pages/calendar-data.a4d",
				key: "",
				ID: 0,
				roomKey: 0,
				prefix: "",
				dateRef: new Date(),
				visibleCal: 1,
				shownCal: 1,  
				dayRef: 1,
				monthRef: 1, 
				calendarClass: "WAC-Calendar ",
				previousClass: "WAC-Calendar-Previous ",
				nextClass: "WAC-Calendar-Next ",
				titleClass: "WAC-Calendar-Title ",
				labelClass: "WAC-Calendar-Label ",
				weekLabelClass: "WAC-Calendar-Week-Label ",
				weekClass: "WAC-Calendar-Week ",
				weekDayClass: "WAC-Calendar-WeekDay ",
				weekDayLabelClass: "WAC-Calendar-WeekDay-Label ",
				weekEndClass: "WAC-Calendar-WeekEnd ", 
				weekEndLabelClass: "WAC-Calendar-WeekEnd-Label ",
				inactiveClass: "WAC-Calendar-Inactive ",
				pastDayClass: "WAC-Calendar-PastDay ",
				todayClass: "WAC-Calendar-Today ",
				anchorClass: "WAC-Calendar-Anchor", 
				weekShort: 'S',
				months : ['Janvier', 'F&eacute;vrier', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Ao&ucirc;t', 'Septembre', 'Octobre', 'Novembre', 'D&eacute;cembre'],
				daysLong : ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'], 
				daysShort : ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
				days: [0,31,28,31,30,31,30,31,31,30,31,30]

			}, 

			init: function(e,o) {
				if (o) jQuery.extend(priv.o, o);
				result = jQuery.getJSON( priv.o.url , { 'key': priv.o.key , 'ID': priv.o.ID, 'roomKey': priv.o.roomKey, 'monthRef': priv.o.monthRef } , function(json) {priv.build(e, json)});
			},

			build: function(e, json ) { 
				var prevNav = jQuery("<div></div>").attr( "class", priv.o.previousClass ).append("<a href='#' >&nbsp;</a>") ;
				var nextNav = jQuery("<div></div>").attr( "class", priv.o.nextClass ).append("<a href='#' >&nbsp;</a>") ;
				var navDiv =  jQuery("<div></div>").css("width","100%").append(prevNav).append(nextNav);
				jQuery(e).append(navDiv) ; 

				priv.o.data  = json   

				var todayDate = new Date();
	            if (priv.o.dateRef <= todayDate) {
					priv.o.dateRef = todayDate ;
				}
				if( priv.o.monthRef == 1 ) {
					jQuery("." + priv.o.previousClass).css( "visibility" , "hidden") ;
				} else {
					jQuery("." + priv.o.previousClass).find("a").bind("click", function() { priv.prevMonth();} ) ;
				}
				if ((priv.o.monthRef + priv.o.shownCal) > priv.o.visibleCal) {
					jQuery("." + priv.o.nextClass).css( "visibility" , "hidden") ;
				} else {
					jQuery("." + priv.o.nextClass).find("a").bind("click", function() { priv.nextMonth();} ) ;
				}
				currentMonth = priv.o.dateRef.getMonth() ;
				currentYear = priv.o.dateRef.getFullYear() ;
				currentMonthlastDay = priv.o.dateRef 
				var cal = priv.o.monthRef + priv.o.shownCal 
				for (k=priv.o.monthRef; (k < cal) && (k <= priv.o.visibleCal); k++) { 
				   	calendarMonth = currentMonth - 1 + k; 
				   	calendarYear = currentYear;
				   	while ( calendarMonth > 11) {
					   	calendarMonth -= 12 ;
						calendarYear +=1 ;
					}
				   	var calendarDiv = jQuery("<div></div>").attr( "class", priv.o.calendarClass );
				   	var titleDiv = jQuery("<div></div>").attr( "class", priv.o.titleClass ).append( priv.o.months[calendarMonth] + "&nbsp;" + calendarYear) ;
					var headRow = jQuery("<tr></tr>").attr( "class", priv.o.labelClass ) ;
					headRow.append(
						jQuery("<th></th>")
							.attr({'scope':'col', 'class': priv.o.weekLabelClass})
							.html(priv.o.weekShort)
						) ;
					for (var j=priv.o.dayRef-1; j<priv.o.dayRef+6; j++) {
						var weekday = j%7;
						var dayShort = priv.o.daysShort[weekday] ;
						var dayLong = priv.o.daysLong[weekday] ;
						var weekDayLabelClass = priv.o.weekDayClass + priv.o.weekDayLabelClass ;
						var weekEndLabelClass = priv.o.weekEndClass + priv.o.weekEndLabelClass ;
						var headClass = weekday==0 || weekday==6 ? weekEndLabelClass : weekDayLabelClass ;
						headRow.append(
							jQuery("<th></th>")
								.attr({'scope':'col', 'abbr': priv.o.dayLong, 'title': dayLong, 'class': headClass })
								.html(dayShort)
							) ;
					} 
					var tBody = jQuery("<tbody></tbody>") ;   

					var d =  new Date(calendarYear, calendarMonth , 1)  ;
					var curDay = priv.o.dayRef - 1 - d.getDay() ;
					if (curDay>0) curDay -= 7 ;
					var lastDay = new Date(calendarYear, calendarMonth + 1 , 0).getDate() ; 	
					var thisMonth = calendarMonth == todayDate.getMonth() && calendarYear == todayDate.getFullYear();

					var w = 0; 
					if( d.getDay() > 0 ) {
						var sundayDate = new Date( d.getFullYear(), d.getMonth(), d.getDate()+7-d.getDay()) ; 
					} else {
						var sundayDate = d ;
					}
					while (w++<6) { 
						var thisRow = jQuery("<tr></tr>"); 
						if ( curDay >= lastDay ) {  
							thisRow.append(jQuery("<td></td>").attr({'class': priv.o.weekClass } ).html('&nbsp;'));
						} else {
							thisRow.append(jQuery("<td></td>").attr({'class': priv.o.weekClass } ).html(priv.getWeekNr(sundayDate)-1));
							var sundayDate = new Date( sundayDate.getFullYear(), sundayDate.getMonth(), sundayDate.getDate()+7) ;
						}
						for (var i=0; i<7; i++) {  

							var weekday = (priv.o.dayRef + i - 1) % 7;
							var atts = {'class': (weekday == 0 || weekday == 6 ? priv.o.weekEndClass : priv.o.weekDayClass )};

							if (curDay < 0 || curDay >= lastDay) {
								dayStr = ' '; 
								atts['class'] += priv.o.inactiveClass ;
							} else if ( thisMonth &&  d.getDate() < todayDate.getDate() - 1) { 
								d.setDate(curDay + 1 );
								dayStr = curDay + 1 ;
								atts['class'] += priv.o.pastDayClass ; 
							} else {
								d.setDate(curDay + 1 );
								dayStr = curDay + 1 ;
							}

							if (thisMonth && curDay+1 == todayDate.getDate()) {
								atts['class'] += priv.o.todayClass ;
							}

							currentDateDay = (100 + d.getDate())+"" ;
							currentDateDay = currentDateDay.substr(1,2) ;
							currentDateMonth = (100 + d.getMonth() + 1)+"" ;
							currentDateMonth = currentDateMonth.substr(1,2) ;
							currentDate = "D"+currentDateDay + currentDateMonth + d.getFullYear() ;

							dateParms = eval('priv.o.data.' + currentDate ) ; 
							var x = 0  ;
							if( dateParms != undefined && curDay >= 0 && curDay < lastDay) {
								while( x < dateParms.length ) { 
									atts['class'] += priv.o.prefix + dateParms[x] + " " ;
									x++;
								}
							}
							var title = "";
							if ( dateParms != undefined) {
								 title = priv.o.prefix + dateParms[0];
							}
							var atta = {'href': "#", 'title': title, 'class': priv.o.anchorClass };
							var thisAnchor = jQuery("<a></a>").attr(atta).html(dayStr);
							var thisCell = jQuery("<td></td>").append(thisAnchor).attr(atts);
							thisRow.append(thisCell);
							curDay++;
						}
						tBody.append(thisRow);
					}

					calendarDiv.append(titleDiv)
						.append(jQuery("<table></table>").attr({cellspacing: "0", cellpadding: "0" }))
						.find("table")
						.append("<thead></thead>")
						.find("thead")
						.append(headRow)
						.parent()
						.append(tBody.children()); 

					jQuery(e).append(calendarDiv);
				} 

			},

			nextMonth: function() {
				jQuery("div.WAC-Calendars").fadeOut("slow",function(){
					jQuery(this).empty();
					priv.o.monthRef += 1;
					priv.init( jQuery(this), priv.o) ;
					jQuery(this).fadeIn("slow") ; 
				}); 
			},

			prevMonth: function() {  
				jQuery("div.WAC-Calendars").fadeOut("slow",function(){
					jQuery(this).empty();
					priv.o.monthRef -= 1;
					priv.init( jQuery(this), priv.o) ;
					jQuery(this).fadeIn("slow") ; 
				});
			},

			getWeekNr: function(theDate) { 
				Year = priv.takeYear(theDate);
				Month = theDate.getMonth();
				Day = theDate.getDate();
				now = Date.UTC(Year,Month,Day+1,0,0,0);
				var Firstday = new Date();
				Firstday.setYear(Year);
				Firstday.setMonth(0);
				Firstday.setDate(1);
				then = Date.UTC(Year,0,1,0,0,0);
				var Compensation = Firstday.getDay();
				if (Compensation > 3) Compensation -= 4;
				else Compensation += 3;
				NumberOfWeek =  Math.round((((now-then)/86400000)+Compensation)/7);
				return NumberOfWeek;
			},

			takeYear: function (theDate) {
				x = theDate.getYear();
				var y = x % 100;
				y += (y < 38) ? 2000 : 1900;
				return y;
			}

		};

		priv.init(e,o); 

	}   

} )

/* jquery.scrollers.js
 * used to address wac scroller resizing when window size changes
 * this is really only needed for IE 6 that does not support sizing of div based on top and bottom css parms
 * 2006-07-01 version 1.1
 * Scroller resize script
 * jquery-scrollers.js
*/

// Scroller resize init : add resize event to window and default CSS property to scroller div(s)

function SCR_init(){       
	var SCR_count = $("div.WAC-scrollers").size() ;
	if( SCR_count != 0) {
		$("div.WAC-scrollers").css({ position: "absolute", overflow: "auto"});
		$(window).resize(SCR_resize);
		var SCR_e0 = $("#Container").get(0).clientHeight;
		var SCR_e1 = $("#Main").get(0).offsetTop;
		$("div.WAC-scrollers").each(function(){
			var SCR_top = this.offsetTop;
			var SCR_height = this.clientHeight;
			var SCR_newHeight = SCR_height - (SCR_e1 + SCR_top);
			var SCR_offset = SCR_e0 - (SCR_e1 + SCR_top + SCR_newHeight);
			this.setAttribute("rel",SCR_offset);
			this.style.height = SCR_newHeight + "px"; 
		});
		$("#Container").css("height","100%"); 
		SCR_resize(); 
	} else {      
		if ($.browser.msie) { 
			Main_Height = $("#Main").css("height") ;
			if ( Main_Height == "auto" )  { 
					Main_Height = $(document.body).height() - $("#Main").offset({ border: true }).top - 2 - Number($("#Main").css("bottom").replace( "px", "") ) ; 
					if ( isNaN(Main_Height) == false ) { $("#Main").css("height", Main_Height ) ;};
			} ; 
		} else {
			$(document.body).css("overflow", "hidden") ;     
		}   
		$("#Container").css("height","100%") ;
		SCR_iframe();
	}  
}

function SCR_resize(){
	var SCR_e0 = $("#Container").get(0).clientHeight;
	var SCR_e1 = $("#Main").get(0).offsetTop;
	if ($.browser.msie) { 
		Main_bottom = isNaN(Number($("#Main").css("bottom").replace( "px", ""))) ;
		if ( Main_bottom == false )  { 
				Main_Height = $(document.body).height() - $("#Main").offset({ border: true }).top - 2 - Number($("#Main").css("bottom").replace( "px", "") ) ;
				$("#Main").css("height", Main_Height ) ; 
		} ; 
		if ($.browser.version == "6.0") {
			CI_bottom = Number($("#Container-Inner").css("bottom").replace( "px", "") ) ;
			if( isNaN(CI_bottom) == false ) {
				CI_base = $("#Container").height() - $("#Container-Inner").offset({ border: true , relativeTo: "#Container" }).top - CI_bottom ;
				$("#Container-Inner").css("height", CI_base ) ; 
			} 
			CI_base = $("#Container-Inner").height() ; 
		} ; 
	}
	$("div.WAC-scrollers").each(function(){
		var SCR_top = this.offsetTop;
		var SCR_height = this.clientHeight;
		var SCR_offset = parseInt(this.getAttribute("rel"));
		var SCR_newOffset = SCR_e0 - (SCR_e1 + SCR_top + SCR_height);
		var SCR_newHeight = SCR_height + (SCR_newOffset - SCR_offset);
		this.style.height = SCR_newHeight + "px"; 
		$(".WAC-scrollers-Inner", this).css("height", SCR_newHeight + "px");
		if (this.offsetHeight < this.scrollHeight) {
			var SCR_width = this.clientWidth;
			var SCR_offsetWidth = this.offsetWidth;
	   		$(this).find("div").each(function(){
				if(this.parentNode.className == "WAC-scrollers-Inner"){
					if(this.offsetWidth >SCR_width) {
						var SCR_newWidth = SCR_width - 10;
						this.style.width = SCR_newWidth + "px";
					};
				};
			});
		};
//		this.style.overflowX ="hidden";   
		$(this).css("overflowX", "hidden") ; 
		SCR_iframe("resize");
	});
}

function SCR_iframe(){ 
	$("iframe").each( function(mode){ 
		var SCR_parentFloat = $(this).parent().css("float");
		if ((SCR_parentFloat == "left" || SCR_parentFloat == "right") && ( mode != "resize") ){
		} else {
			var SCR_iframeHeight = $(this).height() ;  
			if ( SCR_iframeHeight == null || SCR_iframeHeight == 0 ) {
				var SCR_iframeOffset =  $(this).offset().top - $(this).parent().offset().top  ;
				var SCR_iframeHeight = $(this).parent().height() - 2 - SCR_iframeOffset ;
			}
			this.style.height = SCR_iframeHeight + "px" ;
		}
	});
}

function SCR_iframeLoad (o) { 
	 var iframeParentFloat = $(o).parent().css("float");
	 if( iframeParentFloat == "left" || iframeParentFloat == "right") { 
	 	var SCR_iframeContent = $(o).contents().find("body");
	 	var SCR_iframeHeight = SCR_iframeContent.outerHeight();
	 	$(o).height(SCR_iframeHeight).attr("scrolling","no").css("overflow","hidden") ;
		
	}
}


$(document).ready(SCR_init); 

/* jquery.postForm.js - 
 * jQuery function to extend  wac form submit
 * v 1.0
 * author Robert Ernens
*/

jQuery.fn.formPost = function () {
	return this.each(function() { 
		var formName = $(this).parents("form").attr("name");
		var isAnchorTag = $(this).is("a") ;
		$("input:hidden[name=B_Submit]","form[name=" + formName + "]" ).remove() ;
		$("input:hidden[name=B_Cancel]","form[name=" + formName + "]" ).remove() ;
		var mode = "" ;
		if ( isAnchorTag ) {
		    mode = $(this).attr("id").toUpperCase() ;
		} else {
			mode = $(this).attr("name").toUpperCase();
		}
		var i = mode.lastIndexOf("_")+1 ;
		mode = mode.slice(i) ;
		if ( mode == "PRINT") {
			window.print();
			mode = "SUBMIT" ;
		}
		if ( mode == "CANCEL" ) {
			$("form[name=" + formName + "]" ).append("<input type='hidden' name='B_Cancel'  value='Cancel'  />") ;
		}
		if ( mode == "SUBMIT" ) {
			var formChecks = $("input[name=WACformChecks]", "form[name=" + formName + "]" ).val();
			var isValidated = (formChecks.match("0") == null) 
			if ( isValidated ) {
				$("form[name=" + formName + "]" ).append("<input type='hidden' name='B_Submit'  value='Submit'  />") ;
			} else {
			    return false;
			}
		} 
		
		// replace CRLF in text area with <br /> 
		re = /[\n\r]/g ;
		$("textarea","form[name=" + formName + "]" ).each(function(){
			$(this).val($(this).val().replace( re, "<br />" ));
		});
		var block = $("input[name=WACform" + mode + "Target ]", "form[name=" + formName + "]" ).val() ;
		var ajaxTarget = $("input[name=_ajaxTarget ]", "form[name=" + formName + "]" ).val() ; 
		if ( block != "" && ajaxTarget != "no" ) {
			if ($("input[name=_]","form[name=" + formName + "]" ).length=0) {
				$("form[name=" + formName + "]" ).append("<input type='hidden' name='_'  value='x'  />") ;
			}
			var options  = { target: block, success: function(){$(block).activateJFrame();} };
			$("form[name=" + formName + "]" ).ajaxSubmit(options);
			$(block).html("<span><img src='/images/ajax-loader.gif' border='0' class='WAC-ajaxLoader' /></span>"); 
			activateTabs( block );
			return false;
		} else {
			eval("document." + formName +".submit()") ;
			return false;
		}
	})
}

/* jquery.formValidator.js : 
 * Ajax form validation jQuery function used to validate wac forms field by field
 * Author : Robert Ernens 
 * version : 1.1
*/

var formValidator = {
	ajaxCheck : function (n, o, i, a ) {
		if ( a == undefined) {
			var a = null;
		}
		if (o.type == "checkbox") {
			if(o.checked == true) { o.value = "true"} else { o.value = "false" }
		}
		var FV_formKey = $("input[name=WACformKey]", "form[name=" + n + "]" ).get(0) ;
		var FV_formName = $("input[name=WACformName]", "form[name=" + n + "]" ).get(0) ;
		var FV_formSID = $("input[name=WACformSID]", "form[name=" + n + "]" ).get(0) || "" ;
		var FV_formTable = $("input[name=_Table]", "form[name=" + n + "]" ).get(0) || "" ;
		if (FV_formTable != ""){
			FV_formTable = $("input[name=_"+FV_formTable.value+"]", "form[name=" + n + "]" ).get(0) || "" ;
			if (FV_formTable != ""){
			   FV_formTable = FV_formTable.value;
			}
		}
		var FV_url = "/4DCGI/actions/chk_field.a4d"
		var FV_query= "F_formName="+FV_formName.value +"&F_formKey=" + FV_formKey.value + "&F_fieldIndex=" + i + "&F_fieldValue=" + o.value + "&SID=" + FV_formSID.value + "&F_tableKey=" + FV_formTable;
		$("#" + o.name + "_img", "form[name=" + n + "]" ).attr('src', '/images/ajax-loader.gif') ;
		$("#" + o.name + "_msg", "form[name=" + n + "]" ).hide().html("&nbsp;") ;
		a = formValidator.ajaxQueue( a );
		a.add( { 	type: "POST" ,
//		$.ajax( { 	type: "POST" ,
					cache: false, 
					url: FV_url , 
					data: FV_query ,    
					success: formValidator.ajaxSuccess
			   }) ;
		return (a);
	},
	ajaxQueue : function( a ) {
		if( a == null ) {
			var a = $.manageAjax({manageType: 'queue', maxReq: 1 });
		}
		return (a);
	},
	ajaxSuccess : function ( o , t) {
		re = /[\n\r]/ ;
		eval( "var json = " + o.replace(re,"") );
		var inputType =$("input[name=" + json.id + "]", "form[name=" + json.form  + "]" ).attr( "type" ) ;
		if (json.success == 1 ) {
			$("#" + json.id + "_img", "form[name=" + json.form + "]" ).attr('src','/images/ajax-valid.gif');
			if ( inputType == "file") {
				var FV_fileUpload = $("input[name=" + json.id +"]", "form[name=" + json.form  + "]" ).val();
				var delimiterIndex = FV_fileUpload.indexOf(":", 0) ;
				var delimiter =  delimiterIndex != -1  ? "\\" : "/" ;
				var delimiterPos = FV_fileUpload.lastIndexOf( delimiter , FV_fileUpload.length) + 1 ;
				FV_fileUpload = FV_fileUpload.substr( delimiterPos , FV_fileUpload.length - delimiterPos ) ;
				$("input[name=F_" + json.id + "_name]", "form[name=" + json.form  + "]" ).val( FV_fileUpload );
			}
		} else {
			$("#" + json.id + "_img", "form[name=" + json.form + "]" ).attr('src','/images/ajax-invalid.gif');
			if ( inputType == "file" ) {
				$("input[name=" + json.id + "_name]", "form[name=" + json.form  + "]" ).val("");
			}
		};
		if (json.msg != "" ) {
			$("#" + json.id + "_msg", "form[name=" + json.form + "]" ).html(json.msg);
			$("#" + json.id + "_msg", "form[name=" + json.form + "]" ).slideDown("normal");
		} else {
			$("#" + json.id + "_msg", "form[name=" + json.form + "]" ).hide();
		}
		var FV_formChecks = $("input[name=WACformChecks]", "form[name=" + json.form + "]" ).val();
		FV_formChecks = formValidator.formChecks(json.seq, json.success, FV_formChecks ) ;
		$("input[name=WACformChecks]", "form[name=" + json.form + "]" ).val(FV_formChecks);
		var FV_status = (FV_formChecks.match("0") != null );
		$("input[type=submit]", "form[name=" + json.form + "]" ).filter("input[name=B_Submit]").each(function () { this.disabled = FV_status });
		$("#" + json.id + "_msg", "form[name=" + json.form + "]" ).unbind();
		$("#" + json.id + "_img", "form[name=" + json.form + "]" ).unbind();
	},
	formChecks : function ( index, success, value) {
		var start = value.substring( 0, index-1) ;
		var end = value.substring(index, value.length) ;
		var value = start + success + end ;
		return (value)
	},
	formVerify : function ( n ) {
		var FV_formChecks = $("input[name=WACformReset]", "form[name=" + n + "]" ).val();
		if ( FV_formChecks.match("0") != null ) {
			var index = 1;
			var a = null;
			while ( index <= FV_formChecks.length ) {
				if (FV_formChecks.charAt(index-1) == "0") {
					var FV_formField = $("#" + n + "_" + index )
//					if ($(FV_formField).val() != "") { 
					if (FV_formField.length >0) {
						a = formValidator.ajaxCheck( n , FV_formField.get(0) , index, a ) ;
					}
				}
				index += 1 ;
			}
			var FV_status = (FV_formChecks.match("0") == null );
			$(":submit", "form[name=" + n + "]" ).filter("input[name=B_Submit]").each(function () { this.disabled = FV_status });
		}
	}
};

/* function to handle WAC tabs activation */

var handleTabs = function (i,s,h) {
    $(i).addClass( $(i).attr("rev") ); 
    var j = $("a[target=" + $(h).attr("id") + "]").get(0) ;
    $(j).removeClass( $(j).attr("rev") );
    activateTabs(s);
    return true;
};

/* function to force activation of a tab embedded in accordions */

var activateTabs = function (d) { 
	if (d) {
		$(d)
			.parents(".ui-tabs-hide")
			.slice(0,1)
			.add( d + ".ui-tabs-hide")
			.each( function(){
				activateTab(this);
			});
	}
};

/* function to activate a tab based on its div id */

var activateTab = function (d) {
	var target = $(d).attr("id");
	var ul = $("a[target=" + target + "]").parent().parent() ;
	var i = $(">li", ul) ;
	var j = $(">a[target=" + target + "]", i).parent().get(0) ;
	var k = $(i).index(j) + 1 ;
	$(ul).tabsClick(k) ;
};

/* function to redirect a page normally loaded through ajax */

var redirectWAC = function () {
	if ( $("#Container-Inner").length == 0 ) {
		$(document).load("index.a4d");
	}
};

/* function to load content with ajax after full page loading */

var ajaxLoad = function (o) {
	$target = $(o.target) ;
	if (typeof o.preamble == 'function') {
		o.preamble();
	}
	// add loader if required
	if(o.loaderType == 'img'){
		o.loadingMsg = '<img class=\"WAC-ajaxLoader\" src=\"' + o.loadingImg + '\"/>';
		}
	$target.html(o.loadingMsg);  
	// make the call
	$.ajax({ 
		type: o.type, 
		url: o.url,
		success: function(msg){ 
			$target.html(msg);
			//if a callback exist pass arguments ( object,target and receive message)
			if(typeof o.success == 'function'){
				o.success($obj,$target,msg);
				}  						
			},
		error: function(){
			$target.html("<p>" + o.errorMsg + "</p>");
			if(typeof o.error == 'function'){
				o.error($target);
				}  						
		 
		}
	});
};

var handleCheckbox = function( o, f ) {
	if (o.checked) {
		$("input[name=" + o.name + "][type=hidden]","form[name=" + f.name + "]").remove();
	} else {
		$("form[name=" + f.name + "]").prepend("<input type='hidden' name='"+o.name+"' value='off' />")
	}
};

(function($) {

	$.widget("ui.uploader", {
		init: function() {
			var self = this, o = this.options;
			var rand = Math.floor(Math.random() * 10000);
			var swfVars = {};
			swfVars['eventHandler'] = 'jQuery.ui.uploader.eventHandler';
			swfVars['elementID'] = o.movieID;
			if (o.buttonSkin) {
				swfVars['buttonSkin'] = o.buttonSkin;
			}
			swfVars['logging'] = o.logging;
			swfVars['allowedDomain'] = o.allowedDomain;
			swfVars['enabled'] = o.enabled;
			swfVars['multiple'] = o.multiple;
			swfVars['maxFileSize'] = o.maxFileSize;
			swfVars['maxQueueSize'] = o.maxQueueSize;
			swfVars['maxQueueCount'] = o.maxQueueCount;
			swfVars['maxThreads'] = o.maxThreads;
			swfVars['autoAdvanceOnCancel'] = o.autoAdvanceOnCancel;
			swfVars['autoAdvanceOnError'] = o.autoAdvanceOnError;
			fVars = '';
			for (var idx in swfVars) {
				if (fVars != '') 
					fVars += '&';
				fVars+= idx + '=' + swfVars[idx];
			}
			self._eventsQueue = [];
			self._cache = [];
			self._swf = null ;  
			swfHTML = AC_FL_GetContent(
								'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0',
								'width', '100%',
								'height', '100%',
								'menu', 'false',
								'src', o.swfURL + "?" + rand,
								'quality', 'high',
								'bgcolor', o.backgroundColor,
								'id', o.movieID,
								'name', o.movieID + 'Name',
								'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
								'movie', o.swfURL + "?" + rand,
								'flashvars', fVars,
								'wmode', o.wmode
							);
			var overlay = $(self.element)[0] ;
			overlay.innerHTML = swfHTML ;
			$("#" + o.movieID).attr("title","Charger un fichier");
			self._swf = $("#" + o.movieID)[0];
		},
		_queueEvent: function(params) {
				if (typeof this.options.events[params.type] === "function") {
					var flashObject = arguments;
					this._eventsQueue.push(function () {
						this.options.events[params.type].apply(this, flashObject);
					});
					var self = this;
					setTimeout(function () { self._executeNextEvent(); }, 0);
				}
		},
		_executeNextEvent: function() {
				var  f = this._eventsQueue ? this._eventsQueue.shift() : null;
				if (typeof(f) === "function") {
					f.apply(this);
				}
		},
		addZero: function(iInput) {
				return (iInput < 10) ? '0' + iInput : iInput;
		},
		getDateTime: function() {
				var oDate = new Date();
				var dateTime = {
						y: oDate.getFullYear(),
						m: (oDate.getMonth() + 1),
						d: oDate.getDate(),
						h: oDate.getHours(),
						i: oDate.getMinutes(),
						s: oDate.getSeconds()
					};
				dateTime.date = this.addZero(dateTime.d) + '-' + this.addZero(dateTime.m) + '-' + dateTime.y;
				dateTime.time = this.addZero(dateTime.h) + ':' + this.addZero(dateTime.i) + ':' + this.addZero(dateTime.s);
				return dateTime;
		},
		parseTime: function(iInput) {
				iHours = Math.round(iInput / 3600);
				iInput -= (iHours * 3600);
				iMinutes = Math.round(iInput / 60);
				iInput -= (iMinutes * 60);
				iSeconds = Math.round(iInput);
				return { h: iHours, i: iMinutes, s: iSeconds };
		},
		formatTime: function(iInput) {
				var oTime = this.parseTime(iInput);
				var sTime = '';
				if (iHours > 0)
					sTime+= this.addZero(oTime.h) + ':';
				sTime+= this.addZero(oTime.i) + ':';
				sTime+= this.addZero(oTime.s);
				return sTime;
		},
		formatNumber: function(number, decimals, dec_point, thousands_sep ) {
				var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
				var d = dec_point == undefined ? "." : dec_point;
				var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
				var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
				return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
		},
		formatSize: function(iInput) {
				if (iInput >= 1073741824) {
					iInput = this.formatNumber(iInput / 1073741824, 2, '.', '') + ' Gb';
				} else {
					if (iInput >= 1048576) {
						iInput = this.formatNumber(iInput / 1048576, 2, '.', '') + ' Mb';
					} else {
						if (iInput >= 1024) {
							iInput = this.formatNumber(iInput / 1024, 2) + ' Kb';
						} else {
							iInput = this.formatNumber(iInput, 0) + ' bytes';
						}
					}
				}
				return iInput;
		},
		setEnabled: function(allow) {
				this._swf.setEnabled(allow ? "1" : "0");
		},
		setLogging: function(allow) {
				this._swf.setLogging(allow ? "1" : "0");
		},
		setMultiple: function(allow) {
				this._swf.setMultiple(allow ? "1" : "0");
		},
		setFilters: function(filters) { 
				this._swf.setFilters(filters);
		},
		setMaxFileSize: function(maxSize) {
				this._swf.setMaxFileSize(maxSize);
		},
		setMaxQueueSize: function(maxSize) {
				this._swf.setMaxQueueSize(maxSize);
		},
		setMaxQueueCount: function(maxCount) {
				this._swf.setMaxQueueCount(maxCount);
		},
		setMaxThreads: function(maxThreads) {
				this._swf.setMaxThreads(maxThreads);
		},
		setAutoAdvanceOnCancel: function(advance) {
				this._swf.setAutoAdvanceOnCancel(advance ? "1" : "0");
		},
		setAutoAdvanceOnError: function(advance) {
				this._swf.setAutoAdvanceOnError(advance ? "1" : "0");
		},
		remove: function(fileID) {
				this._swf.remove(fileID);
		},
		cancel: function(fileID) {
				this._swf.cancel(fileID);
		},
		upload: function(fileID, uploadScriptURL, method, vars, fieldName) {
				this._swf.upload(fileID, uploadScriptURL, method, vars, fieldName);
		} 
	});
	
	$.ui.uploader.eventHandler = function(elementID, params) {
		 		var overlay = $('#' + elementID).parent()[0];
				var o = $.data(  overlay ,"uploader");
				if ( !o ) {
					setTimeout(function() { $.ui.uploader.eventHandler(elementID, params); }, 10);
					return;
				}
				o._queueEvent(params);
	};
		
	$.ui.uploader.defaults = {
		swfURL: '/medias/jquery.uploader.swf',
		movieID: null,
		backgroundColor: '#ffffff',
		wmode: 'transparent',
		logging: "0",
		allowedDomain: "*",
		enabled: "1",
		multiple: "1",
		maxFileSize: -1,
		maxQueueSize: -1,
		maxQueueCount: -1,
		maxThreads: "6",
		autoAdvanceOnCancel: "1",
		autoAdvanceOnError: "1",
		buttonSkin: '',
		events: {
			uploaderReady: function () {},
			uploaderFailed: function () {},
			rollOver: function() {},
			mouseDown: function() {},
			mouseUp: function() {},
			rollOut: function() {},
			multipleFilesDialogOpened: function() {},
			multipleFilesDialogClosed: function(args) {},
			multipleFilesDialogCancelled: function() {},
			singleFileDialogOpened: function() {},
			singleFileDialogClosed: function(args) {},
			singleFileDialogCancelled: function() {},
			fileErrorSize: function(args) {},
			fileErrorExtension: function(args) {},
			fileErrorNotFound: function(args) {},
			queueErrorSize: function(args) {},
			queueErrorEmpty: function(args) {},
			queueErrorCount: function(args) {},
			fileAdded: function(args) {},
			fileRemoved: function(args) {},
			queueCleared: function() {},
			queueStarted: function() {},
			fileUploadStarted: function(args) {},
			fileUploadProgress: function(args) {},
			fileUploadCancelled: function(args) {},
			fileUploadCompleted: function(args) {},
			fileUploadError: function(args) {},
			fileUploadServerData: function(args) {},
			queueCancelled: function(args) {},
			queueCompleted: function(args) {}
		}
	};

})(jQuery);

jQuery.fn.fileUpload = function () {
	return this.each(function() { 
		var blackbird = "0" ;
		var o = $(this) ;
		var uName = o.attr("name"); 
		var overlayName = uName + "overlay" ;
		var movieName = uName + "movie" ;
		//
		// Step 0: extract info from args
		var uTarget = $("input[name=WACformSUBMITTarget]", o).val();
		var uData = o.formToArray(); 
		var objectData= new Object();
		for (x in uData) {
			objectData[ uData[x].name ] = uData[x].value;
		}
		var fileTypes = "*.*" ; // all file allowed by default
		var fileTypesArray = $("input[name=WACfileUploadTypes]", o).val().split(";");
		for ( x in fileTypesArray ) {
			if( x == 0) {
				fileTypes = "*."+fileTypesArray[x];
			} else {
				fileTypes+= ";*."+fileTypesArray[x]
			}
		}
		var fileDescription = "fichiers de type : " + fileTypes
		var fileSize = parseInt($("input[name=WACfileUploadSize]", o).val())
		fileSize = isNaN(fileSize) ? 102400 : fileSize ; // max file size of 100 Ko by default 
	  // Step 1: create updload overlay an size it to the same size as the form
		var b = o.find("a[id$=_Submit], button[name=Submit], input[type=submit][name=Submit] ").get(0) ;
		var uHeight = $(b).css("height");
		var uWidth = $(b).css("width");
		var uPosition = $(b).css("position");
		var uLeft = $(b).css("left");
		var uRight = $(b).css("right");
		var uTop = $(b).css("top");
		var uBottom = $(b).css("bottom");
		$(b).before("<div id='"+overlayName+"' style='height:"+uHeight+"; width:"+uWidth+";position:"+uPosition+";z-index: 2;'></div>")
		if (uTop == "0px" && uBottom =="0px") {
			uBottom = "";
		} else {
			if (uTop == "0px") {
				uTop = "";
			} else {
				uBottom = "";
			}
		}
		if (uLeft == "0px" && uRight =="0px") {
			uRight = "";
		} else {
			if (uLeft == "0px") {
				uLeft = "";
			} else {
				uRight = "";
			}
		}
		$("#" + overlayName ).css({ top: uTop, bottom: uBottom, left: uLeft, right: uRight });
		//
		// Step 2: Add the uploader 
		if( blackbird == "1") {
			$("#blackbird").css({display: "block", top: "30%", left: "30%", zIndex: 9999 });
		}
		$( "#" + overlayName ).uploader({
			logging: blackbird, // no logging 0 with logging 1
			movieID: movieName, // unique movie id 
			maxFileSize: fileSize , // limit max file size
			maxQueueCount: 1, // disable operation until the file is uploaded 
			multiple: "0",  // only one file allowed
			events: {
				uploaderReady: function() {
						this.setFilters([
											{ description: fileDescription , extensions: fileTypes }
										]);
				},
				/**
				 * File added handler
				 */
				fileAdded: function(args) {
						this.upload(args.fileData.id, '/4DCGI/actions/pro_form.a4d','GET', objectData ,'A4D_Upload');
						$(b).css({visibility: "hidden"});
				},
				/**
				 * Triggered when a file is upload starts
				 */
				fileUploadStarted: function(args) {
						$(uTarget).html("<div id='WACfileUploadProgress'><div class='WAC-ajaxLoader-small'><img src='/images/working.gif' border='0' /><span></span></div></div>");
				},
				/**
				 * Triggered when a file is upload starts
				 */
				fileUploadProgress: function(args) {
					  $("#WACfileUploadProgress span", uTarget).html(args.fileProgress.progress);
				},
				/**
				 * Triggered when a file is uploaded (or has an error)
				 */
				fileUploadCompleted: function(args) {
						//
						// You need to remove the file from the queue or else you can't upload any more!
						this.remove(args.fileData.id);
						$("#WACfileUploadProgress", uTarget).html("<img src='/images/tick.png' />"); 
				},
				/**
				 * Triggered when a file upload is cancelled
				 */
				fileUploadCancelled: function(args) {
					 $("#WACfileUploadProgress", uTarget).html("<img src='/images/cancel.png' />"); 
				},
				/**
				 * Triggered when a file is uploaded (or has an error)
				 */
				fileUploadError: function(args) {
						//
						// You need to remove the file from the queue or else you can't upload any more!
						this.remove(args.fileData.id);
						$("#WACfileUploadProgress", uTarget).html("<img src='/images/cross.png' />");
				},
				/**
				 * Server data returned
				 */
				fileUploadServerData: function(args) {
					$.ajax({ 
						type: "GET", 
						url: args.serverData,
						success: function(msg){
							$(uTarget).html(msg);
							$(b).css({visibility: "visible"}); 
							},
						error: function(){
							$(uTarget).html("<img src='/images/cross.png' />"); 
							}
						});
				}
			}
		});
	})
};
/* 
 * initiate plug-ins if needed
 */ 

$(function(){
	$.ajaxSetup({cache:false});
	$('ul.WAC-chapters').jdMenu();
	$(document).bind('click', function() {$('ul.WAC-chapters ul:visible').jdMenuHide();});
	$('ul.WAC-menus').jdMenu();
	$(document).bind('click', function() {$('ul.WAC-menus ul:visible').jdMenuHide();});
	$(".MetaDiv").remove();
	var oUpload ;
});

