/*  
	1. stepcarousel
	2. easing (menu) min file
	3. lavalamp (menu)
	4. hoverpulse
	5. pngfix
	6. jPlayer
	7. onImagesLoaded
	8. preloadCssImages
	9. rsv
   10. centerInClient
/*
 * 1. stepcarousel
*/
	var stepcarousel={
		ajaxloadingmsg: '<div style="position: relative; margin: 15px auto 0 auto; text-align: center; width: 376px; font-weight: bold;color: #d4360d; direction: rtl;"><p>טוען...</p> <img src="img/slider/ajax-loader.gif" /></div>', //customize HTML to show while fetching Ajax content
		defaultbuttonsfade: 0.5, //Fade degree for disabled nav buttons (0=completely transparent, 1=completely opaque)
		configholder: {},
	
		getCSSValue:function(val){ //Returns either 0 (if val contains 'auto') or val as an integer
			return (val=="auto")? 0 : parseInt(val)
		},
	
		getremotepanels:function($, config){ //function to fetch external page containing the panel DIVs
			config.$belt.html(this.ajaxloadingmsg)
			$.ajax({
				url: config.contenttype[1], //path to external content
				async: true,
				error:function(ajaxrequest){
					config.$belt.html('Error fetching content.<br />Server Response: '+ajaxrequest.responseText)
				},
				success:function(content){
					config.$belt.html(content)
					config.$panels=config.$gallery.find('.'+config.panelclass)
					stepcarousel.alignpanels($, config)
				}
			})
		},
	
		getoffset:function(what, offsettype){
			return (what.offsetParent)? what[offsettype]+this.getoffset(what.offsetParent, offsettype) : what[offsettype]
		},
	
		getCookie:function(Name){ 
			var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
			if (document.cookie.match(re)) //if cookie found
				return document.cookie.match(re)[0].split("=")[1] //return its value
			return null
		},
	
		setCookie:function(name, value){
			document.cookie = name+"="+value
		},
	
		fadebuttons:function(config, currentpanel){
			if (currentpanel==config.lastvisiblepanel) {
				config.$leftnavbutton.fadeTo('fast',this.defaultbuttonsfade).addClass('btnDisabled').removeClass('selected').css('cursor','default');
			} else {
				config.$leftnavbutton.fadeTo('fast',1).removeClass('btnDisabled').css('cursor','pointer');
			}
			
			if (currentpanel==0) {
				config.$rightnavbutton.fadeTo('fast',this.defaultbuttonsfade).addClass('btnDisabled').removeClass('selected').css('cursor','default');
			} else {
				config.$rightnavbutton.fadeTo('fast',1).removeClass('btnDisabled').css('cursor','pointer');
			}
		},
	
		addnavbuttons:function($, config, currentpanel){
			config.$leftnavbutton=$('#leftNavBtn');
			config.$rightnavbutton=$('#rightNavBtn');
			config.$leftnavbutton.bind('click', function(){ //assign nav button event handlers
				if (!$(this).hasClass('btnDisabled')) {
					$('.sliderLink').hide();
				}
				stepcarousel.stepBy(config.galleryid, config.defaultbuttons.moveby);
			})
			config.$rightnavbutton.bind('click', function(){ //assign nav button event handlers
				if (!$(this).hasClass('btnDisabled')) {
					$('.sliderLink').hide();
				}
				stepcarousel.stepBy(config.galleryid, -config.defaultbuttons.moveby);
			})
			if (config.panelbehavior.wraparound==false){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
				this.fadebuttons(config, currentpanel);
			}
			return config.$leftnavbutton.add(config.$rightnavbutton)
		},
	
		stopautostep:function(config){
			clearTimeout(config.steptimer)
			clearTimeout(config.resumeautostep)
		},
	
		alignpanels:function($, config){
			var paneloffset=0
			config.paneloffsets=[paneloffset] //array to store upper left offset of each panel (1st element=0)
			config.panelwidths=[] //array to store widths of each panel
			config.$panels.each(function(index){ //loop through panels
				var $currentpanel=$(this)
				$currentpanel.css({float: 'none', position: 'absolute', left: paneloffset+'px'}) //position panel
				$currentpanel.bind('click', function(e){return config.onpanelclick(e.target)}) //bind onpanelclick() to onclick event
				paneloffset+=stepcarousel.getCSSValue($currentpanel.css('marginRight')) + parseInt($currentpanel.get(0).offsetWidth || $currentpanel.css('width')) //calculate next panel offset
				config.paneloffsets.push(paneloffset) //remember this offset
				config.panelwidths.push(paneloffset-config.paneloffsets[config.paneloffsets.length-2]) //remember panel width
			})
			config.paneloffsets.pop() //delete last offset (redundant)
			var addpanelwidths=0
			var lastpanelindex=config.$panels.length-1
			config.lastvisiblepanel=lastpanelindex
			for (var i=config.$panels.length-1; i>=0; i--){
				addpanelwidths+=(i==lastpanelindex? config.panelwidths[lastpanelindex] : config.paneloffsets[i+1]-config.paneloffsets[i])
				if (config.gallerywidth>addpanelwidths){
					config.lastvisiblepanel=i //calculate index of panel that when in 1st position reveals the very last panel all at once based on gallery width
				}
			}
			config.$belt.css({width: paneloffset+'px'}) //Set Belt DIV to total panels' widths
			config.currentpanel=(config.panelbehavior.persist)? parseInt(this.getCookie(window[config.galleryid+"persist"])) : 0 //determine 1st panel to show by default
			config.currentpanel=(typeof config.currentpanel=="number" && config.currentpanel<config.$panels.length)? config.currentpanel : 0
			if (config.currentpanel!=0){
				var endpoint=config.paneloffsets[config.currentpanel]+(config.currentpanel==0? 0 : config.beltoffset)
				config.$belt.css({left: -endpoint+'px'})
			}
			if (config.defaultbuttons.enable==true){ //if enable default back/forth nav buttons
				var $navbuttons=this.addnavbuttons($, config, config.currentpanel)
				$(window).bind("load resize", function(){ //refresh position of nav buttons when page loads/resizes, in case offsets weren't available document.oncontentload
					config.offsets={left:stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}
					config.$leftnavbutton.css({left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px'})
					config.$rightnavbutton.css({left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px'})
				})
			}
			if (config.autostep && config.autostep.enable){ //enable auto stepping of Carousel?		
				var $carouselparts=config.$gallery.add(typeof $navbuttons!="undefined"? $navbuttons : null)
				$carouselparts.bind('click', function(){
					stepcarousel.stopautostep(config)
					config.autostep.status="stopped"
				})
				$carouselparts.hover(function(){ //onMouseover
					stepcarousel.stopautostep(config)
					config.autostep.hoverstate="over"
				}, function(){ //onMouseout
					if (config.steptimer && config.autostep.hoverstate=="over" && config.autostep.status!="stopped"){
						config.resumeautostep=setTimeout(function(){
							stepcarousel.autorotate(config.galleryid)
							config.autostep.hoverstate="out"
						}, 500)
					}
				})
				config.steptimer=setTimeout(function(){stepcarousel.autorotate(config.galleryid)}, config.autostep.pause) //automatically rotate Carousel Viewer
			} //end enable auto stepping check
			this.statusreport(config.galleryid)
			config.oninit()
			config.onslideaction(this)
		},
	
		stepTo:function(galleryid, pindex){ /*User entered pindex starts at 1 for intuitiveness. Internally pindex still starts at 0 */
			var config=stepcarousel.configholder[galleryid]
			if (typeof config=="undefined"){
				alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
				return
			}
			stepcarousel.stopautostep(config)
			var pindex=Math.min(pindex-1, config.paneloffsets.length-1)
			var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset)
			if (config.panelbehavior.wraparound==false && config.defaultbuttons.enable==true){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
				this.fadebuttons(config, pindex)
			}
			config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this);
																									 			});
			config.currentpanel=pindex;
			this.statusreport(galleryid);
		},
	
		stepBy:function(galleryid, steps){ //isauto if defined indicates stepBy() is being called automatically
			var config=stepcarousel.configholder[galleryid]
			if (typeof config=="undefined"){
				alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
				return
			}
			stepcarousel.stopautostep(config)
			var direction=(steps>0)? 'forward' : 'back' //If "steps" is negative, that means backwards
			var pindex=config.currentpanel+steps //index of panel to stop at
			if (config.panelbehavior.wraparound==false){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
				pindex=(direction=="back" && pindex<=0)? 0 : (direction=="forward")? Math.min(pindex, config.lastvisiblepanel) : pindex
				if (config.defaultbuttons.enable==true){ //if default nav buttons are enabled, fade them in and out depending on if at start or end of carousel
					stepcarousel.fadebuttons(config, pindex)
				}	
			}
			else{ //else, for normal stepBy behavior
				if (pindex>config.lastvisiblepanel && direction=="forward"){
					//if destination pindex is greater than last visible panel, yet we're currently not at the end of the carousel yet
					pindex=(config.currentpanel<config.lastvisiblepanel)? config.lastvisiblepanel : 0
				}
				else if (pindex<0 && direction=="back"){
					//if destination pindex is less than 0, yet we're currently not at the beginning of the carousel yet
					pindex=(config.currentpanel>0)? 0 : config.lastvisiblepanel /*wrap around left*/
				}
			}
			var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset) //left distance for Belt DIV to travel to
			if (pindex==0 && direction=='forward' || config.currentpanel==0 && direction=='back' && config.panelbehavior.wraparound==true){ //decide whether to apply "push pull" effect
				config.$belt.animate({left: -config.paneloffsets[config.currentpanel]-(direction=='forward'? 100 : -30)+'px'}, 'normal', function(){
					config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
				})
			}
			else
				config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
			config.currentpanel=pindex
			this.statusreport(galleryid)
		},
	
		autorotate:function(galleryid){
			var config=stepcarousel.configholder[galleryid]
			if (config.$gallery.attr('_ismouseover')!="yes"){
				this.stepBy(galleryid, config.autostep.moveby)
			}
			config.steptimer=setTimeout(function(){stepcarousel.autorotate(galleryid)}, config.autostep.pause)
		},
		
		statusreport:function(galleryid){
			var config=stepcarousel.configholder[galleryid]
			var startpoint=config.currentpanel //index of first visible panel 
			var visiblewidth=0
			for (var endpoint=startpoint; endpoint<config.paneloffsets.length; endpoint++){ //index (endpoint) of last visible panel
				visiblewidth+=config.panelwidths[endpoint]
				if (visiblewidth>config.gallerywidth){
					break
				}
			}
			startpoint+=1 //format startpoint for user friendiness
			endpoint=(endpoint+1==startpoint)? startpoint : endpoint //If only one image visible on the screen and partially hidden, set endpoint to startpoint
			var valuearray=[startpoint, endpoint, config.panelwidths.length]
			for (var i=0; i<config.statusvars.length; i++){
				window[config.statusvars[i]]=valuearray[i] //Define variable (with user specified name) and set to one of the status values
				config.$statusobjs[i].text(valuearray[i]+" ") //Populate element on page with ID="user specified name" with one of the status values
			}
		},
	
		setup:function(config){
			//Disable Step Gallery scrollbars ASAP dynamically (enabled for sake of users with JS disabled)
			document.write('<style type="text/css">\n#'+config.galleryid+'{overflow: hidden;}\n</style>')
			jQuery(document).ready(function($){
				config.$gallery=$('#'+config.galleryid)
				config.gallerywidth=config.$gallery.width()
				config.offsets={left:stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}
				config.$belt=config.$gallery.find('.'+config.beltclass) //Find Belt DIV that contains all the panels
				config.$panels=config.$gallery.find('.'+config.panelclass) //Find Panel DIVs that each contain a slide
				config.panelbehavior.wraparound=(config.autostep && config.autostep.enable)? true : config.panelbehavior.wraparound //if auto step enabled, set "wraparound" to true
				config.onpanelclick=(typeof config.onpanelclick=="undefined")? function(target){} : config.onpanelclick //attach custom "onpanelclick" event handler
				config.onslideaction=(typeof config.onslide=="undefined")? function(){} : function(beltobj){$(beltobj).stop(); config.onslide()} //attach custom "onslide" event handler
				config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
				config.beltoffset=stepcarousel.getCSSValue(config.$belt.css('marginLeft')) //Find length of Belt DIV's left margin
				config.statusvars=config.statusvars || []  //get variable names that will hold "start", "end", and "total" slides info
				config.$statusobjs=[$('#'+config.statusvars[0]), $('#'+config.statusvars[1]), $('#'+config.statusvars[2])]
				config.currentpanel=0
				stepcarousel.configholder[config.galleryid]=config //store config parameter as a variable
				if (config.contenttype[0]=="ajax" && typeof config.contenttype[1]!="undefined") //fetch ajax content?
					stepcarousel.getremotepanels($, config)
				else
					stepcarousel.alignpanels($, config) //align panels and initialize gallery
			}) //end document.ready
			jQuery(window).bind('unload', function(){ //clean up
				if (config.panelbehavior.persist){
					stepcarousel.setCookie(window[config.galleryid+"persist"], config.currentpanel)
				}
				jQuery.each(config, function(ai, oi){
					oi=null
				})
				config=null
			})
		}
	}
/*
 * 2. easing (menu)
*/
jQuery.easing={easein:function(x,t,b,c,d){return c*(t/=d)*t+b},easeinout:function(x,t,b,c,d){if(t<d/2)return 2*c*t*t/(d*d)+b;var a=t-d/2;return-2*c*a*a/(d*d)+2*c*a/d+c/2+b},easeout:function(x,t,b,c,d){return-c*t*t/(d*d)+2*c*t/d+b},expoin:function(x,t,b,c,d){var a=1;if(c<0){a*=-1;c*=-1}return a*(Math.exp(Math.log(c)/d*t))+b},expoout:function(x,t,b,c,d){var a=1;if(c<0){a*=-1;c*=-1}return a*(-Math.exp(-Math.log(c)/d*(t-d))+c+1)+b},expoinout:function(x,t,b,c,d){var a=1;if(c<0){a*=-1;c*=-1}if(t<d/2)return a*(Math.exp(Math.log(c/2)/(d/2)*t))+b;return a*(-Math.exp(-2*Math.log(c/2)/d*(t-d))+c+1)+b},bouncein:function(x,t,b,c,d){return c-jQuery.easing['bounceout'](x,d-t,0,c,d)+b},bounceout: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}},bounceinout:function(x,t,b,c,d){if(t<d/2)return jQuery.easing['bouncein'](x,t*2,0,c,d)*.5+b;return jQuery.easing['bounceout'](x,t*2-d,0,c,d)*.5+c*.5+b},elasin: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},elasout: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},elasinout: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},backin:function(x,t,b,c,d){var s=1.70158;return c*(t/=d)*t*((s+1)*t-s)+b},backout:function(x,t,b,c,d){var s=1.70158;return c*((t=t/d-1)*t*((s+1)*t+s)+1)+b},backinout:function(x,t,b,c,d){var 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},linear:function(x,t,b,c,d){return c*t/d+b}};

/*
 * 3. lavalamp (menu)
*/
(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(el) {
            $back.css({ "left": el.offsetLeft+"px", "width": el.offsetWidth+"px" });
            curr = el;
        };

        function move(el) {
            $back.each(function() {
                $(this).dequeue(); }
            ).animate({
                width: el.offsetWidth,
                left: el.offsetLeft
            }, o.speed, o.fx);
        };

    });
};
})(jQuery);

/*
* 4. hoverpulse
*/
(function($) {

$.fn.hoverpulse = function(options) {
	var opts = $.extend({}, $.fn.hoverpulse.defaults, options);
	var thisId = 'empty';
	var arrId = [];
	// parent must be relatively positioned
	this.parent().css({ position: 'relative' });
	// pulsing element must be absolutely positioned
	this.css({ position: 'absolute', top: 0, left: 0 });

	this.each(function() {
		var $this = $(this);
		arrId[$this.attr('id')] = 'off';
		var w = $this.width(), h = $this.height();
		$this.data('hoverpulse.size', { w: parseInt(w), h: parseInt(h) });
	});
	var clearHover = function(id){
		setTimeout(function() {arrId[id] = 'off';}, 200);
	};
	// bind hover event for behavior
	return this.hover(
		// hover over
		function() {
			var $this = $(this);
			if (arrId[$this.attr('id')] == 'off'){
				arrId[$this.attr('id')] = 'on';
				$this.parent().css('z-index', opts.zIndexActive);
				
				var size = $this.data('hoverpulse.size');
				var w = size.w, h = size.h;
				//console.log(w*opts.size,h*opts.size);
				$this.stop().animate({ 
					top:  ('-'+'18px'), 
					left: ('-'+'27px'), 
					//height: (h+2*opts.size)+'px', 
					//width:	(w+2*opts.size)+'px' 
					//height: (h*opts.size)+'px', 
					//width:	(w*opts.size)+'px' 
					height: '78px', 
					width:	'115px'
				}, opts.speed);
			}
		},
		// hover out
		function() {
			var $this = $(this);
			var size = $this.data('hoverpulse.size');
			var w = size.w, h = size.h;
			
			$this.stop().animate({ 
				top:  0, 
				left: 0, 
				height: (h+'px'), 
				width:	(w+'px') 
			}, opts.speed, function() {
				$this.parent().css('z-index', opts.zIndexNormal);
				clearHover($this.attr('id'));
			});
		}
	);
};

$.fn.hoverpulse.defaults = {
	size:  20,
	speed: 200,
	zIndexActive: 100,
	zIndexNormal: 1
};

})(jQuery);

/*
* 5. pngfix
*/
(function($) {
	
	$.fn.pngfix = function(options) {
		
		// Review the Microsoft IE developer library for AlphaImageLoader reference 
		// http://msdn2.microsoft.com/en-us/library/ms532969(VS.85).aspx
		
		// ECMA scope fix
		var elements 	= this;
		var settings 	= $.extend({
			imageFixSrc: 	false,
			sizingMethod: 	false 
		}, options);
		
		if(!$.browser.msie || ($.browser.msie &&  $.browser.version >= 7)) {
			return(elements);
		}

		function setFilter(el, path, mode) {
			var fs = el.attr("filters");
			var alpha = "DXImageTransform.Microsoft.AlphaImageLoader";
			if (fs[alpha]) {
				fs[alpha].enabled = true;
				fs[alpha].src = path; 
				fs[alpha].sizingMethod = mode;
			} else {
				el.css("filter", 'progid:' + alpha + '(enabled="true", sizingMethod="' + mode + '", src="' + path + '")');			
			}
		}
		
		function setDOMElementWidth(el) {
			if(el.css("width") == "auto" & el.css("height") == "auto") {
				el.css("width", el.attr("offsetWidth") + "px");
			}
		}

		return(
			elements.each(function() {
				
				// Scope
				var el = $(this);
				
				if(el.attr("tagName").toUpperCase() == "IMG" && (/\.png/i).test(el.attr("src"))) {
					if(!settings.imageFixSrc) {
						
						// Wrap the <img> in a <span> then apply style/filters, 
						// removing the <img> tag from the final render 
						el.wrap("<span></span>");
						var par = el.parent();
						par.css({
							height: 	el.height(),
							width: 		el.width(),
							display: 	"inline-block"
						});
						setFilter(par, el.attr("src"), "scale");
						el.remove();
					} else if((/\.gif/i).test(settings.imageFixSrc)) {
						
						// Replace the current image with a transparent GIF
						// and apply the filter to the background of the 
						// <img> tag (not the preferred route)
						setDOMElementWidth(el);
						setFilter(el, el.attr("src"), "image");
						el.attr("src", settings.imageFixSrc);
					}
					
				} else {
					var bg = new String(el.css("backgroundImage"));
					var matches = bg.match(/^url\("(.*)"\)$/);
					if(matches && matches.length) {
						
						// Elements with a PNG as a backgroundImage have the
						// filter applied with a sizing method relevant to the 
						// background repeat type
						setDOMElementWidth(el);
						el.css("backgroundImage", "none");
						
						// Restrict scaling methods to valid MSDN defintions (or one custom)
						var sc = "crop";
						if(settings.sizingMethod) {
							sc = settings.sizingMethod;
						} 
						setFilter(el, matches[1], sc);
						
						// Fix IE peek-a-boo bug for internal links
						// within that DOM element
						el.find("a").each(function() {
							$(this).css("position", "relative");
						});
					}
				}
				
			})
		);
	}

})(jQuery);
/*
*	6. jPlayer
*/
(function($) {
	$.jPlayerCount = 0;
	
	var methods = {
		jPlayer: function(options) {
			$.jPlayerCount++;
			
			var config = {
				ready: null,
				cssPrefix: "jqjp",
				swfPath: "js",
				volume: 80,
				oggSupport: false,
				position: "absolute",
				width: 0,
				height: 0,
				top: 0,
				left: 0,
				quality: "high",
				bgcolor: "#ffffff"
			};
			$.extend(config, options);

			$(this).prepend('<audio id="' + config.aid + '"></audio>'); // Begin check for HTML5 <audio>
			var audioArray = $("#"+config.aid).get();

			var configWithoutOptions = {
				id: $(this).attr("id"),
				swf: config.swfPath + ((config.swfPath != "") ? "/" : "") + "Jplayer.swf",
				fid: config.cssPrefix + "_flash_" + $.jPlayerCount,
				aid: config.cssPrefix + "_audio_" + $.jPlayerCount,
				hid: config.cssPrefix + "_force_" + $.jPlayerCount,
				i: $.jPlayerCount,
				canPlayMP3: Boolean((audioArray[0].canPlayType) ? ("no" != audioArray[0].canPlayType("audio/mpeg")) : false),
				canPlayOGG: Boolean((audioArray[0].canPlayType) ? ("no" != audioArray[0].canPlayType("audio/ogg")) : false),
				audio: audioArray[0]
			};
			$.extend(config, configWithoutOptions);

			$.fn["jPlayerReady" + config.i] = config.ready;

			var configForHtmlAudio = {
				html5: Boolean((config.oggSupport) ? ((config.canPlayOGG) ? true : config.canPlayMP3) : config.canPlayMP3)
			};
			$.extend(config, configForHtmlAudio);

			$(this).data("jPlayer.config", config);

			var events = {
				setButtons: function(e, playing) {
					var playId = $(this).data("jPlayer.cssId.play");
					var pauseId = $(this).data("jPlayer.cssId.pause");
					var prefix = $(this).data("jPlayer.config").cssPrefix;

					if(playId != null && pauseId != null) {
						if(playing) {
							var style = $(this).data("jPlayer.cssDisplay.pause");
							$("#"+playId).css("display", "none");
							$("#"+pauseId).css("display", style);
						} else {
							var style = $(this).data("jPlayer.cssDisplay.play");
							$("#"+playId).css("display", style);
							$("#"+pauseId).css("display", "none");
						}
					}
				}
			};

			var eventsForFlash = {
				setFile: function(e, f) {
					var fid = $(this).data("jPlayer.config").fid;
					var m = $(this).data("jPlayer.getMovie")(fid);
					m.fl_setFile_mp3(f.mp3);
					$(this).trigger("jPlayer.setButtons", false);
				},
				play: function(e) {
					var fid = $(this).data("jPlayer.config").fid;
					var m = $(this).data("jPlayer.getMovie")(fid);
					var r = m.fl_play_mp3();
					if(r) {
						$(this).trigger("jPlayer.setButtons", true);
					}
				},
				pause: function(e) {
					var fid = $(this).data("jPlayer.config").fid;
					var m = $(this).data("jPlayer.getMovie")(fid);
					var r = m.fl_pause_mp3();
					if(r) {
						$(this).trigger("jPlayer.setButtons", false);
					}
				},
				stop: function(e) {
					var fid = $(this).data("jPlayer.config").fid;
					var m = $(this).data("jPlayer.getMovie")(fid);
					var r = m.fl_stop_mp3();
					if(r) {
						$(this).trigger("jPlayer.setButtons", false);
					}
				},
				playHead: function(e, p) {
					var fid = $(this).data("jPlayer.config").fid;
					var m = $(this).data("jPlayer.getMovie")(fid);
					var r = m.fl_play_head_mp3(p);
					if(r) {
						$(this).trigger("jPlayer.setButtons", true);
					}
				},
				playHeadTime: function(e, t) {
					var fid = $(this).data("jPlayer.config").fid;
					var m = $(this).data("jPlayer.getMovie")(fid);
					var r = m.fl_play_head_time_mp3(t);
					if(r) {
						$(this).trigger("jPlayer.setButtons", true);
					}
				},
				volume: function(e, v) {
					var fid = $(this).data("jPlayer.config").fid;
					var m = $(this).data("jPlayer.getMovie")(fid);
					m.fl_volume_mp3(v);
				}
			};

			var eventsForHtmlAudio = {
				setFile: function(e, f) {
					$("#"+$(this).data("jPlayer.config").aid).remove();
					$(this).prepend('<audio id="' + $(this).data("jPlayer.config").aid + '"></audio>');
					var audioArray = $("#"+$(this).data("jPlayer.config").aid).get();
					$(this).data("jPlayer.config").audio = audioArray[0];

					if($(this).data("jPlayer.config").oggSupport && $(this).data("jPlayer.config").canPlayOGG) {
						$(this).data("jPlayer.config").audio.src = f.ogg;
					} else { 
						$(this).data("jPlayer.config").audio.src = f.mp3;
					}
					$(this).trigger("jPlayer.setButtons", false);
				},
				play: function(e) {
					$(this).data("jPlayer.config").audio.play();
					$(this).trigger("jPlayer.setButtons", true);

					clearInterval($(this).data("jPlayer.interval.jPlayerController"));
					$(this).data("jPlayer.interval.jPlayerController", window.setInterval($(this).jPlayerController, 50, $(this), false));
				},
				pause: function(e) {
					$(this).data("jPlayer.config").audio.pause();
					$(this).trigger("jPlayer.setButtons", false);
					clearInterval($(this).data("jPlayer.interval.jPlayerController"));
				},
				stop: function(e) {
					$(this).data("jPlayer.config").audio.currentTime = 0;
					$(this).trigger("jPlayer.pause");
					$(this).jPlayerController($(this), true); // With override true
				},
				playHead: function(e, p) {
					$(this).data("jPlayer.config").audio.currentTime = ($(this).data("jPlayer.config").audio.buffered) ? p * $(this).data("jPlayer.config").audio.buffered.end() / 100 : p * $(this).data("jPlayer.config").audio.duration / 100;
					$(this).trigger("jPlayer.play");
				},
				playHeadTime: function(e, t) {
					$(this).data("jPlayer.config").audio.currentTime = t/1000;
					$(this).trigger("jPlayer.play");
				},
				volume: function(e, v) {
					$(this).data("jPlayer.config").audio.volume = v/100;
					$(this).jPlayerVolume(v);
				}
			};

			if( config.html5 ) {
				$.extend(events, eventsForHtmlAudio);
			} else {
				$.extend(events, eventsForFlash);
			}
			
			for(var event in events) {
				var e = "jPlayer." + event;
				$(this).unbind(e);
				$(this).bind(e, events[event]);
			}

			var getMovie = function(fid) {
				return document[fid];
			};
			$(this).data("jPlayer.getMovie", getMovie);

			// Function checkForFlash adapted from FlashReplace by Robert Nyman
			// http://code.google.com/p/flashreplace/
			var checkForFlash = function (version){
				var flashIsInstalled = false;
				var flash;
				if(window.ActiveXObject){
					try{
						flash = new ActiveXObject(("ShockwaveFlash.ShockwaveFlash." + version));
						flashIsInstalled = true;
					}
					catch(e){
						// Throws an error if the version isn't available			
					}
				}
				else if(navigator.plugins && navigator.mimeTypes.length > 0){
					flash = navigator.plugins["Shockwave Flash"];
					if(flash){
						var flashVersion = navigator.plugins["Shockwave Flash"].description.replace(/.*\s(\d+\.\d+).*/, "$1");
						if(flashVersion >= version){
							flashIsInstalled = true;
						}
					}
				}
				return flashIsInstalled;
			};

			if( !config.html5 ) {
				if(checkForFlash(8)) {
					if($.browser.msie) {
						var html_obj = '<object id="' + config.fid + '"';
						html_obj += ' classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';
						html_obj += ' codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"';
						html_obj += ' type="application/x-shockwave-flash"';
						html_obj += ' width="' + config.width + '" height="' + config.height + '">';
						html_obj += '</object>';
			
						var obj_param = new Array();
						obj_param[0] = '<param name="movie" value="' + config.swf + '" />';
						obj_param[1] = '<param name="quality" value="high" />';
						obj_param[2] = '<param name="FlashVars" value="id=' + escape(config.id) + '&fid=' + escape(config.fid) + '&vol=' + config.volume + '" />';
						obj_param[3] = '<param name="allowScriptAccess" value="always" />';
						obj_param[4] = '<param name="bgcolor" value="' + config.bgcolor + '" />';
				
						var ie_dom = document.createElement(html_obj);
						for(var i=0; i < obj_param.length; i++) {
							ie_dom.appendChild(document.createElement(obj_param[i]));
						}
						$(this).html(ie_dom);
					} else {
						var html_embed = '<embed name="' + config.fid + '" id="' + config.fid + '" src="' + config.swf + '"';
						html_embed += ' width="' + config.width + '" height="' + config.height + '" bgcolor="' + config.bgcolor + '"';
						html_embed += ' quality="high" FlashVars="id=' + escape(config.id) + '&fid=' + escape(config.fid) + '&vol=' + config.volume + '"';
						html_embed += ' allowScriptAccess="always"';
						html_embed += ' type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
						$(this).html(html_embed);
					}
			
				} else {
					$(this).html("<p>Flash 8 or above is not installed. <a href='http://get.adobe.com/flashplayer'>Get Flash!</a></p>");
				}
			}

			var html_hidden = '<div id="' + config.hid + '"></div>';
			$(this).append(html_hidden);
			
			$(this).css({'position':config.position, 'top':config.top, 'left':config.left});
			$("#"+config.hid).css({'text-indent':'-9999px'});

			if( config.html5 ) { // Emulate initial flash calls after 100ms
				window.setTimeout( function(self) {
					self.volume(config.volume);
					self.jPlayerReady();
				}, 100, $(this));
			}
			
			return $(this);
		},
		setFile: function(f1, f2) {
			var f = {mp3:f1, ogg:f2};
			$(this).trigger("jPlayer.setFile", f);
			return $(this);
		},
		play: function() {
			$(this).trigger("jPlayer.play");
			return $(this);
		},
		pause: function() {
			$(this).trigger("jPlayer.pause");
			return $(this);
		},
		stop: function() {
			$(this).trigger("jPlayer.stop");
			return $(this);
		},
		playHead: function(p) {
			$(this).trigger("jPlayer.playHead", p);
			return $(this);
		},
		playHeadTime: function(t) {
			$(this).trigger("jPlayer.playHeadTime", t);
			return $(this);
		},
		volume: function(v) {
			$(this).trigger("jPlayer.volume", v);
			return $(this);
		},
		jPlayerId: function(fn, id) {
			if(id != null) {
				var isValid = eval("$(this)."+fn);
				if(isValid != null) {
					$(this).data("jPlayer.cssId." + fn, id);
					var jPlayerId = $(this).data("jPlayer.config").id;
					eval("var myHandler = function(e) { $(\"#" + jPlayerId + "\")." + fn + "(e); return false; }");
					$("#"+id).click(myHandler).hover($(this).jPlayerRollOver, $(this).jPlayerRollOut).data("jPlayerId", jPlayerId);
					
					var display = $("#"+id).css("display");
					$(this).data("jPlayer.cssDisplay." + fn, display);
					
					if(fn == "pause") {
						$("#"+id).css("display", "none");
					}
				} else {
					alert("Unknown function assigned in: jPlayerId( fn="+fn+", id="+id+" )");
				}
			} else {
				id = $(this).data("jPlayer.cssId." + fn);
				if(id != null) {
					return id;
				} else {
					alert("Unknown function id requested: jPlayerId( fn="+fn+" )");
					return false;
				}
			}
			return $(this);
		},
		loadBar: function(e) { // Handles clicks on the loadBar
			var lbId = $(this).data("jPlayer.cssId.loadBar");
			if( lbId != null ) {
				var offset = $("#"+lbId).offset();
				var x = e.pageX - offset.left;
				var w = $("#"+lbId).width();
				var p = 100*x/w;
				$(this).playHead(p);
			}
		},
		playBar: function(e) { // Handles clicks on the playBar
			$(this).loadBar(e);
		},
		onProgressChange: function(fn) {
			$.fn["jPlayerOnProgressChange" + $(this).data("jPlayer.config").i] = fn;
			return $(this);
		},
		jPlayerOnProgressChange: function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) { // Called from Flash
			var lbId = $(this).data("jPlayer.cssId.loadBar");
			if (lbId != null) {
				$("#"+lbId).width(loadPercent+"%");
			}
			var pbId = $(this).data("jPlayer.cssId.playBar");
			if (pbId != null ) {
				$("#"+pbId).width(playedPercentRelative+"%");
			}
			
			$(this)["jPlayerOnProgressChange" + $(this).data("jPlayer.config").i](loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime);
			$(this).jPlayerForceUpdate();
			return true;
		},
		jPlayerController: function(self, override) { // For HTML5 interval.
			var playedTime = 0;
			var totalTime = 0;
			var playedPercentAbsolute = 0;
			var loadPercent = 0;
			var playedPercentRelative = 0;
			
			if(self.data("jPlayer.config").audio.readyState >= 1) {
				playedTime = self.data("jPlayer.config").audio.currentTime * 1000; // milliSeconds
				totalTime = self.data("jPlayer.config").audio.duration * 1000; // milliSeconds
				playedPercentAbsolute = 100 * playedTime / totalTime;
				loadPercent = (self.data("jPlayer.config").audio.buffered) ? 100 * self.data("jPlayer.config").audio.buffered.end() / self.data("jPlayer.config").audio.duration : 100;
				playedPercentRelative = (self.data("jPlayer.config").audio.buffered) ? 100 * self.data("jPlayer.config").audio.currentTime / self.data("jPlayer.config").audio.buffered.end() : playedPercentAbsolute;
			}
			
			if(override) {
				self.jPlayerOnProgressChange(loadPercent, 0, 0, 0, totalTime);
			} else {
				self.jPlayerOnProgressChange(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime);
				
				if (self.data("jPlayer.config").audio.ended) {
					clearInterval(self.data("jPlayer.interval.jPlayerController"));
					self.jPlayerOnSoundComplete();
				}
			}
		},
		volumeMin: function() {
			$(this).volume(0);
			return $(this);
		},
		volumeMax: function() {
			$(this).volume(100);
			return $(this);
		},
		volumeBar: function(e) { // Handles clicks on the volumeBar
			var vbId = $(this).data("jPlayer.cssId.volumeBar");
			if( vbId != null ) {
				var offset = $("#"+vbId).offset();
				var x = e.pageX - offset.left;
				var w = $("#"+vbId).width();
				var p = 100*x/w;
				$(this).volume(p);
			}
		},
		volumeBarValue: function(e) { // Handles clicks on the volumeBarValue
			$(this).volumeBar(e);
		},
		jPlayerVolume: function(v) { // Called from Flash
			var vbvId = $(this).data("jPlayer.cssId.volumeBarValue");
			if( vbvId != null ) {
				$("#"+vbvId).width(v+"%");
				$(this).jPlayerForceUpdate();
				return true;
			}
		},
		onSoundComplete: function(fn) {
			$.fn["jPlayerOnSoundComplete" + $(this).data("jPlayer.config").i] = fn;
			return $(this);
		},
		jPlayerOnSoundComplete: function() { // Called from Flash
			$(this).trigger("jPlayer.setButtons", false);
			$(this)["jPlayerOnSoundComplete" + $(this).data("jPlayer.config").i]();
			return true;
		},
		jPlayerBufferState: function (b) { // Called from Flash
			var lbId = $(this).data("jPlayer.cssId.loadBar");
			if( lbId != null ) {
				var prefix = $(this).data("jPlayer.config").cssPrefix;
				if(b) {
					$("#"+lbId).addClass(prefix + "_buffer");
				} else {
					$("#"+lbId).removeClass(prefix + "_buffer");
				}
				return true;
			} else {
				return false;
			}
		},
		bufferMsg: function() {
			// Empty: Initialized to enable jPlayerId() to work.
			// See jPlayerBufferMsg() for code.
		},
		jPlayerBufferMsg: function (msg) { // Called from Flash
			var bmId = $(this).data("jPlayer.cssId.bufferMsg");
			if( bmId != null ) {
				$("#"+bmId).html(msg);
				return true;
			} else {
				return false;
			}
		},
		jPlayerForceUpdate: function() { // For Safari and Chrome
			var hid = $(this).data("jPlayer.config").hid;
			$("#"+hid).html(Math.random());
		},
		jPlayerRollOver: function() {
			var jPlayerId = $(this).data("jPlayerId");
			var prefix = $("#"+jPlayerId).data("jPlayer.config").cssPrefix;
			$(this).addClass(prefix + "_hover");
		},
		jPlayerRollOut: function() {
			var jPlayerId = $(this).data("jPlayerId");
			var prefix = $("#"+jPlayerId).data("jPlayer.config").cssPrefix;
			$(this).removeClass(prefix + "_hover");
		},
		jPlayerReady: function() { // Called from Flash
			$(this)["jPlayerReady" + $(this).data("jPlayer.config").i]();
		},
		jPlayerGetInfo: function(info) {
			return $(this).data("jPlayer.config")[info];
		}
	};

	$.each(methods, function(i) {
		$.fn[i] = this;
	});
})(jQuery);


/*
* 7. onImagesLoaded
*/
(function($){$.fn.onImagesLoad=function(options){var self=this;self.opts=$.extend({},$.fn.onImagesLoad.defaults,options);self.bindEvents=function($imgs,container,callback){if($imgs.length===0){if(self.opts.callbackIfNoImagesExist&&callback){callback(container);}}else{var loadedImages=[];if(!$imgs.jquery){$imgs=$($imgs);}$imgs.each(function(i,val){$(this).bind('load',function(){if(jQuery.inArray(i,loadedImages)<0){loadedImages.push(i);if(loadedImages.length==$imgs.length){if(callback){callback(container);}}}}).each(function(){if(this.complete||this.complete===undefined){this.src=this.src;}});});}};var imgAry=[];self.each(function(){if(self.opts.itemCallback){var $imgs;if(this.tagName=="IMG"){$imgs=this;}else{$imgs=$('img',this);}self.bindEvents($imgs,this,self.opts.itemCallback);}if(self.opts.selectorCallback){if(this.tagName=="IMG"){imgAry.push(this);}else{$('img',this).each(function(){imgAry.push(this);});}}});if(self.opts.selectorCallback){self.bindEvents(imgAry,this,self.opts.selectorCallback);}return self.each(function(){});};$.fn.onImagesLoad.defaults={selectorCallback:null,itemCallback:null,callbackIfNoImagesExist:false};})(jQuery);
/*
* 8. preloadCssImages
*/
;jQuery.preloadCssImages = function(settings){
	settings = jQuery.extend({
		statusTextEl: null,
		statusBarEl: null,
		errorDelay: 999, // handles 404-Errors in IE
		simultaneousCacheLoading: 2
	}, settings);
	var allImgs = [],
		loaded = 0,
		imgUrls = [],
		thisSheetRules,	
		errorTimer;
	
	function onImgComplete(){
		clearTimeout(errorTimer);
		if (imgUrls && imgUrls.length && imgUrls[loaded]) {
			loaded++;
			if (settings.statusTextEl) {
				var nowloading = (imgUrls[loaded]) ? 
					'Now Loading: <span>' + imgUrls[loaded].split('/')[imgUrls[loaded].split('/').length - 1] : 
					'Loading complete'; // wrong status-text bug fixed
				jQuery(settings.statusTextEl).html('<span class="numLoaded">' + loaded + '</span> of <span class="numTotal">' + imgUrls.length + '</span> loaded (<span class="percentLoaded">' + (loaded / imgUrls.length * 100).toFixed(0) + '%</span>) <span class="currentImg">' + nowloading + '</span></span>');
			}
			if (settings.statusBarEl) {
				var barWidth = jQuery(settings.statusBarEl).width();
				jQuery(settings.statusBarEl).css('background-position', -(barWidth - (barWidth * loaded / imgUrls.length).toFixed(0)) + 'px 50%');
			}
			loadImgs();
		}
	}
	
	function loadImgs(){
		//only load 1 image at the same time / most browsers can only handle 2 http requests, 1 should remain for user-interaction (Ajax, other images, normal page requests...)
		// otherwise set simultaneousCacheLoading to a higher number for simultaneous downloads
		if(imgUrls && imgUrls.length && imgUrls[loaded]){
			var img = new Image(); //new img obj
			img.src = imgUrls[loaded];	//set src either absolute or rel to css dir
			if(!img.complete){
				jQuery(img).bind('error load onreadystatechange', onImgComplete);
			} else {
				onImgComplete();
			}
			errorTimer = setTimeout(onImgComplete, settings.errorDelay); // handles 404-Errors in IE
		}
	}
	
	function parseCSS(sheets, urls) {
		var w3cImport = false,
			imported = [],
			importedSrc = [],
			baseURL;
		var sheetIndex = sheets.length;
		while(sheetIndex--){//loop through each stylesheet
			
			var cssPile = '';//create large string of all css rules in sheet
			
			if(urls && urls[sheetIndex]){
				baseURL = urls[sheetIndex];
			} else {
				var csshref = (sheets[sheetIndex].href) ? sheets[sheetIndex].href : 'window.location.href';
				var baseURLarr = csshref.split('/');//split href at / to make array
				baseURLarr.pop();//remove file path from baseURL array
				baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir)
				if (baseURL) {
					baseURL += '/'; //tack on a / if needed
				}
			}
			if(sheets[sheetIndex].cssRules || sheets[sheetIndex].rules){
				thisSheetRules = (sheets[sheetIndex].cssRules) ? //->>> http://www.quirksmode.org/dom/w3c_css.html
					sheets[sheetIndex].cssRules : //w3
					sheets[sheetIndex].rules; //ie 
				var ruleIndex = thisSheetRules.length;
				while(ruleIndex--){
					if(thisSheetRules[ruleIndex].style && thisSheetRules[ruleIndex].style.cssText){
						var text = thisSheetRules[ruleIndex].style.cssText;
						if(text.toLowerCase().indexOf('url') != -1){ // only add rules to the string if you can assume, to find an image, speed improvement
							cssPile += text; // thisSheetRules[ruleIndex].style.cssText instead of thisSheetRules[ruleIndex].cssText is a huge speed improvement
						}
					} else if(thisSheetRules[ruleIndex].styleSheet) {
						imported.push(thisSheetRules[ruleIndex].styleSheet);
						w3cImport = true;
					}
					
				}
			}
			//parse cssPile for image urls
			var tmpImage = cssPile.match(/[^\("]+\.(gif|jpg|jpeg|png)/g);//reg ex to get a string of between a "(" and a ".filename" / '"' for opera-bugfix
			if(tmpImage){
				var i = tmpImage.length;
				while(i--){ // handle baseUrl here for multiple stylesheets in different folders bug
					var imgSrc = (tmpImage[i].charAt(0) == '/' || tmpImage[i].match('://')) ? // protocol-bug fixed
						tmpImage[i] : 
						tmpImage[i].substr(3);
					
					if(jQuery.inArray(imgSrc, imgUrls) == -1){
						imgUrls.push(imgSrc);
					}
				}
			}
			
			if(!w3cImport && sheets[sheetIndex].imports && sheets[sheetIndex].imports.length) {
				for(var iImport = 0, importLen = sheets[sheetIndex].imports.length; iImport < importLen; iImport++){
					var iHref = sheets[sheetIndex].imports[iImport].href;
					iHref = iHref.split('/');
					iHref.pop();
					iHref = iHref.join('/');
					if (iHref) {
						iHref += '/'; //tack on a / if needed
					}
					var iSrc = (iHref.charAt(0) == '/' || iHref.match('://')) ? // protocol-bug fixed
						iHref : 
						baseURL + iHref;
					importedSrc.push(iSrc);
					imported.push(sheets[sheetIndex].imports[iImport]);
				}
				
				
			}
		}//loop
		if(imported.length){
			parseCSS(imported, importedSrc);
			return false;
		}
		var downloads = settings.simultaneousCacheLoading;
		while( downloads--){
			setTimeout(loadImgs, downloads);
		}
	}
	parseCSS(document.styleSheets);
	return imgUrls;
};
/*
* 9. rsv
*/
(function($){var options={};var returnHash=[];$.fn.RSV=function(params){options=$.extend({},$.fn.RSV.defaults,params);return this.each(function(){$(this).bind('submit',{currForm:this,options:options},$(this).RSV.validate);});};$.fn.RSV.defaults={rules:[],displayType:"alert-all",errorFieldClass:null,errorTextIntro:"Please fix the following error(s) and resubmit:",errorJSItemBullet:"* ",errorHTMLItemBullet:"&bull; ",errorTargetElementId:"rsvErrors",customErrorHandler:null,onCompleteHandler:null};$.fn.RSV.validate=function(event)
{options=event.data.options;var form=event.data.currForm;var rules=options.rules;returnHash=[];for(var i=0;i<rules.length;i++)
{var row=rules[i].replace(/\\,/ig,"%%C%%");row=row.split(",");var satisfiesIfConditions=true;while(row[0].match("^if:"))
{var cond=row[0];cond=cond.replace("if:","");var comparison="equal";var parts=[];if(cond.search("!=")!=-1)
{parts=cond.split("!=");comparison="not_equal";}
else
parts=cond.split("=");var fieldToCheck=parts[0];var valueToCheck=parts[1];var fieldnameValue="";if(form[fieldToCheck].type==undefined)
{for(var j=0;j<form[fieldToCheck].length;j++)
{if(form[fieldToCheck][j].checked)
fieldnameValue=form[fieldToCheck][j].value;}}
else if(form[fieldToCheck].type=="checkbox")
{if(form[fieldToCheck].checked)
fieldnameValue=form[parts[0]].value;}
else
fieldnameValue=form[parts[0]].value;if(comparison=="equal"&&fieldnameValue!=valueToCheck)
{satisfiesIfConditions=false;break;}
else if(comparison=="not_equal"&&fieldnameValue==valueToCheck)
{satisfiesIfConditions=false;break;}
else
row.shift();}
if(!satisfiesIfConditions)
continue;var requirement=row[0];var fieldName=row[1];var fieldName2,fieldName3,errorMessage,lengthRequirements,date_flag;if(requirement!="function"&&form[fieldName]==undefined)
{alert("RSV Error: the field \""+fieldName+"\" doesn't exist! Please check your form and settings.");return false;}
if(requirement!="function"&&options.errorFieldClass)
{if(form[fieldName].type==undefined)
{for(var j=0;j<form[fieldName].length;j++)
{if($(form[fieldName][j]).hasClass(options.errorFieldClass))
$(form[fieldName][j]).removeClass(options.errorFieldClass);}}
else
{if($(form[fieldName]).hasClass(options.errorFieldClass))
$(form[fieldName]).removeClass(options.errorFieldClass);}}
if(row.length==6)
{fieldName2=row[2];fieldName3=row[3];date_flag=row[4];errorMessage=row[5];}
else if(row.length==5)
{fieldName2=row[2];fieldName3=row[3];errorMessage=row[4];}
else if(row.length==4)
{fieldName2=row[2];errorMessage=row[3];}
else
errorMessage=row[2];if(requirement.match("^length"))
{lengthRequirements=requirement;requirement="length";}
if(requirement.match("^range"))
{rangeRequirements=requirement;requirement="range";}
switch(requirement)
{case"required":if(form[fieldName].type==undefined)
{var oneIsChecked=false;for(var j=0;j<form[fieldName].length;j++)
{if(form[fieldName][j].checked)
oneIsChecked=true;}
if(!oneIsChecked)
{if(!processError(form[fieldName],errorMessage))
return false;}}
else if(form[fieldName].type=="select-multiple")
{var oneIsSelected=false;for(var k=0;k<form[fieldName].length;k++)
{if(form[fieldName][k].selected)
oneIsSelected=true;}
if(!oneIsSelected||form[fieldName].length==0)
{if(!processError(form[fieldName],errorMessage))
return false;}}
else if(form[fieldName].type=="checkbox")
{if(!form[fieldName].checked)
{if(!processError(form[fieldName],errorMessage))
return false;}}
else if(!form[fieldName].value)
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"digits_only":if(form[fieldName].value&&form[fieldName].value.match(/\D/))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"letters_only":if(form[fieldName].value&&form[fieldName].value.match(/[^a-zA-Z]/))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"is_alpha":if(form[fieldName].value&&form[fieldName].value.match(/\W/))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"custom_alpha":var conversion={"L":"[A-Z]","V":"[AEIOU]","l":"[a-z]","v":"[aeiou]","D":"[a-zA-Z]","F":"[aeiouAEIOU]","C":"[BCDFGHJKLMNPQRSTVWXYZ]","x":"[0-9]","c":"[bcdfghjklmnpqrstvwxyz]","X":"[1-9]","E":"[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]"};var reg_exp_str="";for(var j=0;j<fieldName2.length;j++)
{if(conversion[fieldName2.charAt(j)])
reg_exp_str+=conversion[fieldName2.charAt(j)];else
reg_exp_str+=fieldName2.charAt(j);}
var reg_exp=new RegExp(reg_exp_str);if(form[fieldName].value&&reg_exp.exec(form[fieldName].value)==null)
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"reg_exp":var reg_exp_str=fieldName2.replace(/%%C%%/ig, ",");if(row.length==5)
var reg_exp=new RegExp(reg_exp_str,fieldName3);else
var reg_exp=new RegExp(reg_exp_str);if(form[fieldName].value&&reg_exp.exec(form[fieldName].value)==null)
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"length":comparison_rule="";rule_string="";if(lengthRequirements.match(/length=/))
{comparison_rule="equal";rule_string=lengthRequirements.replace("length=","");}
else if(lengthRequirements.match(/length>=/))
{comparison_rule="greater_than_or_equal";rule_string=lengthRequirements.replace("length>=","");}
else if(lengthRequirements.match(/length>/))
{comparison_rule="greater_than";rule_string=lengthRequirements.replace("length>","");}
else if(lengthRequirements.match(/length<=/))
{comparison_rule="less_than_or_equal";rule_string=lengthRequirements.replace("length<=","");}
else if(lengthRequirements.match(/length</))
{comparison_rule="less_than";rule_string=lengthRequirements.replace("length<","");}
switch(comparison_rule)
{case"greater_than_or_equal":if(!(form[fieldName].value.length>=parseInt(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"greater_than":if(!(form[fieldName].value.length>parseInt(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"less_than_or_equal":if(!(form[fieldName].value.length<=parseInt(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"less_than":if(!(form[fieldName].value.length<parseInt(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"equal":var range_or_exact_number=rule_string.match(/[^_]+/);var fieldCount=range_or_exact_number[0].split("-");if(fieldCount.length==2)
{if(form[fieldName].value.length<fieldCount[0]||form[fieldName].value.length>fieldCount[1])
{if(!processError(form[fieldName],errorMessage))
return false;}}
else
{if(form[fieldName].value.length!=fieldCount[0])
{if(!processError(form[fieldName],errorMessage))
return false;}}
break;}
break;case"valid_email":if(form[fieldName].value&&!isValidEmail(form[fieldName].value))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"valid_date":var isLaterDate=false;if(date_flag=="later_date")
isLaterDate=true;else if(date_flag=="any_date")
isLaterDate=false;if(!isValidDate(form[fieldName].value,form[fieldName2].value,form[fieldName3].value,isLaterDate))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"same_as":if(form[fieldName].value!=form[fieldName2].value)
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"range":comparison_rule="";rule_string="";if(rangeRequirements.match(/range=/))
{comparison_rule="equal";rule_string=rangeRequirements.replace("range=","");}
else if(rangeRequirements.match(/range>=/))
{comparison_rule="greater_than_or_equal";rule_string=rangeRequirements.replace("range>=","");}
else if(rangeRequirements.match(/range>/))
{comparison_rule="greater_than";rule_string=rangeRequirements.replace("range>","");}
else if(rangeRequirements.match(/range<=/))


{comparison_rule="less_than_or_equal";rule_string=rangeRequirements.replace("range<=","");}
else if(rangeRequirements.match(/range</))
{comparison_rule="less_than";rule_string=rangeRequirements.replace("range<","");}
switch(comparison_rule)
{case"greater_than_or_equal":if(!(form[fieldName].value>=Number(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"greater_than":if(!(form[fieldName].value>Number(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"less_than_or_equal":if(!(form[fieldName].value<=Number(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"less_than":if(!(form[fieldName].value<Number(rule_string)))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;case"equal":var rangeValues=rule_string.split("-");if((form[fieldName].value<Number(rangeValues[0]))||(form[fieldName].value>Number(rangeValues[1])))
{if(!processError(form[fieldName],errorMessage))
return false;}
break;}
break;case"function":custom_function=fieldName;eval("var result = "+custom_function+"()");if(result.constructor.toString().indexOf("Array")!=-1)
{for(var j=0;j<result.length;j++)
{if(!processError(result[j][0],result[j][1]))
return false;}}
break;default:alert("Unknown requirement flag in validateFields(): "+requirement);return false;}}
if(typeof options.customErrorHandler=='function')
return options.customErrorHandler(form,returnHash);else if(options.displayType=="alert-all")
{var errorStr=options.errorTextIntro+"\n\n";for(var i=0;i<returnHash.length;i++)
{errorStr+=options.errorJSItemBullet+returnHash[i][1]+"\n";styleField(returnHash[i][0],i==0);}
if(returnHash.length>0)
{alert(errorStr);return false;}}
else if(options.displayType=="display-html")
{var success=displayHTMLErrors(form,returnHash);if(!success)
return false;}
if(typeof options.onCompleteHandler=='function')
return options.onCompleteHandler();else
return true;}
function processError(obj,message)
{message=message.replace(/%%C%%/ig,",");var continueProcessing=true;switch(options.displayType)
{case"alert-one":alert(message);styleField(obj,true);continueProcessing=false;break;case"alert-all":case"display-html":returnHash.push([obj,message]);break;}
return continueProcessing;}
function displayHTMLErrors(f,errorInfo)
{var errorHTML=options.errorTextIntro+"<br /><br />";for(var i=0;i<errorInfo.length;i++)
{errorHTML+=options.errorHTMLItemBullet+errorInfo[i][1]+"<br />";styleField(errorInfo[i][0],i==0);}
if(errorInfo.length>0)
{$("#"+options.errorTargetElementId).css("display","block");$("#"+options.errorTargetElementId).html(errorHTML);return false;}
return true;}
function styleField(field,focus)
{if(field.type==undefined)
{if(focus)
field[0].focus();for(var i=0;i<field.length;i++)
{if(!$(field[i]).hasClass(options.errorFieldClass))
$(field[i]).addClass(options.errorFieldClass);}}
else
{if(options.errorFieldClass)
$(field).addClass(options.errorFieldClass);if(focus)
field.focus();}}
function isValidEmail(str)
{var s=$.trim(str);var at="@";var dot=".";var lat=s.indexOf(at);var lstr=s.length;var ldot=s.indexOf(dot);if(s.indexOf(at)==-1||(s.indexOf(at)==-1||s.indexOf(at)==0||s.indexOf(at)==lstr)||(s.indexOf(dot)==-1||s.indexOf(dot)==0||s.indexOf(dot)==lstr)||(s.indexOf(at,(lat+1))!=-1)||(s.substring(lat-1,lat)==dot||s.substring(lat+1,lat+2)==dot)||(s.indexOf(dot,(lat+2))==-1)||(s.indexOf(" ")!=-1))
{return false;}
return true;}
function isValidDate(month,day,year,isLaterDate)
{var daysInMonth;if((year%4==0)&&((year%100!=0)||(year%400==0)))
daysInMonth=[31,29,31,30,31,30,31,31,30,31,30,31];else
daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31];if(!month||!day||!year)return false;if(1>month||month>12)return false;if(year<0)return false;if(1>day||day>daysInMonth[month-1])return false;if(isLaterDate)
{var today=new Date();var currMonth=today.getMonth()+1;var currDay=today.getDate();var currYear=today.getFullYear();if(String(currMonth).length==1)currMonth="0"+currMonth;if(String(currDay).length==1)currDay="0"+currDay;var currDate=String(currYear)+String(currMonth)+String(currDay);if(String(month).length==1)month="0"+month;if(String(day).length==1)day="0"+day;incomingDate=String(year)+String(month)+String(day);if(Number(currDate)>Number(incomingDate))
return false;}
return true;}})(jQuery);

/*
* 10. centerInClient
*/
$.fn.centerInClient = function(options) {
    /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
    /// <returns type="jQuery" />
    var opt = { forceAbsolute: false,
                container: window,    // selector of element to center in
                completeHandler: null
              };
    $.extend(opt, options);
   
    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that 
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}
