// jc.jquery.js
// written by James D Chalmers
// Where possible, Code Copyright & Property of MTCMedia LTD
// www.mtcmedia.co.uk
// MTCMEDIA: Internet Media Solutions

// v1.632
// released 17 Feb 2010
// Added auto window.resize events to centerscreen & screenfill

// v1.631
// released 8 Feb 2010
// updated centerscreen
//   added auto positioning to element
// this should be checked across all functions
// some rollfade updates got over-written. These have now been fixed.

// v1.63
// released 27 Jan 2010
// added jcmarquee
//  this is an adaptation of brandscroll
//  these two functions badly need to be deprecated and
//  rewritten as a single light function
//  that is highly customisable.
// modified brandscroll_settings identifier.
// 	now : var i = 'bs_'+Math.floor(Math.random()*10102030123);

// v1.62
// released 19 Jan 2010
// changelog:
// fixed rollfade checkclass
// adjusted rollfade default (fades in to 1.0 opacity now instead of 0.9)
// fixed brandscroll mouse out
// cleared timeout properly in brandscroll
// adding date to new versions

// v1.61
// changelog
// added daisychaining to all functions
// modified centerscreen

// v1.6
// changelog
// added brandscroll();

//  v1.51
// changelog
// added formhint

// v1.0 traced back to 8th Dec 2009

/////// NEEDED GLOBAL VARIABLES

var brandscroll_settings = new Array;
var jcmarquee = new Array;

/////// NEEDED FUNCTIONS

// #sp
// stops event bubbling
function sp (event){
	event.stopPropagation();
}

// #screenfill
// leaves no borders
// yset

$.fn.screenfill = function(options){

	var options = $.extend({
		animate : 1,
		onresize : 1,
		onresizeanimate : 0
		}, options);

	$('html, body').css({overflow : 'hidden'});

	var w = $(window).width();
	var h = $(window).height();

	return this.each(function(){

		var el = $(this);
		var ew = el.outerWidth();
		var eh = el.outerHeight();

		var ratio = ew / eh;
		
		// auto positioning
		if(el.css('position')!='absolute'){
			el.css('position', 'relative');
		}

		var cssoptions = {
		};

		if(w > h){
			cssoptions.width = w;
			cssoptions.height = (w/ratio);
		} else {
			cssoptions.height = h;
			cssoptions.width = (h*ratio);
		}

		if(cssoptions.width < w){
			cssoptions.height = h;
			cssoptions.width = (h*ratio);
		}

		if(cssoptions.height < h) {
			cssoptions.height = h;
			cssoptions.width = (h*ratio);
		}

		// center

		cssoptions.left = ((w-cssoptions.width)/2)+'px';
		cssoptions.top = ((h-cssoptions.height)/2)+'px';

		cssoptions.height += 'px';
		cssoptions.width += 'px';

		if(options.animate == true){
		el.stop().animate(cssoptions, {queue : false, duration : 500});
		} else {
		el.stop().css(cssoptions);
		}

		el.fadeIn();
		
		if(options.onresize){
		$(window).bind('resize', function(){
			el.screenfill({
				animate: options.onresizeanimate,
				onresize: 0
			});
		});
		}

	});

};

// #centerscreen

// v1.631 update:
// supports auto positioning

// v1.61 updates:
// now supports custom pre-set width / height
// and horizontal and vertical adjustments
// also supports centering relative to immediate parent

$.fn.centerscreen = function(options){
	var options = $.extend({
		horizontal : true,
		vertical : true,
		animate : true,
		speed : 500,
		parent : false,
		vertical_adjustment : 0,
		horizontal_adjustment : 0,
		w : 0,
		h : 0,
		onresize : 1,
		onresizeanimate : 0
	}, options);
	
	return this.each(function(){
		var el = $(this);

		var ew = el.outerWidth(true);
		var eh = el.outerHeight(true);
		
		if(options.parent){
			var w = el.parent().outerWidth();
			var h = el.parent().outerHeight();
		} else {
			var w = $(window).width();
			var h = $(window).height();
		}
		
		// auto positioning
		if(el.css('position') != 'absolute'){
			el.css('position', 'relative');
		}
		
		if(options.w >0){
			w = options.w-1+1;
		}
		
		if(options.h>0){
			h = options.h-1+1;
		}
		
		var w = (options.horizontal_adjustment-1+1)+w;
		var h = (options.vertical_adjustment-1+1)+h;

		var cssoptions = '';
		var cssoptions = {};

		if(ew < w){
			if(options.horizontal){
				cssoptions.left = (w-ew)/2+'px';
			}
		} else {
			cssoptions.left = 0;
		}

		if(eh < h) {
			if(options.vertical){
				cssoptions.top = (h-eh)/2+'px';
			}
		} else {
			cssoptions.top = 0;
		}
		if(options.animate){
			el.stop().animate(cssoptions, {queue : false, duration : options.speed});
		} else {
			el.stop().css(cssoptions);
		}

		if(options.onresize){
		options.onresize = 0;
		options.animate = options.onresizeanimate;
		$(window).bind('resize', function(){
			el.centerscreen(options);
		});
		}

		el.show();

	});

};


// #rollover
// name images, imagename_0.jpg (or whatever filetype)
// imagename_1.jpg (for hover)..

$.fn.rollover = function(options){

	var options = $.extend({
		preloadID : '#rollover_preloader'
	}, options);

	return this.each(function(){
		var el = $(this);
		if(typeof(el.attr('src')) == 'undefined'){
			// find the image
			el = el.find('img');
		}

		if(el.length > 0){
			// start rollover
			var thissrc = el.attr('src');
			// thissrc is image original src

			var thishover = thissrc;
			thishover = thishover.replace(/(.*)_[0-9](\.[a-z]+)$/, "$1_1$2");

			el.hover(function(){
				el.attr('src', thishover);
			}, function(){
				el.attr('src', thissrc);
			}); // close hover

			// PRELOAD
			if($(options.preloadID).length == 0){
				// create it
				$('body').prepend('<div id="'+options.preloadID.replace(/[#.]/g, '')+'" style="display:none"></div>');
			}

			$(options.preloadID).append('<img src="'+thishover+'" />');

		}	// close el.length
	}); // close each

};

// #slidepanel

$.fn.slidepanel = function(options) {

	var options = $.extend({
		slideID : '.slider',
		speed_in : 500,
		speed_out : 500,
		hideOptions :	{
						top : '100%'
						}
	},options);

	return this.each(function(){

		var el = $(this);
		var slide = $(this).find(options.slideID);
		
		// auto positioning
		if(el.css('position')!='absolute'){
			el.css('position', 'relative');
		}

		// store original positions etc
		var originalcss = {
			top : slide.css('top'),
			left : slide.css('left')
			};

		function hide() {
			slide.stop().animate(options.hideOptions, {queue : false, duration : options.speed_out});

		}

		function show() {

			slide.stop().animate(originalcss, {queue : false, duration : options.speed_in});

		}

		hide();

 		el.hover(show, hide);

		slide.mouseover(sp);

		slide.children().mouseover(sp);
	});
};

////// Alpha PNG Background replacement...
///// note that options.color could supply a background image as well.

//// #alphabg

$.fn.alphabg = function(options) {

	var options = $.extend({
		opacity : 0.7,
		zIndex : '-1',
		color : '#000',
		fadeDuration : 0
	},options);

	return this.each(function(){
		var el = $(this);
		var grabber = 'grabber_'+Math.floor(Math.random()*10010923);
		el.attr('grabber', grabber);


		// auto positioning
		if(el.css('position')!='absolute'){
			el.css('position', 'relative');
		}

		var thisz = el.css('z-index');

		if(typeof(thisz) == 'undefined' || (thisz+'x').replace(/[^0-9]/g, '') == ''){
			el.css('z-index', '1');
		}

		var w = el.outerWidth()+'px';
 		var h = el.outerHeight()+'px';

		var bghtml  = '<div class="bg" style="position:absolute; top:0; left:0; ';
			bghtml += 'width:'+w+'; height:'+h+'; z-index:'+options.zIndex+'; background:'+options.color+';"></div>';

		var g = '[grabber='+grabber+'] ';

		if($(g+'> .bg').length == 0){
			el.append(bghtml);
		} else {
			$(g+'> .bg').css({width : w, height : h});
		}

		$(g+'> .bg').fadeTo(options.fadeDuration, options.opacity);

	});

};




// #rollfade
// apply fading effects to rollover
// check's custom class
$.fn.rollfade = function(options){

	var options = $.extend({
		checkClass : 'clicked',
		fadeIn : 1.0,
		fadeOut : 0.5, // also default fade
		duration : 300
	}, options);

	options.checkClass = options.checkClass.replace(/\./g, '');

	return this.each(function(){

		var el = $(this);
		if(!el.hasClass('.'+options.checkClass)){
			el.fadeTo(0, options.fadeOut);
		}

		el.hover(function(){
			if(el.hasClass('.'+options.checkClass) == false){
				el.stop().fadeTo(options.duration, options.fadeIn);
			}
		}, function(){
			if(el.hasClass(options.checkClass) == false){
				el.stop().fadeTo(options.duration, options.fadeOut);
			}
		});

	});

};



// #formhint
// helpful form field hint text
// clears on focus
$.fn.formhint = function(options){

	var options = $.extend({
	attr : 'title'
	}, options);

	return this.each(function(){
		// set value as title
		var el = $(this);

		if(el.val() == ''){
			el.val(el.attr(options.attr));

			el.focus(function(){
				if(el.val() == el.attr(options.attr)){
					el.val('');
				} else {
					el.select();
				}
			}); // close focus

			el.blur(function(){
				if(el.val() == ''){
					el.val(el.attr(options.attr));
				}
			}); // close blur
		} else { // close if)
			el.focus(function(){
			el.select();
		});

		}
	}); // close each

};

// #brandscroll
// notes: needs continuous mode
// needs work on onclick etc - passing $(this)

// example usage

//	 $(window).load(function(){
//		 $('#brandscroll').brandscroll();
//
//		 $('.right').brandscroll_button({
//			 el : '#brandscroll',
//			 direction : 'right'
//		 });
//
//		 $('.left').brandscroll_button({
//			 el : '#brandscroll'
//		 });
//	 });

// html markup
// <div id="brandscroll">
//	<div class="item">
//		<img src="/images/image.jpg" alt="" />
//	</div>
// </div>

// apply styles to #brandscroll and .item, as well as perhaps .left and .right

$.fn.brandscroll = function(options){

	var options = $.extend({
		speed : 1000,
		stoponhover : true,
		onclick : '',
		onmouseover : '',
		onmouseout : '',
		autoplay : true,
		autoplayinterval : 2000,
		cycle : true,
		autoheight : true,
		itemspacing : 5,
		autocenteritems : true,
		force : 100,
		rewindspeed : 1900
	},options);

	return this.each(function(){
	if($(this).length>0){

		var el = $(this);

		// assign id and save to moveQueue
		var i = 'bs_'+Math.floor(Math.random()*10102030123);
		// this is used to add actions to queue :)

		el.attr('brandscroll_settings', i);

		// save settings
		brandscroll_settings[i] = options;

		// get items
		var items = el.children('.item');

		// empty el interior
 		el.children(':not(.item)').remove();

		// build
		el.wrapInner('<div class="viewport"></div>');
		var vp = el.children('.viewport');

		vp.wrapInner('<div class="universe"></div>');
		var us = vp.children('.universe');

		// force apply some el css
		if(el.css('position')!='absolute'){
			el.css('position', 'relative');
		}

		// force apply some vp css
		vp.css({
			'position' : 'relative',
			height : '100%',
			width : '100%',
			'z-index' : 1,
			overflow : 'hidden'
		});

		// insert a clear
		us.append('<div style="clear:both;"></div>');

		// style universe items
		items = us.children('.item');

		items.css({
			float : 'left',
			'margin-right' : options.itemspacing+'px'
		});

		// calculate universe width
		var us_width = 0;

		// also calculate max height
		var maxheight = 0;

		items.each(function(){
			var e = $(this);
			us_width += (e.outerWidth(true));
			var thisheight = e.outerHeight(true);
			if(thisheight > maxheight){maxheight=thisheight;}
		});

		// force apply some universe css
		us.css({
			'position' : 'absolute',
			top : '0px',
			left : '0px',
			height : '100%',
			'z-index' : 5,
			width : us_width+'px'
		});

		if(options.autoheight){
		 	var css = {height : maxheight+'px'};
			el.css(css);
			us.css(css);
			vp.css(css);
		}

		// do autocenter
		if(options.autocenteritems){

			items.each(function(){

				var e = $(this);
				if(e.outerHeight(true) < maxheight){
					var thistop = maxheight - e.outerHeight(true);
					thistop = thistop/2;

					e.css({
						'position' : 'relative',
						top : thistop+'px'
					});
				}

			});

		}

		// do autoplay
		if(options.autoplay){
			brandscroll_settings[i]['interval'] = setInterval(function(){
				el.brandscroll_move({
					force : options.force,
					cycle : options.cycle,
					i : i,
					speed : options.speed,
					rewindspeed : options.rewindspeed
				});
			}, options.autoplayinterval);

		}

		// do stop on hover
		if(options.stoponhover){
			items.hover(function(){
				el.brandscroll_pause({i:i});
			}, function(){
				el.brandscroll_resume({i:i});
			});
		}

		if(options.onclick!=''){
			items.click(function(){
				return options['onclick']();
			});
		}

		if(options.onmouseover!=''){
			items.mouseover(function(){
				return options['onmouseover']();
			});
		}

		if(options.onmouseout!=''){
			items.mouseout(function(){
				return options['onmouseout']();
			});
		}
	}
	});
};

// brandscroll animation event

$.fn.brandscroll_move = function(options){

	var options = $.extend({
		force : '',
		cycle : '',
		i : '',
		speed : '',
		direction : 'right',
		rewindspeed : '',
		stopqueue : false
	}, options);

	return this.each(function(){
		// establish elements
		var el = $(this);
		var vp = el.children('.viewport');
		var us = vp.children('.universe');

		var i = options.i;

		if(i==''){
			i = el.attr('brandscroll_settings');
		}

		var s = brandscroll_settings[i];

		for (var c in options){
			if(options[c]==''){
				options[c]=s[c];
			}
		}

		// get width of universe
		var uswidth = us.outerWidth(true);

		// get viewport width
		var vpwidth = vp.outerWidth();

		// get current position
		var thisleft = us.position().left;

		// integify
		options.force = options.force-1+1;
		thisleft = thisleft-1+1;

		var speed = options.speed;

		if(options.direction=='right'){
			// get moveleft value
			var ml = thisleft-options.force;

			// cycle
			if(options.cycle){
				if(ml == (-(uswidth-vpwidth)-(options.force))) {
					// reset
					ml = 0;
					speed = options.rewindspeed;
				}
			}

			if((ml*-1)>uswidth-vpwidth){
				ml = -(uswidth-vpwidth);
			}

		} else {
			// move left
			// get moveleft value
			var ml = thisleft+options.force;

			// cycle
			if(options.cycle){
				if((ml*-1)==(-options.force)){
					ml = (uswidth-vpwidth);
					ml = ml*-1;
					speed = options.rewindspeed;
				}
			}
			// see if its greater than end.
			if(ml>0){
				ml = 0;
			}
		}

		ml = Math.floor(ml);

		if(options.stopqueue){
			us.stop(true);
		}

		us.animate({
			left : ml+'px'
		}, {queue : true, duration : speed});

		el.brandscroll_pause();

		var waitspeed = speed;
		if(speed==options.rewindspeed){
			waitspeed += (options.rewindspeed/2);
		}

		brandscroll_settings[i]['movetimer'] = setTimeout(function(){
			el.brandscroll_resume();
		}, waitspeed);

	});

};


$.fn.brandscroll_pause = function(options){

	var options = $.extend({
		i : ''
	}, options);

	return this.each(function(){

		var el = $(this);
		var i = options.i;

		if(i==''){
			i = el.attr('brandscroll_settings');
		}

		var us = el.find('.universe');

		// we have enough info to re-start the
		// interval so we can just clear it here
		clearInterval(brandscroll_settings[i]['interval']);
		clearTimeout(brandscroll_settings[i]['movetimer']);

	});

};

$.fn.brandscroll_resume = function(options){

	var options = $.extend({
		i : ''
	}, options);

	return this.each(function(){
		var el = $(this);
		var i = options.i;

		if(i==''){
			i = el.attr('brandscroll_settings');
		}

		var s = brandscroll_settings[i];

		// we will restart the interval from the saved settings
		if(s.autoplay){
			brandscroll_settings[i]['interval'] = setInterval(function(){
				el.brandscroll_move({
					force : s.force,
					cycle : s.cycle,
					i : i,
					speed : s.speed
				});
			}, s.autoplayinterval);
		}

	});
};

$.fn.brandscroll_button = function(options){

	var options = $.extend({
		direction : 'right',
		el : '',
		force : '',
		stopqueue : true
	}, options);

	return this.each(function(){
		var el = $(this);

		if(options.el == ''){
			alert('Please provide the el option. This can be a normal jquery css reference to the brandscroll element.');
		}

		var e = $(options.el);
		var i = e.attr('brandscroll_settings');
		var s = brandscroll_settings[i];

		for (var c in options){
			if(options[c]==''){options[c]==s[c];}
		}

		el.click(function(){
			e.brandscroll_move(options);
			return false;
		});

	});
};

// #jcmarquee
// similar setup to brandscroll
// more refined _action function
// need to add mover buttons
$.fn.jcmarquee = function(options){

	var options = $.extend({
		speed : 100,  // per 1000 pixels to provide consistency // 100ms/1000px
		autocenter : true,
		autowidth : true,
		loop : true,
		direction : 'left',
		pauseonhover : true
	}, options);
	
	return this.each(function(){
	
		var el = $(this);
		var i = 'jcmarquee_'+Math.floor(Math.random()*1021930);
		el.attr('jcmarquee', i);
		
		jcmarquee[i] = Array;
		jcmarquee[i].options = options;
		
		// positioning
		if(el.css('position')!='absolute'){
			el.css('position', 'relative');
		}
		
		// create viewport
		el.wrapInner('<div class="viewport"></div>');
		var vp = el.find('.viewport:first');
		
		// create universe
		vp.wrapInner('<div class="universe"></div>');
		var us = el.find('.universe:first');
		
		// css viewport
		vp.css({
			'position' : 'absolute',
			'width' : '100%',
			'height' : '100%',
			'overflow' : 'hidden',
			'left' : 0,
			'top' : 0
		});
		
		// css universe
		us.css('position' , 'absolute');
		
		if(options.direction == 'right'){
			var cssoptions = {
				'left' : -vp.outerWidth()+'px'
			};
		} else {
			var cssoptions = {
				'right' : -us.outerWidth()+'px'
			};		
		}
		
		// autowidth?
		if(options.autowidth){
			cssoptions.width = us.outerWidth()+'px';
		}
		
		// autocenter?
		if(options.autocenter){
			cssoptions.top = (vp.outerHeight()-us.outerHeight())/2+'px';
		}
		
		// final css application
		us.css(cssoptions);
		
		// get us width for other calcs
		var uswidth = us.outerWidth();
		
		// calculate speed
		var speed = (options.speed/1000);
		speed = uswidth/speed;
		speed = Math.floor(speed);
		
		// store speed
		jcmarquee[i]['storespeed'] = speed;
		
		// anim function
		function anim () {
			el.addClass('refreshthis'+i);
			el.removeClass('refreshthis'+i);
			
			if(options.direction == 'right'){
				// stop
				us.stop(true).css('left', -us.outerWidth()+'px');
	
				// start animation
				us.animate({
					left : vp.outerWidth()+'px'
				},{
					queue : false,
					duration : speed,
					easing : 'linear'
				});	

			} else {
				// stop
				us.stop(true).css('right', -us.outerWidth()+'px');
	
				// start animation
				us.animate({
					right : vp.outerWidth()+'px'
				},{
					queue : false,
					duration : speed,
					easing : 'linear'
				});	
			}
		}
			
		// start
		anim();
		
		// loop?
		if(options.loop){
			jcmarquee[i]['loop'] = setInterval(function(){
				anim();
			}, speed);
		}
		
		// pause on mouseover?
		if(options.pauseonhover){
			vp.hover(function(){
				el.jcmarquee_action({
					action : 'pause'
				});
			}, function(){
				el.jcmarquee_action({
					action : 'resume'
				});
			});
		}
		

		
	});
	
};


$.fn.jcmarquee_action = function(options){

	var options = $.extend({
		action : ''
	}, options);
	
	return this.each(function(){
		var el = $(this);
		// get i
		var i = el.attr('jcmarquee');
		// get opts
		var opts = jcmarquee[i]['options'];
		
		// set vars
		var us = el.find('.universe:first');
		var vp = el.find('.viewport:first');
		
		// pause
		if(options.action=='pause'){
		
			// stop us
			us.stop(true);
			// stop timer
			clearInterval(jcmarquee[i]['loop']);
			clearTimeout(jcmarquee[i]['timeout']);
		
		}
		
		if(options.action=='resume'){

			clearInterval(jcmarquee[i]['loop']);
			clearTimeout(jcmarquee[i]['timeout']);			
			
			// got to do some beastin calculations
			us.stop(true);
			
			// basically find out how much of us is still to be animated
			var togo = 0;
			
			if(opts.direction == 'left'){
				// using css right
				togo = vp.outerWidth()-us.position().left;
				togo = us.outerWidth()-togo;
			} else {
				togo = us.position().left*-1;
				togo = togo+vp.outerWidth();
			}
			
			if(togo<0){togo=togo*-1;}
			
			// calculate speed
			var speed = (opts.speed/1000);
			speed = togo/speed;
			speed = Math.floor(speed);
			
			el.addClass('refreshthis'+i);
			el.removeClass('refreshthis'+i);
			
			// then fire of an anim
			if(opts.direction == 'right'){		
				// start animation
				us.animate({
						left : vp.outerWidth()+'px'
				}, {
					queue : false,
					duration : speed,
					easing : 'linear'
				});
				
			} else {
				// start animation
				us.animate({
					right : vp.outerWidth()+'px'
				}, {
					queue : false,
					duration : speed,
					easing : 'linear'
				});
			}
			
			function anim () {
				el.addClass('refreshthis'+i);
				el.removeClass('refreshthis'+i);
				if(opts.direction == 'right'){
					// stop
					us.stop(true).css('left', -us.outerWidth()+'px');
	
					// start animation
					us.animate({
						left : vp.outerWidth()+'px'
					},{
						queue : false,
						duration : jcmarquee[i]['storespeed'],
						easing : 'linear'
					});
	
				} else {
					// stop
					us.stop(true).css('right', -us.outerWidth()+'px');
	
					// start animation
					us.animate({
						right : vp.outerWidth()+'px'
					},{
						queue : false,
						duration : jcmarquee[i]['storespeed'],
						easing : 'linear'
					});
				}

			}
			
			// loop?		
			if(opts.loop){
				// then fire off a settimeout
				jcmarquee[i]['timeout'] = setTimeout(function(){
					anim();
					// then within this set up the new loop
					jcmarquee[i]['loop'] = setInterval(anim, jcmarquee[i]['storespeed']);
				
				}, speed);
			
			} 
			
		} // end resume
		
			
	});
	


};
