/**
 * Background position plugin
 * @author Alexander Farkas
 * v. 1.21
 */
(function($) {
	if(!document.defaultView || !document.defaultView.getComputedStyle){ // IE6-IE8
		var oldCurCSS = jQuery.curCSS;
		jQuery.curCSS = function(elem, name, force){
			if(name === 'background-position'){
				name = 'backgroundPosition';
			}
			if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
				return oldCurCSS.apply(this, arguments);
			}
			var style = elem.style;
			if ( !force && style && style[ name ] ){
				return style[ name ];
			}
			return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
		};
	}
	
	var oldAnim = $.fn.animate;
	$.fn.animate = function(prop){
		if('background-position' in prop){
			prop.backgroundPosition = prop['background-position'];
			delete prop['background-position'];
		}
		if('backgroundPosition' in prop){
			prop.backgroundPosition = '('+ prop.backgroundPosition;
		}
		return oldAnim.apply(this, arguments);
	};
	
	function toArray(strg){
		strg = strg.replace(/left|top/g,'0px');
		strg = strg.replace(/right|bottom/g,'100%');
		strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
		var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
		return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
	}
	
	$.fx.step. backgroundPosition = function(fx) {
		if (!fx.bgPosReady) {
			var start = $.curCSS(fx.elem,'backgroundPosition');
			
			if(!start){//FF2 no inline-style fallback
				start = '0px 0px';
			}
			
			start = toArray(start);
			
			fx.start = [start[0],start[2]];
			
			var end = toArray(fx.options.curAnim.backgroundPosition);
			fx.end = [end[0],end[2]];
			
			fx.unit = [end[1],end[3]];
			fx.bgPosReady = true;
		}
		//return;
		var nowPosX = [];
		nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
		nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           
		fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

	};
})(jQuery);

$(document).ready(function () {	

	var activeTab = 'info';

	$('#user_cont ul li a').click(function() {
										   
		// Change tab display
		var selid = $(this).closest('li').attr('id').substring(6);
		$('#user_info').css('display', 'none');
		$('#user_login').css('display', 'none');
		$('#user_register').css('display', 'none');
		$('#user_'+selid).css('display', 'block');
		
		if (selid == 'info') { $('#user_cont ul').css('background-position', '-1px -1px'); activeTab = 'info'; }
		if (selid == 'login') { $('#user_cont ul').css('background-position', '-1px -32px'); activeTab = 'login'; }
		if (selid == 'register') { $('#user_cont ul').css('background-position', '-1px -63px'); activeTab = 'register'; }
		
		return false;
	});
	
	/* Link text hovers */
	$('#u_tab_info a').mouseover(function() { if (activeTab != 'info') { $(this).css('background-position', '-463px -1px'); } });
	$('#u_tab_login a').mouseover(function() { if (activeTab != 'login') { $(this).css('background-position', '-559px -1px'); } });
	$('#u_tab_register a').mouseover(function() { if (activeTab != 'register') { $(this).css('background-position', '-620px -1px'); } });
	$('#u_tab_info a').mouseout(function() { $(this).css('background-position', '-232px -1px'); });
	$('#u_tab_login a').mouseout(function() { $(this).css('background-position', '-328px -1px'); });
	$('#u_tab_register a').mouseout(function() { $(this).css('background-position', '-389px -1px'); });
	
	/* Flash video player 
	
	/* swfobject.js */
	
	// Removed for SPAM appreciation weeke
	swfobject.embedSWF("/video/mojoVideoULTRA.swf?nocache=" + (new Date()).getTime()
, "top_vid", "464", "262", "9", {}, {streaming:"0", fileName: "http://spam.mojofuel.com/video/SPAM_teaser.flv"}, {allowScriptAccess:"always", allowFullScreen:true, wmode:"transparent"});
	//swfobject.embedSWF("/video/mojoVideoULTRA.swf", "top_vid", "464", "262", "9", {}, {streaming:"0", fileName: "http://spam.mojofuel.com/video/SPAM_appreciation.flv"}, {allowScriptAccess:"always", allowFullScreen:true, wmode:"transparent"});
	swfobject.embedSWF("/video/mojoVideoULTRA.swf?nocache=" + (new Date()).getTime()
, "press_vid_recipe", "464", "262", "9", {}, {streaming:"0", fileName: "http://spam.mojofuel.com/video/SPAM_teaser.flv"}, {allowScriptAccess:"always", allowFullScreen:true, wmode:"transparent"});
	swfobject.embedSWF("/video/mojoVideoULTRA.swf?nocache=" + (new Date()).getTime()
, "can-opening-video", "464", "262", "9", {}, {streaming:"0", fileName: "http://spam.mojofuel.com/video/SPAM-Can-Opening.flv"}, {allowScriptAccess:"always", allowFullScreen:true, wmode:"transparent"});
	
	swfobject.embedSWF("/video/mojoVideoULTRA.swf?nocache=" + (new Date()).getTime()
, "recipe_vid", "700", "394", "9", {}, {streaming:"0", fileName: "http://spam.mojofuel.com/video/SPAM_F8_Lg.flv"}, {allowScriptAccess:"always", allowFullScreen:true, wmode:"transparent"});

	/* Top product rotator on homepage */
	var rtImages = [ "spam_original.jpg", "spam_blackpepper.jpg", "spam_lite.jpg", "spam_fritters.jpg", "spam_bacon.jpg" ];
	var rtNames = [ "SPAM&trade; Original", "SPAM&trade; with Black Pepper", "SPAM&trade; Lite", "SPAM&trade; Fritters", "SPAM&trade; with real Bacon" ];
	var rtLinks = [ "original-spam", "spam-with-black-pepper", "spam-lite", "spam-fritters", "spam-with-real-bacon" ];
	var rtIndex = 0;
	
	function doRotate(nextIndex) {
		$('#prod_rot_controls p span').fadeOut(150);
		$('#top_prodrotator').css({backgroundPosition: "0 0"}).stop().animate({backgroundPosition:"(-460px 0)"}, {duration:500, complete:function() {
			$('#prod_rot_controls p span').html(rtNames[nextIndex]);
			$('#prod_rot_controls p span').fadeIn(300);		
			$(this).css({backgroundImage: "url(/images/elements/rotator/"+rtImages[nextIndex]+")", backgroundPosition: "460px 0"});
			$(this).animate({backgroundPosition:"0 0"}, {duration:500});
		}});
		$('#pr_overlay').attr("href", "http://www.spam-uk.com/products/"+rtLinks[nextIndex]);
	}
	
	$('#pr_next').click(function() {
		doRotate(rtIndex);
		rtIndex++;
		if (rtIndex > rtImages.length - 1) rtIndex = 0;
	});
	
	rtIndex = 1;
	
	
// IE5.5+ PNG Alpha Fix v2.0 Alpha: Background Tiling Support
// (c) 2008 Angus Turnbull http://www.twinhelix.com

// This is licensed under the GNU LGPL, version 2.1 or later.
// For details, see: http://creativecommons.org/licenses/LGPL/2.1/

var IEPNGFix = window.IEPNGFix || {};

IEPNGFix.tileBG = function(elm, pngSrc, ready) {
	// Params: A reference to a DOM element, the PNG src file pathname, and a
	// hidden "ready-to-run" passed when called back after image preloading.

	var data = this.data[elm.uniqueID],
		elmW = Math.max(elm.clientWidth, elm.scrollWidth),
		elmH = Math.max(elm.clientHeight, elm.scrollHeight),
		bgX = elm.currentStyle.backgroundPositionX,
		bgY = elm.currentStyle.backgroundPositionY,
		bgR = elm.currentStyle.backgroundRepeat;

	// Cache of DIVs created per element, and image preloader/data.
	if (!data.tiles) {
		data.tiles = {
			elm: elm,
			src: '',
			cache: [],
			img: new Image(),
			old: {}
		};
	}
	var tiles = data.tiles,
		pngW = tiles.img.width,
		pngH = tiles.img.height;

	if (pngSrc) {
		if (!ready && pngSrc != tiles.src) {
			// New image? Preload it with a callback to detect dimensions.
			tiles.img.onload = function() {
				this.onload = null;
				IEPNGFix.tileBG(elm, pngSrc, 1);
			};
			return tiles.img.src = pngSrc;
		}
	} else {
		// No image?
		if (tiles.src) ready = 1;
		pngW = pngH = 0;
	}
	tiles.src = pngSrc;

	if (!ready && elmW == tiles.old.w && elmH == tiles.old.h &&
		bgX == tiles.old.x && bgY == tiles.old.y && bgR == tiles.old.r) {
		return;
	}

	// Convert English and percentage positions to pixels.
	var pos = {
			top: '0%',
			left: '0%',
			center: '50%',
			bottom: '100%',
			right: '100%'
		},
		x,
		y,
		pc;
	x = pos[bgX] || bgX;
	y = pos[bgY] || bgY;
	if (pc = x.match(/(\d+)%/)) {
		x = Math.round((elmW - pngW) * (parseInt(pc[1]) / 100));
	}
	if (pc = y.match(/(\d+)%/)) {
		y = Math.round((elmH - pngH) * (parseInt(pc[1]) / 100));
	}
	x = parseInt(x);
	y = parseInt(y);

	// Handle backgroundRepeat.
	var repeatX = { 'repeat': 1, 'repeat-x': 1 }[bgR],
		repeatY = { 'repeat': 1, 'repeat-y': 1 }[bgR];
	if (repeatX) {
		x %= pngW;
		if (x > 0) x -= pngW;
	}
	if (repeatY) {
		y %= pngH;
		if (y > 0) y -= pngH;
	}

	// Go!
	this.hook.enabled = 0;
	if (!({ relative: 1, absolute: 1 }[elm.currentStyle.position])) {
		elm.style.position = 'relative';
	}
	var count = 0,
		xPos,
		maxX = repeatX ? elmW : x + 0.1,
		yPos,
		maxY = repeatY ? elmH : y + 0.1,
		d,
		s,
		isNew;
	if (pngW && pngH) {
		for (xPos = x; xPos < maxX; xPos += pngW) {
			for (yPos = y; yPos < maxY; yPos += pngH) {
				isNew = 0;
				if (!tiles.cache[count]) {
					tiles.cache[count] = document.createElement('div');
					isNew = 1;
				}
				var clipR = (xPos + pngW > elmW ? elmW - xPos : pngW),
					clipB = (yPos + pngH > elmH ? elmH - yPos : pngH);
				d = tiles.cache[count];
				s = d.style;
				s.behavior = 'none';
				s.left = xPos + 'px';
				s.top = yPos + 'px';
				s.width = clipR + 'px';
				s.height = clipB + 'px';
				s.clip = 'rect(' +
					(yPos < 0 ? 0 - yPos : 0) + 'px,' +
					clipR + 'px,' +
					clipB + 'px,' +
					(xPos < 0 ? 0 - xPos : 0) + 'px)';
				s.display = 'block';
				if (isNew) {
					s.position = 'absolute';
					s.zIndex = -999;
					if (elm.firstChild) {
						elm.insertBefore(d, elm.firstChild);
					} else {
						elm.appendChild(d);
					}
				}
				this.fix(d, pngSrc, 0);
				count++;
			}
		}
	}
	while (count < tiles.cache.length) {
		this.fix(tiles.cache[count], '', 0);
		tiles.cache[count++].style.display = 'none';
	}

	this.hook.enabled = 1;

	// Cache so updates are infrequent.
	tiles.old = {
		w: elmW,
		h: elmH,
		x: bgX,
		y: bgY,
		r: bgR
	};
};


IEPNGFix.update = function() {
	// Update all PNG backgrounds.
	for (var i in IEPNGFix.data) {
		var t = IEPNGFix.data[i].tiles;
		if (t && t.elm && t.src) {
			IEPNGFix.tileBG(t.elm, t.src);
		}
	}
};
IEPNGFix.update.timer = 0;

if (window.attachEvent && !window.opera) {
	window.attachEvent('onresize', function() {
		clearTimeout(IEPNGFix.update.timer);
		IEPNGFix.update.timer = setTimeout(IEPNGFix.update, 100);
	});
}

	
	/* Login/reg form validation */
	/* on username:
	
	,
					remote: "checkemail.php"
					
					*/
/* This doesn't work.					
	var regval = $('#regform').validate({
		rules: {
				reg_username: {
					required: true,
					email: true
				},
				reg_password: {
					required: true,
					minLength: 5
				},
				reg_confirmpassword: {
					required: true,
					minLength: 5,
					equalTo: "#reg_password"
				} 
		},
		messages: {
			reg_username: {
				required: "Please enter a valid email address",
				minLength: "Please enter a valid email address"
			},
			reg_password: {
				required: "Please specify a password",
				minlength: jQuery.format("Enter at least {0} characters")
			},
			reg_confirmpassword: {
				required: "Please specify a password",
				minlength: jQuery.format("Enter at least {0} characters"),
				equalTo: "Please ensure that both passwords match" 
			}
		}, 
        // the errorPlacement has to take the table layout into account 
        errorPlacement: function(error, element) { 
			error.appendTo( element.parent().next() );
			element.addClass('inputerror');
        }, 
        // specifying a submitHandler prevents the default submit, good for the demo 
		submitHandler: function() {
			alert("submitted!");
			return false;
		},
        // set this class to error-labels to indicate valid fields 
        success: function(label) { 
            // set   as text for IE 
            alert('All OK');
		}
	});*/
	
});