/*

	Supersized - Fullscreen Slideshow jQuery Plugin
	Version : 3.2.4
	Site	: www.buildinternet.com/project/supersized
	
	Author	: Sam Dunn
	Company : One Mighty Roar (www.onemightyroar.com)
	License : MIT License / GPL License
	
*/

(function($){

	/* Place Supersized Elements
	----------------------------*/
	$(document).ready(function() {
		$('body').append('<div id="supersized-loader"></div><ul id="supersized"></ul>');
	});
    
    
    $.supersized = function(options){
    	
    	/* Variables
		----------------------------*/
    	var el = '#supersized',
        	base = this;
        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;
        vars = $.supersized.vars;
        // Add a reverse reference to the DOM object
        base.$el.data("supersized", base);
        api = base.$el.data('supersized');
		
		base.init = function(){
        	// Combine options and vars
        	$.supersized.vars = $.extend($.supersized.vars, $.supersized.themeVars);
        	$.supersized.vars.options = $.extend({},$.supersized.defaultOptions, $.supersized.themeOptions, options);
            base.options = $.supersized.vars.options;
            
            base._build();
        };
        
        
        /* Build Elements
		----------------------------*/
        base._build = function(){
        	// Add in slide markers
        	var thisSlide = 0,
        		slideSet = '',
				markers = '',
				markerContent,
				thumbMarkers = '',
				thumbImage;
				
			while(thisSlide <= base.options.slides.length-1){
				//Determine slide link content
				switch(base.options.slide_links){
					case 'num':
						markerContent = thisSlide;
						break;
					case 'name':
						markerContent = base.options.slides[thisSlide].title;
						break;
					case 'blank':
						markerContent = '';
						break;
				}
				
				slideSet = slideSet+'<li class="slide-'+thisSlide+'"></li>';
				
				if(thisSlide == base.options.start_slide-1){
					// Slide links
					if (base.options.slide_links)markers = markers+'<li class="slide-link-'+thisSlide+' current-slide"><a>'+markerContent+'</a></li>';
					// Slide Thumbnail Links
					if (base.options.thumb_links){
						base.options.slides[thisSlide].thumb ? thumbImage = base.options.slides[thisSlide].thumb : thumbImage = base.options.slides[thisSlide].image;
						thumbMarkers = thumbMarkers+'<li class="thumb'+thisSlide+' current-thumb"><img src="'+thumbImage+'"/></li>';
					};
				}else{
					// Slide links
					if (base.options.slide_links) markers = markers+'<li class="slide-link-'+thisSlide+'" ><a>'+markerContent+'</a></li>';
					// Slide Thumbnail Links
					if (base.options.thumb_links){
						base.options.slides[thisSlide].thumb ? thumbImage = base.options.slides[thisSlide].thumb : thumbImage = base.options.slides[thisSlide].image;
						thumbMarkers = thumbMarkers+'<li class="thumb'+thisSlide+'"><img src="'+thumbImage+'"/></li>';
					};
				}
				thisSlide++;
			}
			
			if (base.options.slide_links) $(vars.slide_list).html(markers);
			if (base.options.thumb_links && vars.thumb_tray.length){
				$(vars.thumb_tray).append('<ul id="'+vars.thumb_list.replace('#','')+'">'+thumbMarkers+'</ul>');
			}
			
			$(base.el).append(slideSet);
			
			// Add in thumbnails
			if (base.options.thumbnail_navigation){
				// Load previous thumbnail
				vars.current_slide - 1 < 0  ? prevThumb = base.options.slides.length - 1 : prevThumb = vars.current_slide - 1;
				$(vars.prev_thumb).show().html($("<img/>").attr("src", base.options.slides[prevThumb].image));
				
				// Load next thumbnail
				vars.current_slide == base.options.slides.length - 1 ? nextThumb = 0 : nextThumb = vars.current_slide + 1;
				$(vars.next_thumb).show().html($("<img/>").attr("src", base.options.slides[nextThumb].image));
			}
			
            base._start(); // Get things started
        };
        
        
        /* Initialize
		----------------------------*/
    	base._start = function(){
			
			// Determine if starting slide random
			if (base.options.start_slide){
				vars.current_slide = base.options.start_slide - 1;
			}else{
				vars.current_slide = Math.floor(Math.random()*base.options.slides.length);	// Generate random slide number
			}
			
			// If links should open in new window
			var linkTarget = base.options.new_window ? ' target="_blank"' : '';
			
			// Set slideshow quality (Supported only in FF and IE, no Webkit)
			if (base.options.performance == 3){
				base.$el.addClass('speed'); 		// Faster transitions
			} else if ((base.options.performance == 1) || (base.options.performance == 2)){
				base.$el.addClass('quality');	// Higher image quality
			}
						
			// Shuffle slide order if needed		
			if (base.options.random){
				arr = base.options.slides;
				for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);	// Fisher-Yates shuffle algorithm (jsfromhell.com/array/shuffle)
			    base.options.slides = arr;
			}
			
			/*-----Load initial set of images-----*/
	
			if (base.options.slides.length > 1){
				// Set previous image
				vars.current_slide - 1 < 0  ? loadPrev = base.options.slides.length - 1 : loadPrev = vars.current_slide - 1;	// If slide is 1, load last slide as previous
				var imageLink = (base.options.slides[loadPrev].url) ? "href='" + base.options.slides[loadPrev].url + "'" : "";
				
				var imgPrev = $('<img src="'+base.options.slides[loadPrev].image+'"/>');
				var slidePrev = base.el+' li:eq('+loadPrev+')';
				imgPrev.appendTo(slidePrev).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading prevslide');
				
				imgPrev.load(function(){
					$(this).data('origWidth', $(this).width()).data('origHeight', $(this).height());
					base.resizeNow();	// Resize background image
				});	// End Load
			} else {
				// Slideshow turned off if there is only one slide
				base.options.slideshow = 0;
			}
			
			// Set current image
			imageLink = (api.getField('url')) ? "href='" + api.getField('url') + "'" : "";
			var img = $('<img src="'+api.getField('image')+'"/>');
			
			var slideCurrent= base.el+' li:eq('+vars.current_slide+')';
			img.appendTo(slideCurrent).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading activeslide');
			
			img.load(function(){
				base._origDim($(this));
				base.resizeNow();	// Resize background image
				base.launch();
				if( typeof theme != 'undefined' && typeof theme._init == "function" ) theme._init();	// Load Theme
			});
			
			if (base.options.slides.length > 1){
				// Set next image
				vars.current_slide == base.options.slides.length - 1 ? loadNext = 0 : loadNext = vars.current_slide + 1;	// If slide is last, load first slide as next
				imageLink = (base.options.slides[loadNext].url) ? "href='" + base.options.slides[loadNext].url + "'" : "";
				
				var imgNext = $('<img src="'+base.options.slides[loadNext].image+'"/>');
				var slideNext = base.el+' li:eq('+loadNext+')';
				imgNext.appendTo(slideNext).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading');
				
				imgNext.load(function(){
					$(this).data('origWidth', $(this).width()).data('origHeight', $(this).height());
					base.resizeNow();	// Resize background image
				});	// End Load
			}
			/*-----End load initial images-----*/
			
			//  Hide elements to be faded in
			base.$el.css('visibility','hidden');
			$('.load-item').hide();
			
    	};
		
		
		/* Launch Supersized
		----------------------------*/
		base.launch = function(){
		
			base.$el.css('visibility','visible');
			$('#supersized-loader').remove();		//Hide loading animation
			
			// Call theme function for before slide transition
			if( typeof theme != 'undefined' && typeof theme.beforeAnimation == "function" ) theme.beforeAnimation('next');
			$('.load-item').show();
			
			// Keyboard Navigation
			if (base.options.keyboard_nav){
				$(document.documentElement).keyup(function (event) {
				
					if(vars.in_animation) return false;		// Abort if currently animating
					
					// Left Arrow or Down Arrow
					if ((event.keyCode == 37) || (event.keyCode == 40)) {
						clearInterval(vars.slideshow_interval);	// Stop slideshow, prevent buildup
						base.prevSlide();
					
					// Right Arrow or Up Arrow
					} else if ((event.keyCode == 39) || (event.keyCode == 38)) {
						clearInterval(vars.slideshow_interval);	// Stop slideshow, prevent buildup
						base.nextSlide();
					
					// Spacebar	
					} else if (event.keyCode == 32 && !vars.hover_pause) {
						clearInterval(vars.slideshow_interval);	// Stop slideshow, prevent buildup
						base.playToggle();
					}
				
				});
			}
			
			// Pause when hover on image
			if (base.options.slideshow && base.options.pause_hover){
				$(base.el).hover(function() {
					if(vars.in_animation) return false;		// Abort if currently animating
			   			vars.hover_pause = true;	// Mark slideshow paused from hover
			   			if(!vars.is_paused){
			   				vars.hover_pause = 'resume';	// It needs to resume afterwards
			   				base.playToggle();
			   			}
			   	}, function() {
					if(vars.hover_pause == 'resume'){
						base.playToggle();
						vars.hover_pause = false;
					}
			   	});
			}
			
			if (base.options.slide_links){
				// Slide marker clicked
				$(vars.slide_list+'> li').click(function(){
				
					index = $(vars.slide_list+'> li').index(this);
					targetSlide = index + 1;
					
					base.goTo(targetSlide);
					return false;
					
				});
			}
			
			// Thumb marker clicked
			if (base.options.thumb_links){
				$(vars.thumb_list+'> li').click(function(){
				
					index = $(vars.thumb_list+'> li').index(this);
					targetSlide = index + 1;
					
					api.goTo(targetSlide);
					return false;
					
				});
			}
			
			// Start slideshow if enabled
			if (base.options.slideshow && base.options.slides.length > 1){
	    		
	    		// Start slideshow if autoplay enabled
	    		if (base.options.autoplay && base.options.slides.length > 1){
	    			vars.slideshow_interval = setInterval(base.nextSlide, base.options.slide_interval);	// Initiate slide interval
				}else{
					vars.is_paused = true;	// Mark as paused
				}
				
				//Prevent navigation items from being dragged					
				$('.load-item img').bind("contextmenu mousedown",function(){
					return false;
				});
								
			}
			
			// Adjust image when browser is resized
			$(window).resize(function(){
	    		base.resizeNow();
			});
    		
    	};
        
        
        /* Resize Images
		----------------------------*/
		base.resizeNow = function(){
			
			return base.$el.each(function() {
		  		//  Resize each image seperately
		  		$('img', base.el).each(function(){
		  			
					thisSlide = $(this);
					var ratio = (thisSlide.data('origHeight')/thisSlide.data('origWidth')).toFixed(2);	// Define image ratio
                    if(isNaN(ratio)){
                        thisSlide.data('origHeight', thisSlide.height());
                        thisSlide.data('origWidth', thisSlide.width());
					    ratio = (thisSlide.data('origHeight')/thisSlide.data('origWidth')).toFixed(2);	// Define image ratio
                        if(isNaN(ratio)){
                            base.needsResize = true;
                        }
                    }
					
					// Gather browser size
					var browserwidth = base.$el.width(),
						browserheight = base.$el.height(),
						offset;
					
					/*-----Resize Image-----*/
					if (base.options.fit_always){	// Fit always is enabled
						if ((browserheight/browserwidth) > ratio){
							resizeWidth();
						} else {
							resizeHeight();
						}
					}else{	// Normal Resize
						if ((browserheight <= base.options.min_height) && (browserwidth <= base.options.min_width)){	// If window smaller than minimum width and height
						
							if ((browserheight/browserwidth) > ratio){
								base.options.fit_landscape && ratio < 1 ? resizeWidth(true) : resizeHeight(true);	// If landscapes are set to fit
							} else {
								base.options.fit_portrait && ratio >= 1 ? resizeHeight(true) : resizeWidth(true);		// If portraits are set to fit
							}
						
						} else if (browserwidth <= base.options.min_width){		// If window only smaller than minimum width
						
							if ((browserheight/browserwidth) > ratio){
								base.options.fit_landscape && ratio < 1 ? resizeWidth(true) : resizeHeight();	// If landscapes are set to fit
							} else {
								base.options.fit_portrait && ratio >= 1 ? resizeHeight() : resizeWidth(true);		// If portraits are set to fit
							}
							
						} else if (browserheight <= base.options.min_height){	// If window only smaller than minimum height
						
							if ((browserheight/browserwidth) > ratio){
								base.options.fit_landscape && ratio < 1 ? resizeWidth() : resizeHeight(true);	// If landscapes are set to fit
							} else {
								base.options.fit_portrait && ratio >= 1 ? resizeHeight(true) : resizeWidth();		// If portraits are set to fit
							}
						
						} else {	// If larger than minimums
							
							if ((browserheight/browserwidth) > ratio){
								base.options.fit_landscape && ratio < 1 ? resizeWidth() : resizeHeight();	// If landscapes are set to fit
							} else {
								base.options.fit_portrait && ratio >= 1 ? resizeHeight() : resizeWidth();		// If portraits are set to fit
							}
							
						}
					}
					/*-----End Image Resize-----*/
					
					
					/*-----Resize Functions-----*/
					
					function resizeWidth(minimum){
						if (minimum){	// If minimum height needs to be considered
							if(thisSlide.width() < browserwidth || thisSlide.width() < base.options.min_width ){
								if (thisSlide.width() * ratio >= base.options.min_height){
									thisSlide.width(base.options.min_width);
						    		thisSlide.height(thisSlide.width() * ratio);
						    	}else{
						    		resizeHeight();
						    	}
						    }
						}else{
							if (base.options.min_height >= browserheight && !base.options.fit_landscape){	// If minimum height needs to be considered
								if (browserwidth * ratio >= base.options.min_height || (browserwidth * ratio >= base.options.min_height && ratio <= 1)){	// If resizing would push below minimum height or image is a landscape
									thisSlide.width(browserwidth);
									thisSlide.height(browserwidth * ratio);
								} else if (ratio > 1){		// Else the image is portrait
									thisSlide.height(base.options.min_height);
									thisSlide.width(thisSlide.height() / ratio);
								} else if (thisSlide.width() < browserwidth) {
									thisSlide.width(browserwidth);
						    		thisSlide.height(thisSlide.width() * ratio);
								}
							}else{	// Otherwise, resize as normal
								thisSlide.width(browserwidth);
								thisSlide.height(browserwidth * ratio);
							}
						}
					};
					
					function resizeHeight(minimum){
						if (minimum){	// If minimum height needs to be considered
							if(thisSlide.height() < browserheight){
								if (thisSlide.height() / ratio >= base.options.min_width){
									thisSlide.height(base.options.min_height);
									thisSlide.width(thisSlide.height() / ratio);
								}else{
									resizeWidth(true);
								}
							}
						}else{	// Otherwise, resized as normal
							if (base.options.min_width >= browserwidth){	// If minimum width needs to be considered
								if (browserheight / ratio >= base.options.min_width || ratio > 1){	// If resizing would push below minimum width or image is a portrait
									thisSlide.height(browserheight);
									thisSlide.width(browserheight / ratio);
								} else if (ratio <= 1){		// Else the image is landscape
									thisSlide.width(base.options.min_width);
						    		thisSlide.height(thisSlide.width() * ratio);
								}
							}else{	// Otherwise, resize as normal
								thisSlide.height(browserheight);
								thisSlide.width(browserheight / ratio);
							}
						}
					};
					
					/*-----End Resize Functions-----*/
					
					if (thisSlide.parents('li').hasClass('image-loading')){
						$('.image-loading').removeClass('image-loading');
					}
					
					// Horizontally Center
					if (base.options.horizontal_center){
						$(this).css('left', (browserwidth - $(this).width())/2);
					}
					
					// Vertically Center
					if (base.options.vertical_center){
						$(this).css('top', (browserheight - $(this).height())/2);
					}
					
				});
				
				// Basic image drag and right click protection
				if (base.options.image_protect){
					
					$('img', base.el).bind("contextmenu mousedown",function(){
						return false;
					});
				
				}
				
				return false;
				
			});
			
		};
        
        
        /* Next Slide
		----------------------------*/
		base.nextSlide = function(){
			
			if(vars.in_animation || !api.options.slideshow) return false;		// Abort if currently animating
				else vars.in_animation = true;		// Otherwise set animation marker
				
		    clearInterval(vars.slideshow_interval);	// Stop slideshow
		    
		    var slides = base.options.slides,					// Pull in slides array
				liveslide = base.$el.find('.activeslide');		// Find active slide
				$('.prevslide').removeClass('prevslide');
				liveslide.removeClass('activeslide').addClass('prevslide');	// Remove active class & update previous slide
					
			// Get the slide number of new slide
			vars.current_slide + 1 == base.options.slides.length ? vars.current_slide = 0 : vars.current_slide++;
			
		    var nextslide = $(base.el+' li:eq('+vars.current_slide+')'),
		    	prevslide = base.$el.find('.prevslide');
			
			// If hybrid mode is on drop quality for transition
			if (base.options.performance == 1) base.$el.removeClass('quality').addClass('speed');	
			
			
			/*-----Load Image-----*/
			
			loadSlide = false;
			
			vars.current_slide == base.options.slides.length - 1 ? loadSlide = 0 : loadSlide = vars.current_slide + 1;	// Determine next slide
			
			var targetList = base.el+' li:eq('+loadSlide+')';
			if (!$(targetList).html()){
				
				// If links should open in new window
				var linkTarget = base.options.new_window ? ' target="_blank"' : '';
				
				imageLink = (base.options.slides[loadSlide].url) ? "href='" + base.options.slides[loadSlide].url + "'" : "";	// If link exists, build it
				var img = $('<img src="'+base.options.slides[loadSlide].image+'"/>'); 
				
				img.appendTo(targetList).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading').css('visibility','hidden');
				
				img.load(function(){
					base._origDim($(this));
					base.resizeNow();
				});	// End Load
			};
						
			// Update thumbnails (if enabled)
			if (base.options.thumbnail_navigation == 1){
			
				// Load previous thumbnail
				vars.current_slide - 1 < 0  ? prevThumb = base.options.slides.length - 1 : prevThumb = vars.current_slide - 1;
				$(vars.prev_thumb).html($("<img/>").attr("src", base.options.slides[prevThumb].image));
			
				// Load next thumbnail
				nextThumb = loadSlide;
				$(vars.next_thumb).html($("<img/>").attr("src", base.options.slides[nextThumb].image));
				
			}
			
			
			
			/*-----End Load Image-----*/
			
			
			// Call theme function for before slide transition
			if( typeof theme != 'undefined' && typeof theme.beforeAnimation == "function" ) theme.beforeAnimation('next');
			
			//Update slide markers
			if (base.options.slide_links){
				$('.current-slide').removeClass('current-slide');
				$(vars.slide_list +'> li' ).eq(vars.current_slide).addClass('current-slide');
			}
		    
		    nextslide.css('visibility','hidden').addClass('activeslide');	// Update active slide
		    
	    	switch(base.options.transition){
	    		case 0: case 'none':	// No transition
	    		    nextslide.css('visibility','visible');
	    		    vars.in_animation = false;
	    		    break;
	    		case 1: case 'fade':	// Fade
	    		    nextslide.animate({opacity : 0},0).css('visibility','visible').animate({opacity : 1, avoidTransforms : false}, base.options.transition_speed, function(){ base.afterAnimation(); });
	    		    break;
	    		case 2: case 'slideTop':	// Slide Top
	    		    nextslide.animate({top : -base.$el.height()}, 0 ).css('visibility','visible').animate({ top:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    		    break;
	    		case 3: case 'slideRight':	// Slide Right
	    			nextslide.animate({left : base.$el.width()}, 0 ).css('visibility','visible').animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    			break;
	    		case 4: case 'slideBottom': // Slide Bottom
	    			nextslide.animate({top : base.$el.height()}, 0 ).css('visibility','visible').animate({ top:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    			break;
	    		case 5: case 'slideLeft':  // Slide Left
	    			nextslide.animate({left : -base.$el.width()}, 0 ).css('visibility','visible').animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    			break;
	    		case 6: case 'carouselRight':	// Carousel Right
	    			nextslide.animate({left : base.$el.width()}, 0 ).css('visibility','visible').animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
					liveslide.animate({ left: -base.$el.width(), avoidTransforms : false }, base.options.transition_speed );
	    			break;
	    		case 7: case 'carouselLeft':   // Carousel Left
	    			nextslide.animate({left : -base.$el.width()}, 0 ).css('visibility','visible').animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
					liveslide.animate({ left: base.$el.width(), avoidTransforms : false }, base.options.transition_speed );
	    			break;
	    	}
            if (base.needsResize){
                base.needsResize = false;
                base.resizeNow();
            }
		    return false;	
		};
		
		
		/* Previous Slide
		----------------------------*/
		base.prevSlide = function(){
		
			if(vars.in_animation || !api.options.slideshow) return false;		// Abort if currently animating
				else vars.in_animation = true;		// Otherwise set animation marker
			
			clearInterval(vars.slideshow_interval);	// Stop slideshow
			
			var slides = base.options.slides,					// Pull in slides array
				liveslide = base.$el.find('.activeslide');		// Find active slide
				$('.prevslide').removeClass('prevslide');
				liveslide.removeClass('activeslide').addClass('prevslide');		// Remove active class & update previous slide
			
			// Get current slide number
			vars.current_slide == 0 ?  vars.current_slide = base.options.slides.length - 1 : vars.current_slide-- ;
				
		    var nextslide =  $(base.el+' li:eq('+vars.current_slide+')'),
		    	prevslide =  base.$el.find('.prevslide');
			
			// If hybrid mode is on drop quality for transition
			if (base.options.performance == 1) base.$el.removeClass('quality').addClass('speed');	
			
			
			/*-----Load Image-----*/
			
			loadSlide = false;
			
			vars.current_slide - 1 < 0  ? loadSlide = base.options.slides.length - 1 : loadSlide = vars.current_slide - 1;	// Determine next slide
			var targetList = base.el+' li:eq('+loadSlide+')';
			if (!$(targetList).html()){
				// If links should open in new window
				var linkTarget = base.options.new_window ? ' target="_blank"' : '';
				imageLink = (base.options.slides[loadSlide].url) ? "href='" + base.options.slides[loadSlide].url + "'" : "";	// If link exists, build it
				var img = $('<img src="'+base.options.slides[loadSlide].image+'"/>'); 
				
				img.appendTo(targetList).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading').css('visibility','hidden');
				
				img.load(function(){
					base._origDim($(this));
					base.resizeNow();
				});	// End Load
			};
			
			// Update thumbnails (if enabled)
			if (base.options.thumbnail_navigation == 1){
			
				// Load previous thumbnail
				prevThumb = loadSlide;
				$(vars.prev_thumb).html($("<img/>").attr("src", base.options.slides[prevThumb].image));
				
				// Load next thumbnail
				vars.current_slide == base.options.slides.length - 1 ? nextThumb = 0 : nextThumb = vars.current_slide + 1;
				$(vars.next_thumb).html($("<img/>").attr("src", base.options.slides[nextThumb].image));
			}
			
			/*-----End Load Image-----*/
			
			
			// Call theme function for before slide transition
			if( typeof theme != 'undefined' && typeof theme.beforeAnimation == "function" ) theme.beforeAnimation('prev');
			
			//Update slide markers
			if (base.options.slide_links){
				$('.current-slide').removeClass('current-slide');
				$(vars.slide_list +'> li' ).eq(vars.current_slide).addClass('current-slide');
			}
			
		    nextslide.css('visibility','hidden').addClass('activeslide');	// Update active slide
		    
		    switch(base.options.transition){
	    		case 0: case 'none':	// No transition
	    		    nextslide.css('visibility','visible'); vars.in_animation = false; base.afterAnimation();
	    		    break;
	    		case 1: case 'fade':	// Fade
	    		  	nextslide.animate({opacity : 0},0).css('visibility','visible').animate({opacity : 1, avoidTransforms : false}, base.options.transition_speed, function(){ base.afterAnimation(); });
	    		    break;
	    		case 2: case 'slideTop':	// Slide Top (reverse)
	    		    nextslide.animate({top : base.$el.height()}, 0 ).css('visibility','visible').animate({ top:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    		    break;
	    		case 3: case 'slideRight':	// Slide Right (reverse)
	    			nextslide.animate({left : -base.$el.width()}, 0 ).css('visibility','visible').animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    			break;
	    		case 4: case 'slideBottom': // Slide Bottom (reverse)
	    			nextslide.animate({top : -base.$el.height()}, 0 ).css('visibility','visible').animate({ top:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    			break;
	    		case 5: case 'slideLeft':  // Slide Left (reverse)
	    			nextslide.animate({left : base.$el.width()}, 0 ).css('visibility','visible').animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    			break;
	    		case 6: case 'carouselRight':	// Carousel Right (reverse)
	    			nextslide.animate({left : -base.$el.width()}, 0 ).css('visibility','visible').animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
					liveslide.animate({left : 0}, 0 ).animate({ left: base.$el.width(), avoidTransforms : false}, base.options.transition_speed );
	    			break;
	    		case 7: case 'carouselLeft':   // Carousel Left (reverse)
	    			nextslide.animate({left : base.$el.width()}, 0 ).css('visibility','visible').animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
					liveslide.animate({left : 0}, 0 ).animate({ left: -base.$el.width(), avoidTransforms : false }, base.options.transition_speed );
	    			break;
	    	}
		    return false;	
		};
		
		
		/* Play/Pause Toggle
		----------------------------*/
		base.playToggle = function(){
		
			if (vars.in_animation || !api.options.slideshow) return false;		// Abort if currently animating
			
			if (vars.is_paused){
				
				vars.is_paused = false;
				
				// Call theme function for play
				if( typeof theme != 'undefined' && typeof theme.playToggle == "function" ) theme.playToggle('play');
				
				// Resume slideshow
	        	vars.slideshow_interval = setInterval(base.nextSlide, base.options.slide_interval);
	        	  
        	}else{
        		
        		vars.is_paused = true;
        		
        		// Call theme function for pause
        		if( typeof theme != 'undefined' && typeof theme.playToggle == "function" ) theme.playToggle('pause');
        		
        		// Stop slideshow
        		clearInterval(vars.slideshow_interval);	
       		
       		}
		    
		    return false;
    		
    	};
    	
    	
    	/* Go to specific slide
		----------------------------*/
    	base.goTo = function(targetSlide){
			if (vars.in_animation || !api.options.slideshow) return false;		// Abort if currently animating
			
			var totalSlides = base.options.slides.length;
			
			// If target outside range
			if(targetSlide < 0){
				targetSlide = totalSlides;
			}else if(targetSlide > totalSlides){
				targetSlide = 1;
			}
			targetSlide = totalSlides - targetSlide + 1;
			
			clearInterval(vars.slideshow_interval);	// Stop slideshow, prevent buildup
			
			// Call theme function for goTo trigger
			if (typeof theme != 'undefined' && typeof theme.goTo == "function" ) theme.goTo();
			
			if (vars.current_slide == totalSlides - targetSlide){
				if(!(vars.is_paused)){
					vars.slideshow_interval = setInterval(base.nextSlide, base.options.slide_interval);
				} 
				return false;
			}
			
			// If ahead of current position
			if(totalSlides - targetSlide > vars.current_slide ){
				
				// Adjust for new next slide
				vars.current_slide = totalSlides-targetSlide-1;
				vars.update_images = 'next';
				base._placeSlide(vars.update_images);
				
			//Otherwise it's before current position
			}else if(totalSlides - targetSlide < vars.current_slide){
				
				// Adjust for new prev slide
				vars.current_slide = totalSlides-targetSlide+1;
				vars.update_images = 'prev';
			    base._placeSlide(vars.update_images);
			    
			}
			
			// set active markers
			if (base.options.slide_links){
				$(vars.slide_list +'> .current-slide').removeClass('current-slide');
				$(vars.slide_list +'> li').eq((totalSlides-targetSlide)).addClass('current-slide');
			}
			
			if (base.options.thumb_links){
				$(vars.thumb_list +'> .current-thumb').removeClass('current-thumb');
				$(vars.thumb_list +'> li').eq((totalSlides-targetSlide)).addClass('current-thumb');
			}
			
		};
        
        
        /* Place Slide
		----------------------------*/
        base._placeSlide = function(place){
    			
			// If links should open in new window
			var linkTarget = base.options.new_window ? ' target="_blank"' : '';
			
			loadSlide = false;
			
			if (place == 'next'){
				
				vars.current_slide == base.options.slides.length - 1 ? loadSlide = 0 : loadSlide = vars.current_slide + 1;	// Determine next slide
				
				var targetList = base.el+' li:eq('+loadSlide+')';
				
				if (!$(targetList).html()){
					// If links should open in new window
					var linkTarget = base.options.new_window ? ' target="_blank"' : '';
					
					imageLink = (base.options.slides[loadSlide].url) ? "href='" + base.options.slides[loadSlide].url + "'" : "";	// If link exists, build it
					var img = $('<img src="'+base.options.slides[loadSlide].image+'"/>'); 
					
					img.appendTo(targetList).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading').css('visibility','hidden');
					
					img.load(function(){
						base._origDim($(this));
						base.resizeNow();
					});	// End Load
				};
				
				base.nextSlide();
				
			}else if (place == 'prev'){
			
				vars.current_slide - 1 < 0  ? loadSlide = base.options.slides.length - 1 : loadSlide = vars.current_slide - 1;	// Determine next slide
				
				var targetList = base.el+' li:eq('+loadSlide+')';
				
				if (!$(targetList).html()){
					// If links should open in new window
					var linkTarget = base.options.new_window ? ' target="_blank"' : '';
					
					imageLink = (base.options.slides[loadSlide].url) ? "href='" + base.options.slides[loadSlide].url + "'" : "";	// If link exists, build it
					var img = $('<img src="'+base.options.slides[loadSlide].image+'"/>'); 
					
					img.appendTo(targetList).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading').css('visibility','hidden');
					
					img.load(function(){
						base._origDim($(this));
						base.resizeNow();
					});	// End Load
				};
				base.prevSlide();
			}
			
		};
		
		
		/* Get Original Dimensions
		----------------------------*/
		base._origDim = function(targetSlide){
			targetSlide.data('origWidth', targetSlide.width()).data('origHeight', targetSlide.height());
		};
		
		
		/* After Slide Animation
		----------------------------*/
		base.afterAnimation = function(){
			
			// If hybrid mode is on swap back to higher image quality
			if (base.options.performance == 1){
		    	base.$el.removeClass('speed').addClass('quality');
			}
			
			// Update previous slide
			if (vars.update_images){
				vars.current_slide - 1 < 0  ? setPrev = base.options.slides.length - 1 : setPrev = vars.current_slide-1;
				vars.update_images = false;
				$('.prevslide').removeClass('prevslide');
				$(base.el+' li:eq('+setPrev+')').addClass('prevslide');
			}
			
			vars.in_animation = false;
			
			// Resume slideshow
			if (!vars.is_paused && base.options.slideshow){
				vars.slideshow_interval = setInterval(base.nextSlide, base.options.slide_interval);
				if (base.options.stop_loop && vars.current_slide == base.options.slides.length - 1 ) base.playToggle();
			}
			
			// Call theme function for after slide transition
			if (typeof theme != 'undefined' && typeof theme.afterAnimation == "function" ) theme.afterAnimation();
			
			return false;
		
		};
		
		base.getField = function(field){
			return base.options.slides[vars.current_slide][field];
		};
		
        // Make it go!
        base.init();
	};
	
	
	/* Global Variables
	----------------------------*/
	$.supersized.vars = {
	
		// Elements							
		thumb_tray			:	'#thumb-tray',	// Thumbnail tray
		thumb_list			:	'#thumb-list',	// Thumbnail list
		slide_list          :   '#slide-list',	// Slide link list
		
		// Internal variables
		current_slide			:	0,			// Current slide number
		in_animation 			:	false,		// Prevents animations from stacking
		is_paused 				: 	false,		// Tracks paused on/off
		hover_pause				:	false,		// If slideshow is paused from hover
		slideshow_interval		:	false,		// Stores slideshow timer					
		update_images 			: 	false,		// Trigger to update images after slide jump
		options					:	{}			// Stores assembled options list
		
	};
	
	
	/* Default Options
	----------------------------*/
	$.supersized.defaultOptions = {
    
    	// Functionality
		slideshow               :   1,			// Slideshow on/off
		autoplay				:	1,			// Slideshow starts playing automatically
		start_slide             :   1,			// Start slide (0 is random)
		stop_loop				:	0,			// Stops slideshow on last slide
		random					: 	0,			// Randomize slide order (Ignores start slide)
		slide_interval          :   5000,		// Length between transitions
		transition              :   1, 			// 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
		transition_speed		:	750,		// Speed of transition
		new_window				:	1,			// Image links open in new window/tab
		pause_hover             :   0,			// Pause slideshow on hover
		keyboard_nav            :   1,			// Keyboard navigation on/off
		performance				:	1,			// 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed //  (Only works for Firefox/IE, not Webkit)
		image_protect			:	1,			// Disables image dragging and right click with Javascript
												   
		// Size & Position
		fit_always				:	0,			// Image will never exceed browser width or height (Ignores min. dimensions)
		fit_landscape			:   0,			// Landscape images will not exceed browser width
		fit_portrait         	:   1,			// Portrait images will not exceed browser height  			   
		min_width		        :   0,			// Min width allowed (in pixels)
		min_height		        :   0,			// Min height allowed (in pixels)
		horizontal_center       :   1,			// Horizontally center background
		vertical_center         :   1,			// Vertically center background
		
												   
		// Components							
		slide_links				:	1,			// Individual links for each slide	
		thumb_links				:	1,			// Individual thumb links for each slide
		thumbnail_navigation    :   0			// Thumbnail navigation
    	
    };
    
    $.fn.supersized = function(options){
        return this.each(function(){
            (new $.supersized(options));
        });
    };
		
})(jQuery);

;
/*

	Supersized - Fullscreen Slideshow jQuery Plugin
	Version : 3.2.4
	Theme 	: Shutter 1.1
	
	Site	: www.buildinternet.com/project/supersized
	Author	: Sam Dunn
	Company : One Mighty Roar (www.onemightyroar.com)
	License : MIT License / GPL License

*/

(function(a){theme={_init:function(){if(api.options.slide_links){a(vars.slide_list).css("margin-left",-a(vars.slide_list).width()/2)}if(api.options.autoplay){if(api.options.progress_bar){theme.progressBar()}}else{if(a(vars.play_button).attr("src")){a(vars.play_button).attr("src",vars.image_path+"play.png")}if(api.options.progress_bar){a(vars.progress_bar).stop().animate({left:-a(window).width()},0)}}a(vars.thumb_tray).animate({bottom:-a(vars.thumb_tray).height()},0);a(vars.tray_button).toggle(function(){a(vars.thumb_tray).stop().animate({bottom:0,avoidTransforms:true},300);if(a(vars.tray_arrow).attr("src")){a(vars.tray_arrow).attr("src",vars.image_path+"button-tray-down.png")}return false},function(){a(vars.thumb_tray).stop().animate({bottom:-a(vars.thumb_tray).height(),avoidTransforms:true},300);if(a(vars.tray_arrow).attr("src")){a(vars.tray_arrow).attr("src",vars.image_path+"button-tray-up.png")}return false});a(vars.thumb_list).width(a("> li",vars.thumb_list).length*a("> li",vars.thumb_list).outerWidth(true));if(a(vars.slide_total).length){a(vars.slide_total).html(api.options.slides.length)}if(api.options.thumb_links){if(a(vars.thumb_list).width()<=a(vars.thumb_tray).width()){a(vars.thumb_back+","+vars.thumb_forward).fadeOut(0)}vars.thumb_interval=Math.floor(a(vars.thumb_tray).width()/a("> li",vars.thumb_list).outerWidth(true))*a("> li",vars.thumb_list).outerWidth(true);vars.thumb_page=0;a(vars.thumb_forward).click(function(){if(vars.thumb_page-vars.thumb_interval<=-a(vars.thumb_list).width()){vars.thumb_page=0;a(vars.thumb_list).stop().animate({left:vars.thumb_page},{duration:500,easing:"easeOutExpo"})}else{vars.thumb_page=vars.thumb_page-vars.thumb_interval;a(vars.thumb_list).stop().animate({left:vars.thumb_page},{duration:500,easing:"easeOutExpo"})}});a(vars.thumb_back).click(function(){if(vars.thumb_page+vars.thumb_interval>0){vars.thumb_page=Math.floor(a(vars.thumb_list).width()/vars.thumb_interval)*-vars.thumb_interval;if(a(vars.thumb_list).width()<=-vars.thumb_page){vars.thumb_page=vars.thumb_page+vars.thumb_interval}a(vars.thumb_list).stop().animate({left:vars.thumb_page},{duration:500,easing:"easeOutExpo"})}else{vars.thumb_page=vars.thumb_page+vars.thumb_interval;a(vars.thumb_list).stop().animate({left:vars.thumb_page},{duration:500,easing:"easeOutExpo"})}})}a(vars.next_slide).click(function(){api.nextSlide()});a(vars.prev_slide).click(function(){api.prevSlide()});if(jQuery.support.opacity){a(vars.prev_slide+","+vars.next_slide).mouseover(function(){a(this).stop().animate({opacity:1},100)}).mouseout(function(){a(this).stop().animate({opacity:0.6},100)})}if(api.options.thumbnail_navigation){a(vars.next_thumb).click(function(){api.nextSlide()});a(vars.prev_thumb).click(function(){api.prevSlide()})}a(vars.play_button).click(function(){api.playToggle()});if(api.options.mouse_scrub){a(vars.thumb_tray).mousemove(function(f){var c=a(vars.thumb_tray).width(),g=a(vars.thumb_list).width();if(g>c){var b=1,d=f.pageX-b;if(d>10||d<-10){b=f.pageX;newX=(c-g)*(f.pageX/c);d=parseInt(Math.abs(parseInt(a(vars.thumb_list).css("left"))-newX)).toFixed(0);a(vars.thumb_list).stop().animate({left:newX},{duration:d*3,easing:"easeOutExpo"})}}})}a(window).resize(function(){if(api.options.progress_bar&&!vars.in_animation){if(vars.slideshow_interval){clearInterval(vars.slideshow_interval)}if(api.options.slides.length-1>0){clearInterval(vars.slideshow_interval)}a(vars.progress_bar).stop().animate({left:-a(window).width()},0);if(!vars.progressDelay&&api.options.slideshow){vars.progressDelay=setTimeout(function(){if(!vars.is_paused){theme.progressBar();vars.slideshow_interval=setInterval(api.nextSlide,api.options.slide_interval)}vars.progressDelay=false},1000)}}if(api.options.thumb_links&&vars.thumb_tray.length){vars.thumb_page=0;vars.thumb_interval=Math.floor(a(vars.thumb_tray).width()/a("> li",vars.thumb_list).outerWidth(true))*a("> li",vars.thumb_list).outerWidth(true);if(a(vars.thumb_list).width()>a(vars.thumb_tray).width()){a(vars.thumb_back+","+vars.thumb_forward).fadeIn("fast");a(vars.thumb_list).stop().animate({left:0},200)}else{a(vars.thumb_back+","+vars.thumb_forward).fadeOut("fast")}}})},goTo:function(b){if(api.options.progress_bar&&!vars.is_paused){a(vars.progress_bar).stop().animate({left:-a(window).width()},0);theme.progressBar()}},playToggle:function(b){if(b=="play"){if(a(vars.play_button).attr("src")){a(vars.play_button).attr("src",vars.image_path+"pause.png")}if(api.options.progress_bar&&!vars.is_paused){theme.progressBar()}}else{if(b=="pause"){if(a(vars.play_button).attr("src")){a(vars.play_button).attr("src",vars.image_path+"play.png")}if(api.options.progress_bar&&vars.is_paused){a(vars.progress_bar).stop().animate({left:-a(window).width()},0)}}}},beforeAnimation:function(b){if(api.options.progress_bar&&!vars.is_paused){a(vars.progress_bar).stop().animate({left:-a(window).width()},0)}if(a(vars.slide_caption).length){(api.getField("title"))?a(vars.slide_caption).html(api.getField("title")):a(vars.slide_caption).html("")}if(vars.slide_current.length){a(vars.slide_current).html(vars.current_slide+1)}if(api.options.thumb_links){a(".current-thumb").removeClass("current-thumb");a("li",vars.thumb_list).eq(vars.current_slide).addClass("current-thumb");if(a(vars.thumb_list).width()>a(vars.thumb_tray).width()){if(b=="next"){if(vars.current_slide==0){vars.thumb_page=0;a(vars.thumb_list).stop().animate({left:vars.thumb_page},{duration:500,easing:"easeOutExpo"})}else{if(a(".current-thumb").offset().left-a(vars.thumb_tray).offset().left>=vars.thumb_interval){vars.thumb_page=vars.thumb_page-vars.thumb_interval;a(vars.thumb_list).stop().animate({left:vars.thumb_page},{duration:500,easing:"easeOutExpo"})}}}else{if(b=="prev"){if(vars.current_slide==api.options.slides.length-1){vars.thumb_page=Math.floor(a(vars.thumb_list).width()/vars.thumb_interval)*-vars.thumb_interval;if(a(vars.thumb_list).width()<=-vars.thumb_page){vars.thumb_page=vars.thumb_page+vars.thumb_interval}a(vars.thumb_list).stop().animate({left:vars.thumb_page},{duration:500,easing:"easeOutExpo"})}else{if(a(".current-thumb").offset().left-a(vars.thumb_tray).offset().left<0){if(vars.thumb_page+vars.thumb_interval>0){return false}vars.thumb_page=vars.thumb_page+vars.thumb_interval;a(vars.thumb_list).stop().animate({left:vars.thumb_page},{duration:500,easing:"easeOutExpo"})}}}}}}},afterAnimation:function(){if(api.options.progress_bar&&!vars.is_paused){theme.progressBar()}},progressBar:function(){a(vars.progress_bar).stop().animate({left:-a(window).width()},0).animate({left:0},api.options.slide_interval)}};a.supersized.themeVars={progress_delay:false,thumb_page:false,thumb_interval:false,image_path:"img/",play_button:"#pauseplay",next_slide:"#nextslide",prev_slide:"#prevslide",next_thumb:"#nextthumb",prev_thumb:"#prevthumb",slide_caption:"#slidecaption",slide_current:".slidenumber",slide_total:".totalslides",slide_list:"#slide-list",thumb_tray:"#thumb-tray",thumb_list:"#thumb-list",thumb_forward:"#thumb-forward",thumb_back:"#thumb-back",tray_arrow:"#tray-arrow",tray_button:"#tray-button",progress_bar:"#progress-bar"};a.supersized.themeOptions={progress_bar:1,mouse_scrub:0}})(jQuery);;
/**
 * @author alexander.farkas
 * @version 1.4.1
 * Jquery plugin that replaces checkboxes and radio buttons to easy to stylize html elements
 * http://www.protofunc.com/scripts/jquery/checkbox-radiobutton/
 */
(function($){
	var baseClasses = /ui-checkbox|ui-radio/;
    $.widget('ui.checkBox', {
		options: {
	        hideInput: true,
			addVisualElement: true,
			addLabel: true,
			_delegated: false
	    },
        _create: function(){
            var that = this,
				opts = this.options
			;

			if(!this.element.is(':radio,:checkbox')){
				if($.nodeName(this.element[0], 'input')){return false;}
				this._addDelegate();
				this.updateContainer();
				return false;
			}
            this.labels = $([]);

            this.checkedStatus = false;
			this.disabledStatus = false;
			this.hoverStatus = false;

            this.radio = (this.element.is(':radio'));

            this.visualElement = $([]);
            if (opts.hideInput) {
				this.element
					.addClass('ui-helper-hidden-accessible')
				;
				if(opts.addVisualElement){
					this.visualElement = $('<span />')
						.addClass(this.radio ? 'ui-radio' : 'ui-checkbox')
					;
					this.element.after(this.visualElement[0]);
				}
            }

			if(opts.addLabel){
				this.labels = $('label[for=' + this.element.attr('id') + ']')
					.addClass(this.radio ? 'ui-radio' : 'ui-checkbox')
				;
			}
			if(!opts._delegated){
				this._addEvents();
			}
			this.initialized = true;
            this.reflectUI({type: 'initialReflect'});
			return undefined;
        },
		updateContainer: function(){
			if(!this.element.is(':radio,:checkbox') && !$.nodeName(this.element[0], 'input')){
				$('input', this.element[0])
					.filter(function(){
						return !($.data(this, 'checkBox'));
					})
					.checkBox($.extend({}, this.options, {_delegated: true}))
				;
			}
		},
		_addDelegate: function(){
			var opts 		= this.options,

				toggleHover = function(e, that){
					if(!that){return;}
					that.hover = !!(e.type == 'focus' || e.type == 'mouseenter' || e.type == 'focusin' || e.type == 'mouseover');
					that._changeStateClassChain.call(that);
					return undefined;
				}
			;


			this.element
				.bind('click', function(e){
					if(!$.nodeName(e.target, 'input')){return;}
					var inst = ($.data(e.target) || {}).checkBox;
					if(!inst){return;}
					inst.reflectUI.call(inst, e.target, e);
				})
				.bind('focusin.checkBox focusout.checkBox', function(e){
					if(!$.nodeName(e.target, 'input')){return;}
					var inst = ($.data(e.target) || {}).checkBox;
					toggleHover(e, inst);
				})
			;

			if (opts.hideInput){
				this.element
					.bind('usermode', function(e){
						if(!e.enabled){return;}
						$('input', this).each(function(){
		                    var inst = ($.data(this) || {}).checkBox;
							(inst && inst.destroy.call(inst, true));
						});
	                })
				;
            }

			if(opts.addVisualElement){
				this.element
					.bind('mouseover.checkBox mouseout.checkBox', function(e){
						if(!$.nodeName(e.target, 'span')){return;}
						var inst = ( $.data($(e.target).prev()[0]) || {} ).checkBox;
						toggleHover(e, inst);
					})
					.bind('click.checkBox', function(e){
						if(!$.nodeName(e.target, 'span') || !baseClasses.test( e.target.className || '' )){return;}
						$(e.target).prev()[0].click();
						return false;
					})
				;
			}
			if(opts.addLabel){
				this.element
					.delegate('label.ui-radio, label.ui-checkbox', 'mouseenter.checkBox mouseleave.checkBox', function(e){
						var inst = ( $.data(document.getElementById( $(this).attr('for') )) || {} ).checkBox;
						toggleHover( e, inst );
					});
			}

		},
		_addEvents: function(){
			var that 		= this,

				opts 		= this.options,

				toggleHover = function(e){
					if(that.disabledStatus){
						return false;
					}
					that.hover = (e.type == 'focus' || e.type == 'mouseenter');
					that._changeStateClassChain();
					return undefined;
				}
			;

			this.element
				.bind('click.checkBox', $.proxy(this, 'reflectUI'))
				.bind('focus.checkBox blur.checkBox', toggleHover)
			;
			if (opts.hideInput){
				this.element
					.bind('usermode', function(e){
	                    (e.enabled &&
	                        that.destroy.call(that, true));
	                })
				;
            }
			if(opts.addVisualElement){
					this.visualElement
						.bind('mouseenter.checkBox mouseleave.checkBox', toggleHover)
						.bind('click.checkBox', function(e){
							that.element[0].click();
							return false;
						})
					;
				}
			if(opts.addLabel){
				this.labels.bind('mouseenter.checkBox mouseleave.checkBox', toggleHover);
			}
		},
		_changeStateClassChain: function(){
			var allElements = this.labels.add(this.visualElement),
				stateClass 	= '',
				baseClass 	= 'ui-'+((this.radio) ? 'radio' : 'checkbox')
			;

			if(this.checkedStatus){
				stateClass += '-checked';
				allElements.addClass(baseClass+'-checked');
			} else {
				allElements.removeClass(baseClass+'-checked');
			}

			if(this.disabledStatus){
				stateClass += '-disabled';
				allElements.addClass(baseClass+'-disabled');
			} else {
				allElements.removeClass(baseClass+'-disabled');
			}
			if(this.hover){
				stateClass += '-hover';
				allElements.addClass(baseClass+'-hover');
			} else {
				allElements.removeClass(baseClass+'-hover');
			}

			baseClass += '-state';
			if(stateClass){
				stateClass = baseClass + stateClass;
			}

			function switchStateClass(){
				var classes = this.className.split(' '),
					found = false;
				$.each(classes, function(i, classN){
					if(classN.indexOf(baseClass) === 0){
						found = true;
						classes[i] = stateClass;
						return false;
					}
					return undefined;
				});
				if(!found){
					classes.push(stateClass);
				}
				this.className = classes.join(' ');
			}

			this.labels.each(switchStateClass);
			this.visualElement.each(switchStateClass);
		},
        destroy: function(onlyCss){
            this.element.removeClass('ui-helper-hidden-accessible');
			this.visualElement.addClass('ui-helper-hidden');
            if (!onlyCss) {
                var o = this.options;
                this.element.unbind('.checkBox');
				this.visualElement.remove();
                this.labels
					.unbind('.checkBox')
					.removeClass('ui-state-hover ui-state-checked ui-state-disabled')
				;
            }
        },

        disable: function(){
            this.element[0].disabled = true;
            this.reflectUI({type: 'manuallyDisabled'});
        },

        enable: function(){
            this.element[0].disabled = false;
            this.reflectUI({type: 'manuallyenabled'});
        },

        toggle: function(e){
            this.changeCheckStatus((this.element.is(':checked')) ? false : true, e);
        },

        changeCheckStatus: function(status, e){
            if(e && e.type == 'click' && this.element[0].disabled){
				return false;
			}
			this.element.attr({'checked': status});
            this.reflectUI(e || {
                type: 'changeCheckStatus'
            });
			return undefined;
        },

        propagate: function(n, e, _noGroupReflect){
			if(!e || e.type != 'initialReflect'){
				if (this.radio && !_noGroupReflect) {
					//dynamic
	                $(document.getElementsByName(this.element.attr('name')))
						.checkBox('reflectUI', e, true);
	            }
	            return this._trigger(n, e, {
	                options: this.options,
	                checked: this.checkedStatus,
	                labels: this.labels,
					disabled: this.disabledStatus
	            });
			}
			return undefined;
        },
		
        reflectUI: function(e){

            var oldChecked 			= this.checkedStatus,
				oldDisabledStatus 	= this.disabledStatus
			;

			this.disabledStatus = this.element.is(':disabled');
			this.checkedStatus = this.element.is(':checked');

			if (this.disabledStatus != oldDisabledStatus || this.checkedStatus !== oldChecked) {
				this._changeStateClassChain();

				(this.disabledStatus != oldDisabledStatus &&
					this.propagate('disabledChange', e));

				(this.checkedStatus !== oldChecked &&
					this.propagate('change', e));
			}

        }
    });
})(jQuery);
;
﻿/*****************************************************************************
jQuery Placeholder 1.1.1

Copyright (c) 2010 Michael J. Ryan (http://tracker1.info/)

Dual licensed under the MIT and GPL licenses:
	http://www.opensource.org/licenses/mit-license.php
	http://www.gnu.org/licenses/gpl.html

------------------------------------------------------------------------------

Sets up a watermark for inputted fields... this will create a LABEL.watermark 
tag immediately following the input tag, the positioning will be set absolute, 
and it will be positioned to match the input tag.

To activate on all tags with a 'data-watermark' attribute:

	$('input[placeholder],textarea[placeholder]').placeholder();


To style the tags as appropriate (you'll want to make sure the font matches):

	label.placeholder {
		cursor: text;				<--- display a cursor to match the text input

		padding: 4px 4px 4px 4px;   <--- this should match the border+padding 
											for the input field(s)
		color: #999999;				<--- this will display as faded
	}

You'll also want to have the color set for browsers with native support
	input:placeholder, textarea:placeholder {
		color: #999999;
	}
	input::-webkit-input-placeholder, textarea::-webkit-input-placeholder {
		color: #999999;
	}

------------------------------------------------------------------------------

Thanks to...
	http://www.alistapart.com/articles/makingcompactformsmoreaccessible
	http://plugins.jquery.com/project/overlabel

	This works similar to the overlabel, but creates the actual label tag
	based on a data-watermark attribute on the input tag, instead of 
	relying on the markup to provide it.

*****************************************************************************/
(function($){
	
	var ph = "PLACEHOLDER-INPUT";
	var phl = "PLACEHOLDER-LABEL";
	var boundEvents = false;
	var default_options = {
		labelClass: 'placeholder'
	};
	
	//check for native support for placeholder attribute, if so stub methods and return
	var input = document.createElement("input");
	if ('placeholder' in input) {
		$.fn.placeholder = $.fn.unplaceholder = function(){}; //empty function
		delete input; //cleanup IE memory
		return;
	};
	delete input;

	$.fn.placeholder = function(options) {
		bindEvents();

		var opts = $.extend(default_options, options)

		this.each(function(){
			var rnd=Math.random().toString(32).replace(/\./,'')
				,input=$(this)
				,label=$('<label style="position:absolute;display:none;top:0;left:0;"></label>');

			if (!input.attr('placeholder') || input.data(ph) === ph) return; //already watermarked

			//make sure the input tag has an ID assigned, if not, assign one.
			if (!input.attr('id')) input.attr('id') = 'input_' + rnd;

			label	.attr('id',input.attr('id') + "_placeholder")
					.data(ph, '#' + input.attr('id'))	//reference to the input tag
					.attr('for',input.attr('id'))
					.addClass(opts.labelClass)
					.addClass(opts.labelClass + '-for-' + this.tagName.toLowerCase()) //ex: watermark-for-textarea
					.addClass(phl)
					.text(input.attr('placeholder'));

			input
				.data(phl, '#' + label.attr('id'))	//set a reference to the label
				.data(ph,ph)		//set that the field is watermarked
				.addClass(ph)		//add the watermark class
				.after(label);		//add the label field to the page

			//setup overlay
			itemIn.call(this);
			itemOut.call(this);
		});
	};

	$.fn.unplaceholder = function(){
		this.each(function(){
			var	input=$(this),
				label=$(input.data(phl));

			if (input.data(ph) !== ph) return;
				
			label.remove();
			input.removeData(ph).removeData(phl).removeClass(ph);
		});
	};


	function bindEvents() {
		if (boundEvents) return;

		//prepare live bindings if not already done.
		$('.' + ph)
			.live('click',itemIn)
			.live('focusin',itemIn)
			.live('focusout',itemOut);
		bound = true;

		boundEvents = true;
	};

	function itemIn() {
		var input = $(this)
			,label = $(input.data(phl));

		label.css('display', 'none');
	};

	function itemOut() {
		var that = this;

		//use timeout to let other validators/formatters directly bound to blur/focusout work first
		setTimeout(function(){
			var input = $(that);
			$(input.data(phl))
				.css('top', input.position().top + 'px')
				.css('left', input.position().left + 'px')
				.css('display', !!input.val() ? 'none' : 'block');
		}, 200);
	};

}(jQuery));;
 /*
 * jQuery UI selectmenu
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 * https://github.com/fnagel/jquery-ui/wiki/Selectmenu
 */

(function($) {

$.widget("ui.selectmenu", {
	getter: "value",
	version: "1.8",
	eventPrefix: "selectmenu",
	options: {
		transferClasses: true,
		typeAhead: "sequential",
		style: 'dropdown',
		positionOptions: {
			my: "left top",
			at: "left bottom",
			offset: null
		},
		width: null, 
		menuWidth: null, 
		handleWidth: 26,
		maxHeight: null,
		icons: null, 
		format: null,
		bgImage: function() {},
		wrapperElement: ""
	},

	_create: function() {
		var self = this, o = this.options;

		// set a default id value, generate a new random one if not set by developer
		var selectmenuId = this.element.attr('id') || 'ui-selectmenu-' + Math.random().toString(16).slice(2, 10);

		// quick array of button and menu id's
		this.ids = [ selectmenuId + '-button', selectmenuId + '-menu' ];

		// define safe mouseup for future toggling
		this._safemouseup = true;
		
		// FIXME temp workaround for IE
		if ($.browser.msie) o.typeAhead = "";

		// create menu button wrapper
		this.newelement = $('<a class="' + this.widgetBaseClass + ' ui-widget ui-state-default ui-corner-all" id="' + this.ids[0] + '" role="button" href="#" tabindex="0" aria-haspopup="true" aria-owns="' + this.ids[1] + '"></a>')
			.insertAfter(this.element);
		this.newelement.wrap(o.wrapperElement);

		// transfer tabindex
		var tabindex = this.element.attr('tabindex');
		if (tabindex) {
			this.newelement.attr('tabindex', tabindex);
		}

		// save reference to select in data for ease in calling methods
		this.newelement.data('selectelement', this.element);
		
		// menu icon
		this.selectmenuIcon = $('<span class="' + this.widgetBaseClass + '-icon ui-icon"></span>')
			.prependTo(this.newelement);
			
		// append status span to button
		this.newelement.prepend('<span class="' + self.widgetBaseClass + '-status" />');
			
		// make associated form label trigger focus
		$('label[for="' + this.element.attr('id') + '"]')
			.attr('for', this.ids[0])
			.bind('click.selectmenu', function() {
				self.newelement[0].focus();
				return false;
			});	
			
		// click toggle for menu visibility
		this.newelement
			.bind('mousedown.selectmenu', function(event) {
				self._toggle(event, true);
				// make sure a click won't open/close instantly
				if (o.style == "popup") {
					self._safemouseup = false;
					setTimeout(function() { self._safemouseup = true; }, 300);
				}
				return false;
			})
			.bind('click.selectmenu', function() {
				return false;
			})
			.bind("keydown.selectmenu", function(event) {
				var ret = false;
				switch (event.keyCode) {
					case $.ui.keyCode.ENTER:
						ret = true;
						break;
					case $.ui.keyCode.SPACE:
						self._toggle(event);	
						break;
					case $.ui.keyCode.UP:
						if (event.altKey) {
							self.open(event);
						} else {
							self._moveSelection(-1);
						}
						break;
					case $.ui.keyCode.DOWN:
						if (event.altKey) {
							self.open(event);
						} else {
							self._moveSelection(1);
						}
						break;
					case $.ui.keyCode.LEFT:
						self._moveSelection(-1);
						break;
					case $.ui.keyCode.RIGHT:
						self._moveSelection(1);
						break;
					case $.ui.keyCode.TAB:
						ret = true;
						break;
					default:
						ret = true;
						self._typeAhead(event.keyCode, 'mouseup');
						break;	
				}
				return ret;
			})
			.bind('mouseover.selectmenu focus.selectmenu', function() { 
				if (!o.disabled) {
					$(this).addClass(self.widgetBaseClass + '-focus ui-state-hover');
				}
			})
			.bind('mouseout.selectmenu blur.selectmenu', function() {
				if (!o.disabled) {
					$(this).removeClass(self.widgetBaseClass + '-focus ui-state-hover');
				}
			});

		// document click closes menu
		$(document).bind("mousedown.selectmenu", function(event) {
			self.close(event);
		});

		// change event on original selectmenu
		this.element
			.bind("click.selectmenu", function() {
				self._refreshValue();
			})
			// FIXME: newelement can be null under unclear circumstances in IE8 
			// TODO not sure if this is still a problem (fnagel 20.03.11)
			.bind("focus.selectmenu", function() {
				if (self.newelement) {
					self.newelement[0].focus();
				}
			});

		// original selectmenu width
		var selectWidth = this.element.width();

		// set menu button width
		this.newelement.width(o.width ? o.width : selectWidth);

		// hide original selectmenu element
		this.element.hide();		

		// create menu portion, append to body
		this.list = $('<ul class="' + self.widgetBaseClass + '-menu ui-widget ui-widget-content" aria-hidden="true" role="listbox" aria-labelledby="' + this.ids[0] + '" id="' + this.ids[1] + '"></ul>').appendTo('body');
		this.list.wrap(o.wrapperElement);				

		// transfer menu click to menu button
		this.list
			.bind("keydown.selectmenu", function(event) {
				var ret = false;
				switch (event.keyCode) {
					case $.ui.keyCode.UP:
						if (event.altKey) {
							self.close(event, true);
						} else {
							self._moveFocus(-1);
						}
						break;
					case $.ui.keyCode.DOWN:
						if (event.altKey) {
							self.close(event, true);
						} else {
							self._moveFocus(1);
						}
						break;	
					case $.ui.keyCode.LEFT:
						self._moveFocus(-1);
						break;
					case $.ui.keyCode.RIGHT:
						self._moveFocus(1);
						break;	
					case $.ui.keyCode.HOME:
						self._moveFocus(':first');
						break;		
					case $.ui.keyCode.PAGE_UP:
						self._scrollPage('up');
						break;	
					case $.ui.keyCode.PAGE_DOWN:
						self._scrollPage('down');
						break;
					case $.ui.keyCode.END:
						self._moveFocus(':last');
						break;		
					case $.ui.keyCode.ENTER:
					case $.ui.keyCode.SPACE:
						self.close(event, true);
						$(event.target).parents('li:eq(0)').trigger('mouseup');
						break;		
					case $.ui.keyCode.TAB:
						ret = true;
						self.close(event, true);
						$(event.target).parents('li:eq(0)').trigger('mouseup');
						break;	
					case $.ui.keyCode.ESCAPE:
						self.close(event, true);
						break;
					default:
						ret = true;	
						self._typeAhead(event.keyCode,'focus');					
						break;	
				}
				return ret;
			});			
		
		// needed when window is resized
		$(window).bind( "resize.selectmenu", $.proxy( self._refreshPosition, this ) );
	},

	_init: function() {
		var self = this, o = this.options;
		
		// serialize selectmenu element options	
		var selectOptionData = [];
		this.element
			.find('option')
			.each(function() {
				selectOptionData.push({
					value: $(this).attr('value'),
					text: self._formatText($(this).text()),
					selected: $(this).attr('selected'),
					disabled: $(this).attr('disabled'),
					classes: $(this).attr('class'),
					typeahead: $(this).attr('typeahead'),
					parentOptGroup: $(this).parent('optgroup'),
					bgImage: o.bgImage.call($(this))
				});
			});		
				
		// active state class is only used in popup style
		var activeClass = (self.options.style == "popup") ? " ui-state-active" : "";

		// empty list so we can refresh the selectmenu via selectmenu()
		this.list.html("");

		// write li's
		for (var i = 0; i < selectOptionData.length; i++) {
				var thisLi = $('<li role="presentation"' + (selectOptionData[i].disabled ? ' class="' + this.namespace + '-state-disabled' + '"' : '' ) + '><a href="#" tabindex="-1" role="option"' + (selectOptionData[i].disabled ? ' aria-disabled="true"' : '' ) + ' aria-selected="false"' + (selectOptionData[i].typeahead ? ' typeahead="' + selectOptionData[i].typeahead + '"' : '' ) + '>'+ selectOptionData[i].text +'</a></li>')
				.data('index', i)
				.addClass(selectOptionData[i].classes)
				.data('optionClasses', selectOptionData[i].classes || '')
				.bind("mouseup.selectmenu", function(event) {
					if (self._safemouseup && !self._disabled(event.currentTarget) && !self._disabled($( event.currentTarget ).parents( "ul>li." + self.widgetBaseClass + "-group " )) ) {
						var changed = $(this).data('index') != self._selectedIndex();
						self.index($(this).data('index'));
						self.select(event);
						if (changed) {
							self.change(event);
						}
						self.close(event, true);
					}
					return false;
				})
				.bind("click.selectmenu", function() {
					return false;
				})
				.bind('mouseover.selectmenu focus.selectmenu', function(e) {
					// no hover if diabled
					if (!$(e.currentTarget).hasClass(self.namespace + '-state-disabled')) {
						self._selectedOptionLi().addClass(activeClass); 
						self._focusedOptionLi().removeClass(self.widgetBaseClass + '-item-focus ui-state-hover'); 
						$(this).removeClass('ui-state-active').addClass(self.widgetBaseClass + '-item-focus ui-state-hover'); 
					}
				})
				.bind('mouseout.selectmenu blur.selectmenu', function() { 
					if ($(this).is(self._selectedOptionLi().selector)) {
						$(this).addClass(activeClass);
					}
					$(this).removeClass(self.widgetBaseClass + '-item-focus ui-state-hover');
				});

			// optgroup or not...
			if ( selectOptionData[i].parentOptGroup.length ) {
				var optGroupName = self.widgetBaseClass + '-group-' + this.element.find( 'optgroup' ).index( selectOptionData[i].parentOptGroup );
				if (this.list.find( 'li.' + optGroupName ).length ) {
					this.list.find( 'li.' + optGroupName + ':last ul' ).append( thisLi );
				} else {
					$(' <li role="presentation" class="' + self.widgetBaseClass + '-group ' + optGroupName + (selectOptionData[i].parentOptGroup.attr("disabled") ? ' ' + this.namespace + '-state-disabled" aria-disabled="true"' : '"' ) + '><span class="' + self.widgetBaseClass + '-group-label">' + selectOptionData[i].parentOptGroup.attr('label') + '</span><ul></ul></li> ')
						.appendTo( this.list )
						.find( 'ul' )
						.append( thisLi );
				}
			} else {
				thisLi.appendTo(this.list);
			}
			
			// this allows for using the scrollbar in an overflowed list
			this.list.bind('mousedown.selectmenu mouseup.selectmenu', function() { return false; });
			
			// append icon if option is specified
			if (o.icons) {
				for (var j in o.icons) {
					if (thisLi.is(o.icons[j].find)) {
						thisLi
							.data('optionClasses', selectOptionData[i].classes + ' ' + self.widgetBaseClass + '-hasIcon')
							.addClass(self.widgetBaseClass + '-hasIcon');
						var iconClass = o.icons[j].icon || "";						
						thisLi
							.find('a:eq(0)')
							.prepend('<span class="' + self.widgetBaseClass + '-item-icon ui-icon ' + iconClass + '"></span>');
						if (selectOptionData[i].bgImage) {
							thisLi.find('span').css('background-image', selectOptionData[i].bgImage);
						}
					}
				}
			}
		}	
				
		// we need to set and unset the CSS classes for dropdown and popup style
		var isDropDown = (o.style == 'dropdown');
		this.newelement
			.toggleClass(self.widgetBaseClass + "-dropdown", isDropDown)
			.toggleClass(self.widgetBaseClass + "-popup", !isDropDown);
		this.list
			.toggleClass(self.widgetBaseClass + "-menu-dropdown ui-corner-bottom", isDropDown)
			.toggleClass(self.widgetBaseClass + "-menu-popup ui-corner-all", !isDropDown)
			// add corners to top and bottom menu items
			.find('li:first')
			.toggleClass("ui-corner-top", !isDropDown)
			.end().find('li:last')
			.addClass("ui-corner-bottom");
		this.selectmenuIcon
			.toggleClass('ui-icon-triangle-1-s', isDropDown)
			.toggleClass('ui-icon-triangle-2-n-s', !isDropDown);

		// transfer classes to selectmenu and list
		if (o.transferClasses) {
			var transferClasses = this.element.attr('class') || '';
			this.newelement.add(this.list).addClass(transferClasses);
		}

		// original selectmenu width
		var selectWidth = this.element.width();

		// set menu width to either menuWidth option value, width option value, or select width 
		if (o.style == 'dropdown') { 
			this.list.width(o.menuWidth ? o.menuWidth : (o.width ? o.width : selectWidth)); 
		} else { 
			this.list.width(o.menuWidth ? o.menuWidth : (o.width ? o.width - o.handleWidth : selectWidth - o.handleWidth)); 
		}

		// calculate default max height
		if (o.maxHeight) {
			// set max height from option 
			if (o.maxHeight < this.list.height()) {
				this.list.height(o.maxHeight);
			}
		} else {
			if (!o.format && ($(window).height() / 3) < this.list.height()) {
				o.maxHeight = $(window).height() / 3;
				this.list.height(o.maxHeight);
			}
		}

		// save reference to actionable li's (not group label li's)
		this._optionLis = this.list.find('li:not(.' + self.widgetBaseClass + '-group)');
						
		// transfer disabled state
		if (this.element.attr('disabled') === true) {
			this.disable();
		}

		// update value
		this.index(this._selectedIndex());		

		// needed when selectmenu is placed at the very bottom / top of the page
		window.setTimeout(function() {
			self._refreshPosition();
		}, 200);
	},

	destroy: function() {
		this.element.removeData( this.widgetName )
			.removeClass( this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled' )
			.removeAttr( 'aria-disabled' )
			.unbind( ".selectmenu" );
			
		$( window ).unbind( ".selectmenu" );
		$( document ).unbind( ".selectmenu" );
	
		// unbind click on label, reset its for attr
		$( 'label[for=' + this.newelement.attr('id') + ']' )
			.attr( 'for', this.element.attr( 'id' ) )
			.unbind( '.selectmenu' );
		
		if ( this.options.wrapperElement ) {
			this.newelement.find( this.options.wrapperElement ).remove();
			this.list.find( this.options.wrapperElement ).remove();
		} else {
			this.newelement.remove();
			this.list.remove();
		}
		this.element.show();	

		// call widget destroy function
		$.Widget.prototype.destroy.apply(this, arguments);
	},

	_typeAhead: function(code, eventType){
		var self = this, focusFound = false, C = String.fromCharCode(code);
		c = C.toLowerCase();

		if (self.options.typeAhead == 'sequential') {
			// clear the timeout so we can use _prevChar
			window.clearTimeout('ui.selectmenu-' + self.selectmenuId);

			// define our find var
			var find = typeof(self._prevChar) == 'undefined' ? '' : self._prevChar.join('');
			
			function focusOptSeq(elem, ind, c){
				focusFound = true;
				$(elem).trigger(eventType);
				typeof(self._prevChar) == 'undefined' ? self._prevChar = [c] : self._prevChar[self._prevChar.length] = c;
			}
			this.list.find('li a').each(function(i) {	
				if (!focusFound) {
					// allow the typeahead attribute on the option tag for a more specific lookup
					var thisText = $(this).attr('typeahead') || $(this).text();
					if (thisText.indexOf(find+C) == 0) {
						focusOptSeq(this,i, C)
					} else if (thisText.indexOf(find+c) == 0) {
						focusOptSeq(this,i,c)
					}
				}
			});
			
			// if we didnt find it clear the prevChar
			// if (!focusFound) {
				//self._prevChar = undefined
			// }

			// set a 1 second timeout for sequenctial typeahead
			//  	keep this set even if we have no matches so it doesnt typeahead somewhere else
			window.setTimeout(function(el) {
				el._prevChar = undefined;
			}, 1000, self);

		} else {
			//define self._prevChar if needed
			if (!self._prevChar){ self._prevChar = ['',0]; }

			var focusFound = false;
			function focusOpt(elem, ind){
				focusFound = true;
				$(elem).trigger(eventType);
				self._prevChar[1] = ind;
			}
			this.list.find('li a').each(function(i){	
				if(!focusFound){
					var thisText = $(this).text();
					if( thisText.indexOf(C) == 0 || thisText.indexOf(c) == 0){
							if(self._prevChar[0] == C){
								if(self._prevChar[1] < i){ focusOpt(this,i); }	
							}
							else{ focusOpt(this,i); }	
					}
				}
			});
			this._prevChar[0] = C;
		}
	},
	
	// returns some usefull information, called by callbacks only
	_uiHash: function() {
		var index = this.index();
		return {
			index: index,
			option: $("option", this.element).get(index),
			value: this.element[0].value
		};
	},

	open: function(event) {
		var self = this;
		if ( this.newelement.attr("aria-disabled") != 'true' ) {
			// TODO: seems to be useless
			// this._refreshPosition();
			this._closeOthers(event);
			this.newelement
				.addClass('ui-state-active');
			if (self.options.wrapperElement) {
				this.list.parent().appendTo('body');
			} else {
				this.list.appendTo('body');
			}
			
			this.list.addClass(self.widgetBaseClass + '-open').attr('aria-hidden', false);
			// FIX IE: Refreshing position before focusing the element, prevents IE from scrolling to the focused element before it is in position.
			this._refreshPosition();
			this.list.find('li:not(.' + self.widgetBaseClass + '-group):eq(' + this._selectedIndex() + ') a')[0].focus();
			if ( this.options.style == "dropdown" ) {
				this.newelement.removeClass('ui-corner-all').addClass('ui-corner-top');
			}
			this._trigger("open", event, this._uiHash());
		}
	},

	close: function(event, retainFocus) {
		if ( this.newelement.is('.ui-state-active') ) {
			this.newelement
				.removeClass('ui-state-active');
			this.list
				.attr('aria-hidden', true)
				.removeClass(this.widgetBaseClass + '-open');
			if ( this.options.style == "dropdown" ) {
				this.newelement.removeClass('ui-corner-top').addClass('ui-corner-all');
			}
			if ( retainFocus ) {
				this.newelement.focus();
			}
			this._trigger("close", event, this._uiHash());
		}
	},

	change: function(event) {
		this.element.trigger("change");
		this._trigger("change", event, this._uiHash());
	},

	select: function(event) {
		this._trigger("select", event, this._uiHash());
	},

	_closeOthers: function(event) {
		$('.' + this.widgetBaseClass + '.ui-state-active').not(this.newelement).each(function() {
			$(this).data('selectelement').selectmenu('close', event);
		});
		$('.' + this.widgetBaseClass + '.ui-state-hover').trigger('mouseout');
	},

	_toggle: function(event, retainFocus) {
		if ( this.list.is('.' + this.widgetBaseClass + '-open') ) {
			this.close(event, retainFocus);
		} else {
			this.open(event);
		}
	},

	_formatText: function(text) {
		return (this.options.format ? this.options.format(text) : text);
	},

	_selectedIndex: function() {
		return this.element[0].selectedIndex;
	},

	_selectedOptionLi: function() {
		return this._optionLis.eq(this._selectedIndex());
	},

	_focusedOptionLi: function() {
		return this.list.find('.' + this.widgetBaseClass + '-item-focus');
	},

	_moveSelection: function(amt) {
		var currIndex = parseInt(this._selectedOptionLi().data('index'), 10);
		var newIndex = currIndex + amt;
		// do not loop when using up key
		if (newIndex >= 0 )  return this._optionLis.eq(newIndex).trigger('mouseup');
	},

	_moveFocus: function(amt) {
		if (!isNaN(amt)) {
			var currIndex = parseInt(this._focusedOptionLi().data('index') || 0, 10);
			var newIndex = currIndex + amt;
		}
		else {
			var newIndex = parseInt(this._optionLis.filter(amt).data('index'), 10);
		}

		if (newIndex < 0) {
			newIndex = 0;
		}
		if (newIndex > this._optionLis.size() - 1) {
			newIndex = this._optionLis.size() - 1;
		}
		
		var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000);

		this._focusedOptionLi().find('a:eq(0)').attr('id', '');
		
		if (this._optionLis.eq(newIndex).hasClass( this.namespace + '-state-disabled' )) {
			// if option at newIndex is disabled, call _moveFocus, incrementing amt by one
			(amt > 0) ? amt++ : amt--;
			this._moveFocus(amt, newIndex);
		} else {
			this._optionLis.eq(newIndex).find('a:eq(0)').attr('id',activeID).focus();
		}
		
		this.list.attr('aria-activedescendant', activeID);
	},

	_scrollPage: function(direction) {
		var numPerPage = Math.floor(this.list.outerHeight() / this.list.find('li:first').outerHeight());
		numPerPage = (direction == 'up' ? -numPerPage : numPerPage);
		this._moveFocus(numPerPage);
	},

	_setOption: function(key, value) {
		this.options[key] = value;
		// set 
		if (key == 'disabled') {
			this.close();
			this.element
				.add(this.newelement)
				.add(this.list)[value ? 'addClass' : 'removeClass'](
					this.widgetBaseClass + '-disabled' + ' ' +
					this.namespace + '-state-disabled')
				.attr("aria-disabled", value);
		}
	},

	disable: function(index, type){
			// if options is not provided, call the parents disable function
			if ( typeof( index ) == 'undefined' ) {
				this._setOption( 'disabled', true );
			} else {
				if ( type == "optgroup" ) {
					this._disableOptgroup(index);
				} else {
					this._disableOption(index);
				}
			}
	},

	enable: function(index, type) {
			// if options is not provided, call the parents enable function
			if ( typeof( index ) == 'undefined' ) {
				this._setOption('disabled', false);
			} else {
				if ( type == "optgroup" ) {
					this._enableOptgroup(index);
				} else {
					this._enableOption(index);
				}
			}
	},

	_disabled: function(elem) {
			return $(elem).hasClass( this.namespace + '-state-disabled' );
	},
	

	_disableOption: function(index) {
			var optionElem = this._optionLis.eq(index);
			if (optionElem) {
				optionElem.addClass(this.namespace + '-state-disabled')
					.find("a").attr("aria-disabled", true);
				this.element.find("option").eq(index).attr("disabled", "disabled");
			}
	},

	_enableOption: function(index) {
			var optionElem = this._optionLis.eq(index);
			if (optionElem) {
				optionElem.removeClass( this.namespace + '-state-disabled' )
					.find("a").attr("aria-disabled", false);
				this.element.find("option").eq(index).removeAttr("disabled");
			}
	},

	_disableOptgroup: function(index) {		
			var optGroupElem = this.list.find( 'li.' + this.widgetBaseClass + '-group-' + index );
			if (optGroupElem) {
				optGroupElem.addClass(this.namespace + '-state-disabled')
					.attr("aria-disabled", true);
				this.element.find("optgroup").eq(index).attr("disabled", "disabled");
			}
	},

	_enableOptgroup: function(index) {		
			var optGroupElem = this.list.find( 'li.' + this.widgetBaseClass + '-group-' + index );
			if (optGroupElem) {
				optGroupElem.removeClass(this.namespace + '-state-disabled')
					.attr("aria-disabled", false);
				this.element.find("optgroup").eq(index).removeAttr("disabled");
			}
	},
	
	index: function(newValue) {
		if (arguments.length) {
			if (!this._disabled($(this._optionLis[newValue]))) {
				this.element[0].selectedIndex = newValue;
				this._refreshValue();
			} else {
				return false;
			}
		} else {
			return this._selectedIndex();
		}
	},

	value: function(newValue) {
		if (arguments.length) {
			this.element[0].value = newValue;
			this._refreshValue();
		} else {
			return this.element[0].value;
		}
	},

	_refreshValue: function() {
		var activeClass = (this.options.style == "popup") ? " ui-state-active" : "";
		var activeID = this.widgetBaseClass + '-item-' + Math.round(Math.random() * 1000);
		// deselect previous
		this.list
			.find('.' + this.widgetBaseClass + '-item-selected')
			.removeClass(this.widgetBaseClass + "-item-selected" + activeClass)
			.find('a')
			.attr('aria-selected', 'false')
			.attr('id', '');
		// select new
		this._selectedOptionLi()
			.addClass(this.widgetBaseClass + "-item-selected" + activeClass)
			.find('a')
			.attr('aria-selected', 'true')
			.attr('id', activeID);
			
		// toggle any class brought in from option
		var currentOptionClasses = (this.newelement.data('optionClasses') ? this.newelement.data('optionClasses') : "");
		var newOptionClasses = (this._selectedOptionLi().data('optionClasses') ? this._selectedOptionLi().data('optionClasses') : "");
		this.newelement
			.removeClass(currentOptionClasses)
			.data('optionClasses', newOptionClasses)
			.addClass( newOptionClasses )
			.find('.' + this.widgetBaseClass + '-status')
			.html( 
				this._selectedOptionLi()
					.find('a:eq(0)')
					.html()
			);

		this.list.attr('aria-activedescendant', activeID);
	},

	_refreshPosition: function() {
		var o = this.options;
		// if its a native pop-up we need to calculate the position of the selected li
		if (o.style == "popup" && !o.positionOptions.offset) {
			var selected = this._selectedOptionLi();
			var _offset = "0 -" + (selected.outerHeight() + selected.offset().top - this.list.offset().top);
		}
		this.list
			.css({
				zIndex: this.element.zIndex()
			})
			.position({
				// set options for position plugin
				of: o.positionOptions.of || this.newelement,
				my: o.positionOptions.my,
				at: o.positionOptions.at,
				offset: o.positionOptions.offset || _offset
			});
	}
});

})(jQuery);
;
(function($){
  $.fn.file_upload_widget = function() {

      $.each( $(this), function(){
        $(this)
        .addClass("stylized")
        .wrap('<div class="fake_input_container clearfix" />')
        .after("<div class='fake_input_file clearfix'>&nbsp;</div><a class='fake_input_file_link huge_txt' href='#' tabindex = -1 >Browse</a>")
        .hover(
            function(){
              $(this).parent('.fake_input_container').addClass('hovered');
            },function(){
              $(this).parent('.fake_input_container').removeClass('hovered');
            }
        )
        .focus(
            function(){
              $(this).parent('.fake_input_container').addClass('focused')
            }
        )
        .blur(
            function(){
              $(this).parent('.fake_input_container').removeClass('focused')
            }
        )
        .change(
            function(){
              //Inserting file names to our generated inputs
              var array_of_strings = $(this).val().split("\\");
              var last = array_of_strings.length - 1;
              $(this).parent('.fake_input_container').find('.fake_input_file').text(array_of_strings[last]);
            }
        );
      });

  };
})(jQuery);;
var Frank = function($) {
  HOVER_ANIMATION_DELAY = 120;
  return {
    init: function(){
      // styled checkbox and radio button
      $("input:checkbox, input:radio").checkBox();

      // styled input file
      $("input[type='file']:not(.stylized)").addClass('stylized').file_upload_widget();

      // styled combobox
      $('select:not(.combobox)').addClass('combobox').selectmenu();


      // Calculate margins beetween footer menu columns, agile aproach for different link content
      available_space = 899;
      content_space = $('#block-menu-menu-footer-menu ul.menu:first').width();
      margin_space = available_space - content_space ;
      $('#block-menu-menu-footer-menu ul.menu:first > li').css('margin-right', (margin_space/4));


      $('[placeholder]:visible').placeholder();

      Frank.ctaHoverAnim($('.indent-with-arrow, input:submit, input:button, .more-link a').not('.modified, .search-block-button'));


      //Add listener to logo for speech bubble
      $('#logo', '#header').mouseenter(function(){
        $('.speech-bubble-container', '#header').show();
      });
      $('.speech-bubble-container', '#header').mouseleave(function(){
        $('.speech-bubble-container', '#header').hide();
      });

      $('.box-with-animation', '#main-wrapper').not('[href="javascript:void(0);"]').hoverIntent({
        over: Frank.box_up,
        timeout: 200,
        out: Frank.box_down
      });

      Frank.initAnimatedBackground();
      Frank.survey.init_survey();
    },
    ctaHoverAnim: function(selector){
      selector.wrap('<div class="special-link-container">').after('<div class="rollover-helper"></div>');
      $('.special-link-container').hover(
        function(){ $('.rollover-helper', $(this)).animate({width: '100%'}, {duration: 200, queue: false}); },
        function(){ $('.rollover-helper', $(this)).animate({width: '0%'}, {duration: 200, queue: false});   }
      );
    },
    renderPrintButtonTo: function(render_place, title){
      render_place.append('<span class="print-button" title="' + title + '"></span>');
      $('.print-button', render_place).click(function() {
        window.print();
      });
    },

    initAnimatedBackground: function() {
      if (Drupal.settings.backgrounds.length > 0){
        $.supersized({
          // Functionality
          slide_interval          :   10000,		// Length between transitions
          transition              :   1,        // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
          transition_speed        :	700,        // Speed of transition
          random                  : true,       // Load images in random order
          keyboard_nav            : false,
          fit_landscape           : false,
          fit_portrait            : true,

          // Components
          slide_links             :	false,      // Individual links for each slide (Options: false, 'number', 'name', 'blank')
          slides                  : Drupal.settings['backgrounds'] // Slideshow Images
        //[{
        //  'image' : Drupal.settings.basePath + 'sites/all/themes/frank/images/backgrounds/bg_01.jpg'
        //}]
        });
      };
    },
    box_up: function(){
      $(this).addClass('animated-box').delay(50).animate({
        top: -13,
        left: -13
      }, HOVER_ANIMATION_DELAY, function(){

      });
      $(this).children('.hoverable-box-border-right').attr('style', 'display:inline; right: 0; top: -13px; width: 0px; padding-bottom: 13px;').delay(50).animate({
        top: 0,
        right: -13,
        width: 13,
        'padding-bottom': 0
      }, HOVER_ANIMATION_DELAY);

      $(this).children('.hoverable-box-border-bottom').attr('style', 'display:inline; left: -13px; bottom: 0px; height: 0px; padding-right: 13px;').delay(50).animate({
        left: 0,
        bottom: -13,
        height: 13,
        'padding-right': 0
      }, HOVER_ANIMATION_DELAY);
      
      $(this).children('.hoverable-box-border-bottom-right').attr('style', 'display:inline; right: 0px; bottom: 0px; height: 0; width:0;').delay(50).animate({
        right: -13,
        bottom: -13,
        height: 13,
        width: 13
      }, HOVER_ANIMATION_DELAY);


      
    },

    box_down: function(){
      $(this).children('.hoverable-box-border-right').attr('style', 'display:inline; padding-bottom: 0px; right: -13px; top: 0;').delay(50).animate({
        right: 0,
        top: -13,
        width: 0,
        'padding-bottom': 13
      }, HOVER_ANIMATION_DELAY );

      $(this).children('.hoverable-box-border-bottom').attr('style', 'display:inline; left: 0; bottom: -13px; padding-right: 0px;').delay(50).animate({
        left: -13,
        bottom: 0,
        height: 0,
        'padding-right': 13
      }, HOVER_ANIMATION_DELAY);

      $(this).children('.hoverable-box-border-bottom-right').attr('style', 'display:inline; right: -13px; bottom: -13px; height: 13px; width:13px;').delay(50).animate({
        right: 0,
        bottom: 0,
        height: 0,
        width: 0
      }, HOVER_ANIMATION_DELAY);

      $(this).delay(50).animate({
        top: 0,
        left: 0
      }, HOVER_ANIMATION_DELAY, function() {
        $(this).removeClass('animated-box');
        Frank.hover_animation_state = 0;
      });
    }
  }
}(jQuery);

jQuery(document).ready(function(){
  Frank.init();
});

;
Frank.drugs = function($) {
  HIDE_DELAY = 0;
  var search_timer = null;
  var color_timer = null;
  var letter_timer = null
  var debug_timer = null;
  var empty_timer = null;
  var visible_letters = 0;
  var debug_mode = false;

  return {
    get_elapsed_time: function() {
      var my_current_timestamp;
      var ret = 0;
      my_current_timestamp = new Date();		//stamp current date & time
      if (debug_timer) {
        ret = my_current_timestamp.getTime() - debug_timer;
      }
      debug_timer = my_current_timestamp.getTime();
      return ret;
    },

    debug_drug_js: function(message, reset){
      if (debug_mode == true) {
        time = Frank.drugs.get_elapsed_time();
        if (reset) console.log(message);
        else console.log(message + ': ' + time);
      }
    },
    
    levenshtein: function(s1, s2) {
      // Calculate Levenshtein distance between two strings
      //
      // version: 1109.2015
      // discuss at: http://phpjs.org/functions/levenshtein
      // + original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
      // + bugfixed by: Onno Marsman
      // + revised by: Andrea Giammarchi (http://webreflection.blogspot.com)
      // + reimplemented by: Brett Zamir (http://brett-zamir.me)
      // + reimplemented by: Alexander M Beedie
      // * example 1: levenshtein('Kevin van Zonneveld', 'Kevin van Sommeveld');
      // * returns 1: 3
      if (s1 == s2) {
        return 0;
      }
      var s1_len = s1.length;
      var s2_len = s2.length;
      if (s1_len === 0) {
        return s2_len;
      }
      if (s2_len === 0) {
        return s1_len;
      }
      // BEGIN STATIC
      var split = false;
      try {
        split = !('0')[0];
      } catch (e) {
        split = true; // Earlier IE may not support access by string index
      }
      // END STATIC
      if (split) {
        s1 = s1.split('');
        s2 = s2.split('');
      }

      var v0 = new Array(s1_len + 1);
      var v1 = new Array(s1_len + 1);
      var s1_idx = 0,
      s2_idx = 0,
      cost = 0;
      for (s1_idx = 0; s1_idx < s1_len + 1; s1_idx++) {
        v0[s1_idx] = s1_idx;
      }
      var char_s1 = '',
      char_s2 = '';
      for (s2_idx = 1; s2_idx <= s2_len; s2_idx++) {
        v1[0] = s2_idx;
        char_s2 = s2[s2_idx - 1];

        for (s1_idx = 0; s1_idx < s1_len; s1_idx++) {
          char_s1 = s1[s1_idx];
          cost = (char_s1 == char_s2) ? 0 : 1;
          var m_min = v0[s1_idx + 1] + 1;
          var b = v1[s1_idx] + 1;
          var c = v0[s1_idx] + cost;
          if (b < m_min) {
            m_min = b;
          }
          if (c < m_min) {
            m_min = c;
          }
          v1[s1_idx + 1] = m_min;
        }
        var v_tmp = v0;
        v0 = v1;
        v1 = v_tmp;
      }
      return v0[s1_len];
    },

    filter_drug_types: function(){
      Frank.drugs.filter_drugs($('#drug_filter').val());
    },

    show_drug_types: function(){
      Frank.drugs.debug_drug_js('show drug types start', true);
      if ($("#drug_filter_type_drug").is(':checked') && $("#drug_filter_type_street_talk").is(':checked')) {
        $('.drug-type, .street-slang-type').show();
      } else {
        $('.drug-type, .street-slang-type ').hide();
      }
      Frank.drugs.debug_drug_js('show drug types end');

    },

    filter_drugs: function(term){
      if (!term || term === '') {
        //filter only by entity type
        Frank.drugs.debug_drug_js('entity type filter start', true);
        if ($("#drug_filter_type_drug").is(':checked')) {
          $('.drug.type_drug, .drug.type_drug_aka').show().addClass('visible_box');
        } else {
          $('.drug.type_drug, .drug.type_drug_aka').hide().removeClass('visible_box');
        }
        if ($("#drug_filter_type_street_talk").is(':checked')) {
          $('.drug.type_street_talk').show().addClass('visible_box');
        } else {
          $('.drug.type_street_talk').hide().removeClass('visible_box');
        }
        Frank.drugs.debug_drug_js('entity type filter end');
      } else {
        //term filtering
        Frank.drugs.debug_drug_js('term filter start', true);
        term = term.toLowerCase();
        var show_drugs = $("#drug_filter_type_drug").is(':checked');
        var show_street_talk = $("#drug_filter_type_street_talk").is(':checked');
        $('div.drug').each(function(){
          if (!show_drugs && ($(this).hasClass('type_drug') || $(this).hasClass('type_drug_aka')) || !show_street_talk && $(this).hasClass('type_street_talk')) {
            $(this).hide().removeClass('visible_box');
          } else {
            var title = $(this).find('.drug_box').children('.field-content').text().toLowerCase();
            if (title.toLowerCase().indexOf(term) != -1) {
              $(this).show().addClass('visible_box');
            } else {
              $(this).hide().removeClass('visible_box');
            }
          }
        });
        Frank.drugs.debug_drug_js('term filter end');

      }
      Frank.drugs.show_drug_types();
      clearTimeout(color_timer);
      color_timer = setTimeout(function (){Frank.drugs.colorize_titles(term)}, 5);
      clearTimeout(letter_timer);
      letter_timer = setTimeout(function (){Frank.drugs.adjust_drug_letters()}, 5);
    },

    colorize_titles: function(term) {
      Frank.drugs.debug_drug_js('colorize start');
      $('div.drug.visible_box .drug_box .field-content').each(function(){
        // get text, not html, to clear previous highlihts
        title = $(this).text();
        if (term && term.length > 0 && term !== '') {
          $(this).addClass('search_result');
          var re = new RegExp('('+term+')','ig');
          title = title.replace(re, '<span class="drug_highlighted">$1<\/span>');
        } else {
          $(this).removeClass('search_result');
        }
        $(this).html(title);
      });
      Frank.drugs.debug_drug_js('colorize end');
    },

    adjust_drug_letter: function(el){
      elem = $(el);
      letter = $.trim(elem.find('.inner-content').text());
      Frank.drugs.debug_drug_js('letter ' + letter + ' start');

      var hide_letter = true;
      if ($('#frank-drugs-slider .drug_box_'+letter+'.visible_box').length > 0) hide_letter = false;

      if (hide_letter) {
        elem.hide();
        $('.frank_letter_links.link_to_letter_' + letter).children('span').show();
        $('.frank_letter_links.link_to_letter_' + letter).children('a').hide();
      } else {
        elem.show();
        visible_letters = visible_letters + 1;
        $('.frank_letter_links.link_to_letter_' + letter).children('span').hide();
        $('.frank_letter_links.link_to_letter_' + letter).children('a').show();
      }
      clearTimeout(empty_timer);
      empty_timer = setTimeout(function (){Frank.drugs.show_empty_message()}, 250);
      Frank.drugs.debug_drug_js('letters end');
    },

    adjust_drug_letters: function(){
      visible_letters = 0;
      
      Frank.drugs.debug_drug_js('letters start');
      $('#frank-drugs-slider .letter-container').each(function(i, elem){
        setTimeout(function() {Frank.drugs.adjust_drug_letter(elem)}, i*3);
      });
      Frank.drugs.debug_drug_js('letters end');
    },

    show_empty_message: function(){
      //if empty, show suggestions
      if (visible_letters == 0) {
        if ($('.drug_filter_types > :checkbox:checked').length == 0) {
          $('#drugs-view-empty').hide();
          $('#drugs-no-filter').show(1500);
          return;
        }
        $('#drugs-no-filter').hide();
        var best_match_val = 10000;
        var best_match = '';
        var show_drugs = $("#drug_filter_type_drug").is(':checked');
        var show_street_talk = $("#drug_filter_type_street_talk").is(':checked');
        $('div.drug').each(function(){
          if (show_drugs && ($(this).hasClass('type_drug') || $(this).hasClass('type_drug_aka')) || show_street_talk && $(this).hasClass('type_street_talk')) {
            var title = $(this).find('.drug_box').children('.field-content').text().toLowerCase();
            var lev = Frank.drugs.levenshtein(title.toLowerCase(), $('#drug_filter').val());
            if ( lev < best_match_val) {
              best_match_val = lev;
              best_match = title;
            }
          }
        });
        $('#no-result-for-term, #no-result-for-term-tell-us').html($('#drug_filter').val());
        $('#do-you-mean-term').html(best_match);
        $('#drugs-view-empty').show(900);
        Frank.drugs.debug_drug_js('suggestions end');
      } else {
        $('#drugs-view-empty').hide();
      }
    },

    prepare_search: function(delay){
      clearTimeout(search_timer);
      if (!delay) delay = 1000;
      search_timer = setTimeout(Frank.drugs.perform_search, delay);
      if ($('#drug_filter').val().length == 0  ) {
        $('#clear-search-results').hide();
      }
      else {
        $('#clear-search-results').show();
      }
    },

    perform_search: function(){
      term = $('#drug_filter').val();
      Frank.drugs.filter_drugs(term);

      if (term && term.length > 0) {
        var search_log_url = "http://" + window.location.hostname + Drupal.settings.basePath + "?q=log_search/";
        $.get( search_log_url + term);
      }
    },

    init_search_pane: function() {
      Frank.drugs.debug_drug_js('init start', true);

      $(".drug_box").mouseenter( function(){
        $('.views-row', '#frank-drugs-slider').removeClass('active');
        $(".drug_description").hide();
        if ( $(this).next(".drug_description").find(".inner-content").html().length > 39 ) {
          $(this)
          .parents('.views-row').addClass('active').find(".drug_description")
          .show()
          .css({
            'left' : $(this).outerWidth() + 23 + 15, // label width + description arrow width + adjustable offset
            'top'  : $(this).outerHeight()/2 - $(this).parents('.drug').children(".drug_description").outerHeight()/2
          });
        };
      });

      $('.drug_filter_types > :checkbox').change(function(){
        Frank.drugs.filter_drug_types();
      });
      $('#drug_filter').keyup(function(){
        Frank.drugs.prepare_search();
      })
      $('#drug_filter').change(function(){
        Frank.drugs.prepare_search();
      })
      $("a#clear-search-results").click(function(){
        $('.search-input-container input').val('');
        Frank.drugs.prepare_search(10);
        return false;
      });
      $('.drug_filter_letters a').click(function(){
        $('.drug_filter_letters a').removeClass('current');
        $(this).addClass('current');
      });
      $('#do-you-mean-term').click(function(){
        $('#drug_filter').val($(this).html());
        $('#drug_filter').change();
      });

      if ($('#drug_filter').length && $('#drug_filter').val().length == 0 ) {
        $('#clear-search-results').hide();
      }
      Frank.drugs.debug_drug_js('init end');

      Frank.drugs.filter_drug_types();
    },

    init_description_page: function() {


      // Bind actions to drug description tabs
      main_tabs = $('.main-tab','#tabs');
      main_tabs_contents = $('.drug-description-content .level_1_tabs');


      main_tabs.click(function(){
        requested_maintabs_content = main_tabs_contents.eq($(this).index());

        main_tabs.removeClass('active'); //remove class from all main tabs "The Drug", "The Effects", "The Risks", "The Law"
        main_tabs_contents.removeClass('active'); //remove class from all main tabs sections container

        $(this).addClass('active');
        requested_maintabs_content.addClass('active');

        try{ coi_container_track({action:'changetab'}); } catch(e) {}
      });

      $('.submenu-tab', main_tabs_contents).click(function(){
        currently_active_main_tab = main_tabs_contents.filter('.active');
        requested_submenu_content = $('.submenu-content', currently_active_main_tab).eq( $(this).index() );

        $('.submenu-content', currently_active_main_tab).removeClass('active'); //remove class from all submenu contents
        $('.submenu span', currently_active_main_tab ).removeClass('active');  //remove class from all submenu contents

        $(this).addClass('active');
        requested_submenu_content.addClass('active');

      });

      $('.submenu-next-link', main_tabs_contents).click(function(){
        currently_active_main_tab = main_tabs_contents.filter('.active');
        requested_submenu_content = $('.submenu-content.active', currently_active_main_tab).next();

        $('.submenu-content', currently_active_main_tab).removeClass('active'); //remove class from all submenu contents
        $('.submenu span.active', currently_active_main_tab ).removeClass('active').next().addClass('active');  //remove set active submenu element

        requested_submenu_content.addClass('active');

      });

      // Match every two boxes in stories row and expand them to its highest heights (drugs description)
      $('.views-row', '#block-views-stories-widebox-block').each(function(){
        if ($(this).hasClass('views-row-even')){

          if ($(this).height() > $(this).prev().height())
            maxHeight = $(this).height();
          else
            maxHeight = $(this).prev().height();

          $(this).prev().find('.stories-widebox-item >.inner-content').height( maxHeight );
          $(this).find('.stories-widebox-item >.inner-content').height( maxHeight );
        }

      });
    },
	
	init_contact_set_equal_height: function() {
      // Match every two boxes in stories row and expand them to its highest heights (drugs description)
      $('.block.block-boxes', '.page-contact-frank .region-content').each(function(index){
        if (index % 2){

          if ($(this).find('.inner-content').height() > $(this).prev().find('.inner-content').height())
            maxHeight = $(this).find('.inner-content').height();
          else
            maxHeight = $(this).prev().find('.inner-content').height();

          $(this).prev().find('.static-box >.inner-content').height( maxHeight );
          $(this).find('.static-box >.inner-content').height( maxHeight );
        }

      });
	},
	
	init_contact_tooltip: function() {
	  this.init_contact_set_equal_height();
	  $(".boxes-box-content a.static-box").mouseenter( function(){
        $(".drug_description").hide();
          $(this)
          .parents('.boxes-box-content').children(".drug_description")
          .show()
		  .addClass('hovered-box')
          .css({
            'left' : $(this).outerWidth() - 15, // label width + description arrow width + adjustable offset
            'top'  : $(this).outerHeight()/2 - $(this).parents('.boxes-box-content').children(".drug_description").outerHeight()/2 - 15
          })
		  .unbind('mouseenter mouseleave')
		  .bind('mouseleave',function(e){
			$(this).hide();
			e.preventDefault();
		  })
		  .bind('mouseenter',function(e){
			e.preventDefault();
		  });
      });
	}
  }
}(jQuery);
;
/**
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
*
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne brian(at)cherne(dot)net
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover)}})(jQuery);;
/**
 * @file
 *
 * Implement a modal form.
 *
 * @see modal.inc for documentation.
 *
 * This javascript relies on the CTools ajax responder.
 */

(function ($) {
  // Make sure our objects are defined.
  Drupal.CTools = Drupal.CTools || {};
  Drupal.CTools.Modal = Drupal.CTools.Modal || {};

  /**
   * Display the modal
   *
   * @todo -- document the settings.
   */
  Drupal.CTools.Modal.show = function(choice) {
    var opts = {};

    if (choice && typeof choice == 'string' && Drupal.settings[choice]) {
      // This notation guarantees we are actually copying it.
      $.extend(true, opts, Drupal.settings[choice]);
    }
    else if (choice) {
      $.extend(true, opts, choice);
    }

    var defaults = {
      modalTheme: 'CToolsModalDialog',
      throbberTheme: 'CToolsModalThrobber',
      animation: 'show',
      animationSpeed: 'fast',
      modalSize: {
        type: 'fixed',
        width: 'auto',
        height: 'auto',
        addWidth: 0,
        addHeight: 0,
        // How much to remove from the inner content to make space for the
        // theming.
        contentRight: 0,
        contentBottom: 0
      },
      modalOptions: {
        opacity: .60,
        background: 'black'
      }
    };

    var settings = {};
    $.extend(true, settings, defaults, Drupal.settings.CToolsModal, opts);

    if (Drupal.CTools.Modal.currentSettings && Drupal.CTools.Modal.currentSettings != settings) {
      Drupal.CTools.Modal.modal.remove();
      Drupal.CTools.Modal.modal = null;
    }

    Drupal.CTools.Modal.currentSettings = settings;

    var resize = function(e) {
      // When creating the modal, it actually exists only in a theoretical
      // place that is not in the DOM. But once the modal exists, it is in the
      // DOM so the context must be set appropriately.
      var context = e ? document : Drupal.CTools.Modal.modal;

      if (Drupal.CTools.Modal.currentSettings.modalSize.type == 'scale') {
        var width = $(window).width() * Drupal.CTools.Modal.currentSettings.modalSize.width;
        var height = $(window).height() * Drupal.CTools.Modal.currentSettings.modalSize.height;
      }
      else {
        var width = Drupal.CTools.Modal.currentSettings.modalSize.width;
        var height = Drupal.CTools.Modal.currentSettings.modalSize.height;
      }

      // Use the additionol pixels for creating the width and height.
      $('div.ctools-modal-content', context).css({
        'width': width + Drupal.CTools.Modal.currentSettings.modalSize.addWidth + 'px',
        'height': height + Drupal.CTools.Modal.currentSettings.modalSize.addHeight + 'px'
      });
      $('div.ctools-modal-content .modal-content', context).css({
        'width': (width - Drupal.CTools.Modal.currentSettings.modalSize.contentRight) + 'px',
        'height': (height - Drupal.CTools.Modal.currentSettings.modalSize.contentBottom) + 'px'
      });
    }

    if (!Drupal.CTools.Modal.modal) {
      Drupal.CTools.Modal.modal = $(Drupal.theme(settings.modalTheme));
      if (settings.modalSize.type == 'scale') {
        $(window).bind('resize', resize);
      }
    }

    resize();

    $('span.modal-title', Drupal.CTools.Modal.modal).html(Drupal.CTools.Modal.currentSettings.loadingText);
    Drupal.CTools.Modal.modalContent(Drupal.CTools.Modal.modal, settings.modalOptions, settings.animation, settings.animationSpeed);
    $('#modalContent .modal-content').html(Drupal.theme(settings.throbberTheme));
    
    setTimeout("Frank.ctaHoverAnim(jQuery('.indent-with-arrow, input:submit, input:button', '#modalContent').not('.modified'))", 1000);
  };


  /**
   * Provide the HTML to create the modal dialog.
   */
  Drupal.theme.prototype.CToolsModalDialog = function () {
    var html = ''
    html += '  <div id="ctools-modal">'
    html += '    <div class="ctools-modal-content">' // panels-modal-content
    html += '      <div class="inner-content clearfix">';
    html += '        <div class="modal-header">';
    html += '          <span class="close">';
    html += '          </span>';
    html += '          <span id="modal-title" class="modal-title">&nbsp;</span>';
    html += '        </div>';
    html += '        <div id="modal-content" class="modal-content">';
    html += '        </div>';
    html += '      </div>';
    html += '      <span class="hoverable-box-border-right"></span>';
    html += '      <span class="hoverable-box-border-bottom"></span>';
    html += '      <span class="hoverable-box-border-bottom-right"></span>';
    html += '    </div>';
    html += '  </div>';

    return html;
  }


})(jQuery);
;
/**
 *
 * jquery.charcounter.js version 1.2
 * requires jQuery version 1.2 or higher
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */

(function($) {
	/**
	 * attaches a character counter to each textarea element in the jQuery object
	 * usage: $("#myTextArea").charCounter(max, settings);
	 */

	$.fn.charCounter = function (max, settings) {
		max = max || 100;
		settings = $.extend({
			container: "<small></small>",
			classname: "charcounter",
			format: "%1 characters left",
			pulse: true,
			delay: 0
		}, settings);
		var p, timeout;

		function count(el, container) {
			el = $(el);
			if (el.val().length > max) {
			    el.val(el.val().substring(0, max));
			    if (settings.pulse && !p) {
			    	pulse(container, true);
			    };
			};
			if (settings.delay > 0) {
				if (timeout) {
					window.clearTimeout(timeout);
				}
				timeout = window.setTimeout(function () {
					container.html(settings.format.replace(/%1/, (max - el.val().length)));
				}, settings.delay);
			} else {
				container.html(settings.format.replace(/%1/, (max - el.val().length)));
			}
		};

		function pulse(el, again) {
			if (p) {
				window.clearTimeout(p);
				p = null;
			};
			el.animate({ opacity: 0.1 }, 100, function () {
				$(this).animate({ opacity: 1.0 }, 100);
			});
			if (again) {
				p = window.setTimeout(function () { pulse(el) }, 200);
			};
		};

		return this.each(function () {
			var container;
			if (!settings.container.match(/^<.+>$/)) {
				// use existing element to hold counter message
				container = $(settings.container);
			} else {
				$(this).next("." + settings.classname).remove();
				container = $(settings.container).addClass(settings.classname);
                                
				// append element to hold counter message (clean up old element first)
                                if ( $('label[for=' + $(this).attr('id') + ']').not('.placeholder').length ) {
                                  $('label[for=' + $(this).attr('id') + ']').not('.placeholder').last().find("." + settings.classname).remove();
                                  $('label[for=' + $(this).attr('id') + ']').not('.placeholder').last().addClass('with-charcounter').append(container);
                                }
                                else {
                                  container.insertAfter(this);
                                }

			}
			$(this)
				.unbind(".charCounter")
				.bind("keydown.charCounter", function () { count(this, container); })
				.bind("keypress.charCounter", function () { count(this, container); })
				.bind("keyup.charCounter", function () { count(this, container); })
				.bind("focus.charCounter", function () { count(this, container); })
				.bind("mouseover.charCounter", function () { count(this, container); })
				.bind("mouseout.charCounter", function () { count(this, container); })
				.bind("paste.charCounter", function () {
					var me = this;
					setTimeout(function () { count(me, container); }, 10);
				});
			if (this.addEventListener) {
				this.addEventListener('input', function () { count(this, container); }, false);
			};
			count(this, container);
		});
	};

})(jQuery);;

function show_story_second_form(url, nid, token) {
 
  Drupal.CTools.Modal.show();
  jQuery('#modal-title').html('');                                   
  
  jQuery('#story-add-first-form').html(
    jQuery('#submit_info').html()
  );
  
  //Drupal.CTools.Modal.show();
  jQuery.ajax({
    url: url + '/ajax/' + nid + '/' + token, 
    success: function( data ) {
    jdata = jQuery.parseJSON(data);
    jQuery.each(jdata, function(index, value) { 
      if (value.command == "modal_display") {
        jQuery('#modal-content').html(value.output);
        jQuery('#modalContent').addClass('story-add-second-form');
      }
      
      // styled checkbox and radio button
      jQuery("input:checkbox, input:radio").checkBox();
      });

      bind_events_to_stories ();
      
      jQuery('#modalContent span.close').bind('click', function(){
        window.location.reload();
      });
     
    }
  });
}

function bind_events_to_stories () {
  //style upload widget
  jQuery("input[type='file']:not(.stylized)").addClass('stylized').file_upload_widget();

  
  story_tabs = jQuery('.submit-story-tabs a','#page-wrapper, #slider');

  story_tabs.click(function(){
            story_tabs_head = jQuery(this).parents('.submit-story-tabs');
            story_tabs_head.find('.story-tab-active').removeClass('story-tab-active');
            jQuery(this).addClass('story-tab-active');

            story_tabs_content = jQuery(this).parents('form').find('.submit-story-tabs-content');
            story_tabs_content.find('.story-tab-active').removeClass('story-tab-active');

            keys = jQuery(this).attr('id').split('-');
            jQuery('input[name="story_type"]', story_tabs_content.parent()).val(keys[2]);

            story_tabs_content.find('.submit-story-tab-content').eq(story_tabs_head.find('a').index(this)).addClass('story-tab-active');

//        story_tabs.removeClass('story-tab-active');
//        story_tabs_content.removeClass('story-tab-active');
//
//        jQuery(this).addClass('story-tab-active');
//        
//        keys = jQuery(this).attr('id').split('-');
//        jQuery('input[name="story_type"]', jQuery('#story-add-first-form')).val(keys[2]);
//          
//        story_tabs_content.eq(story_tabs.index(this)).addClass('story-tab-active');
//
  });
      
   };

jQuery(function($){
   jQuery(document).ready(function(){
      bind_events_to_stories();

      //inputs in stadrad form (not modal)
      $('[placeholder]', '#story-add-first-form').placeholder();
      $("input[type=text]", '#story-add-first-form').charCounter(100);
      $("textarea", '#story-add-first-form').charCounter(4000);

      //slider form on the right side
      $('[placeholder]', '#slider-tab-content-story').placeholder();
      $('input[type=text]', '#slider-tab-content-story').charCounter(100);
      $("textarea", '#slider-tab-content-story').charCounter(4000);


   });

});

jQuery(function($){
    var theme_modal = function(node) {
      if (node.hasClass('stories-widebox-item')) {
        $('div#modalContent').addClass("video-campaign");
      }
    }

  var bindPlayAction = function(selector){
    $(selector).bind('click', function(e){
      Drupal.CTools.Modal.show();
      $('#modal-title').html('');
      $('#modal-content').html($('.video-gallery-item-modal', $(this).parents('.inner-content')).html());
      theme_modal($(this).parents('.inner-content').parent());
      console.log($(this).parents('.inner-content').parent());

      e.preventDefault();
      return false;
    });
  }

  jQuery(document).ready(function(){

    bindPlayAction('.stories-widebox-item-video');
    bindPlayAction('.stories-widebox-item-button-play');
    bindPlayAction('.stories-widebox-item-type-video .stories-widebox-item-links a');
  });
});
;
Frank.survey = function($) {
  var popup_start_date = new Date("10 Jan 2012 15:00:00 GMT");
  var popup_stop_date = new Date("20 Jan 2012 14:00:00 GMT");
  var minutes_on_site = 4;

  return {
    readCookie: function(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
      }
      return null;
    },

    createCookie: function(name,value,minutes) {
      if (minutes) {
        var date = new Date();
        date.setTime(date.getTime()+(minutes*60*1000));
        var expires = "; expires="+date.toGMTString();
      }
      else var expires = "";
      document.cookie = name+"="+value+expires+"; path=/";
    },

    eraseCookie: function(name) {
      Frank.survey.createCookie(name,"",-60*24);
    },

    showPopup: function(){
      if ($('.ctools-modal-content').length < 1){
        Drupal.CTools.Modal.show();
        $('#modal-title').html('');
        $('#modal-content').html($('#survey').html());
        $('#modalContent').addClass('survey-modal');
        $('.indent-with-arrow', "#modalContent").live('click', Drupal.CTools.Modal.dismiss );

        Frank.survey.createCookie("no_survey", 1, 60*24*30);
        Frank.survey.eraseCookie("visit_time");
      }
    },

    init_survey: function(){
      var now = new Date();
      if (!Frank.survey.readCookie("no_survey") &&
      now > popup_start_date && now < popup_stop_date){
        var cookie = Frank.survey.readCookie("visit_time");
        var visitDate = now;
        if (cookie == null){
          Frank.survey.createCookie("visit_time", visitDate.toUTCString(), minutes_on_site + 1);
        } else {
          visitDate = new Date(cookie);
        }

        var miliseconds_till_popup = (((60 - visitDate.getSeconds()) + (minutes_on_site-1) * 60)*1000) - (now - visitDate);

        if (miliseconds_till_popup > 0){
          setTimeout(Frank.survey.showPopup, miliseconds_till_popup);
        }
      }
    }
  };
}(jQuery);
;
var TREATMENT_CENTRES_MAP = {
  map: null,
  bounds: null,
  points: new Array
}

TREATMENT_CENTRES_MAP.init = function(node_id, zoom) {
  var latlng = new google.maps.LatLng(53.409532, -2.06543);
  var mapOptions = {
    zoom: zoom,
    center: latlng,
    streetViewControl: false,
    mapTypeControl: false,
    panControl: true,
    scrollwheel: false,
    zoomControlOptions: {
      style: google.maps.ZoomControlStyle.SMALL
    },

    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  this.map = new google.maps.Map(document.getElementById(node_id),
      mapOptions);
  this.bounds = new google.maps.LatLngBounds();
      
};

;
jQuery(function($){

    var bind_events_to_feedback = function() {

      $('.feedback-submit-modal .close').click(function() {
        $('.feedback-submit-modal').hide();
      });
    }

    $('#submit-feedback, .submit-feedback', '#page-wrapper, #slider').click(function() {
      // form source
      $form = $(this).parents('form');

      if ($.trim($('.edit-title-first', $form).val()) == '')  {
        $('.edit-title-first', $form).addClass('error');
        alert('Subject field is required');
        return false;
      }
      else {
        $('.edit-title-first', $form).removeClass('error');
      }

      if ($.trim($('.edit-body-first', $form).val()) == '')  {
        $('.edit-body-first', $form).addClass('error');
        alert('Your comments are empty');
        return false;
      }
      else {
        $('.edit-body-first', $form).removeClass('error');
      }

      Drupal.CTools.Modal.show();

      $('#modal-title').html('');
      $('#modal-content').html($('.feedback-submit-modal', '#slider').clone().show());
      $('#modalContent').addClass('feedback-second-form');

      $modal_form = $('form', '#modal-content').attr('id', 'feedback-add-second-form-modal');

      $('input[name=title]', $modal_form).val($('.edit-title-first', $form).val());
      $('input[name=body]', $modal_form).val($('.edit-body-first', $form).val());


      //inputs in ctools modal
      $('[placeholder]', $modal_form).placeholder();
   });

   $(document).ready(function(){
      bind_events_to_feedback();

      //inputs in stadrad form (not modal)
      $('[placeholder]', '#feedback-add-form').placeholder();
      $("input[type=text]", '#feedback-add-form').charCounter(100);
      $("textarea", '#feedback-add-form').charCounter(200);

      //slider form on the right side
      $('.feedback [placeholder]', '#slider-tab-content-feedback').placeholder();
      $(".feedback input[type=text]", '#slider-tab-content-feedback').charCounter(100);
      $(".feedback textarea", '#slider-tab-content-feedback').charCounter(200);

  });

});
;

function bind_events_to_slider () {

  jQuery("input[type='file']:not(.stylized)").addClass('stylized').file_upload_widget();
      
  slider_tabs = jQuery('a','#slider-tabs');
  slider_tabs_content = jQuery('.slider-tab-content','#slider-tabs-content');

  jQuery('#slider-close').click(function(){
    jQuery('#slider').stop().animate({right: '-495px'}, {
      queue:false, 
      duration:200,  
      complete: function () {
        jQuery(this).css({'top' : 100}).removeClass('slider-active').animate({right: '-450px'}, 200);
      }
    });
    jQuery('#modalBackdrop').hide();
  });                                                                           

  slider_tabs.click(function(){

    slider_tabs
      .removeClass()
      .not(jQuery(this))
      .addClass('slider-tab-not-active')
      .end()
      .filter((jQuery(this)))
      .addClass('slider-tab-active');

    slider_tabs_content.removeClass('slider-tab-active');
    slider_tabs_content.eq(slider_tabs.index(this)).addClass('slider-tab-active');

    if (!jQuery('#slider').hasClass('slider-active')) {
      jQuery('#slider').stop().animate({right: 0}, {
        queue:false, 
        duration:200, 
        //easing:'easeOutExpo', 
        complete: function () {
          jQuery(this).css({'top' : jQuery(this).offset().top }).addClass('slider-active');
        }
      });
    }

    if( jQuery('#modalBackdrop').length < 1){
      jQuery('body').append('<div id="modalBackdrop" style="display: none;"></div>');      
    }
    if( !jQuery('#modalBackdrop').is(':visible')) {
      jQuery('#modalBackdrop').show();
    }
    
  });
      
};


jQuery(document).ready(function(){
  bind_events_to_slider();
});
;
Frank.contact = function($) {
  return {
    bind_events_to_contact_info: function(){
      $(".site-promo-box", "#block-views-promo-boxes-block-5").mouseenter( function(){
          $(this)
          .parents('.views-row')
          .addClass('active')
          .end()
          .next('.additional_info')
          .show()
          .css({
            'left' : $(this).outerWidth() + 0 + 0, // label width + description arrow width + adjustable offset
            'top'  : -20
          });
      });
      $(".site-promo-box", "#block-views-promo-boxes-block-5").mouseleave( function(){
        $(this)
        .parents('.views-row')
        .removeClass('active')
        $(".additional_info", "#block-views-promo-boxes-block-5").hide();
      });
    }
  }
}(jQuery);

jQuery(document).ready(function(){
  Frank.contact.bind_events_to_contact_info();
});

