/*
 * jQuery Tools 1.2.3 - The missing UI library for the Web
 * 
 * [tooltip, tooltip.slide, tooltip.dynamic, overlay, overlay.apple]
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/
 * 
 * File generated: Tue Jul 27 11:43:42 GMT 2010
 */
(function(f){function p(a,b,c){var h=c.relative?a.position().top:a.offset().top,e=c.relative?a.position().left:a.offset().left,i=c.position[0];h-=b.outerHeight()-c.offset[0];e+=a.outerWidth()+c.offset[1];var j=b.outerHeight()+a.outerHeight();if(i=="center")h+=j/2;if(i=="bottom")h+=j;i=c.position[1];a=b.outerWidth()+a.outerWidth();if(i=="center")e-=a/2;if(i=="left")e-=a;return{top:h,left:e}}function t(a,b){var c=this,h=a.add(c),e,i=0,j=0,m=a.attr("title"),q=n[b.effect],k,r=a.is(":input"),u=r&&a.is(":checkbox, :radio, select, :button, :submit"),
s=a.attr("type"),l=b.events[s]||b.events[r?u?"widget":"input":"def"];if(!q)throw'Nonexistent effect "'+b.effect+'"';l=l.split(/,\s*/);if(l.length!=2)throw"Tooltip: bad events configuration for "+s;a.bind(l[0],function(d){clearTimeout(i);if(b.predelay)j=setTimeout(function(){c.show(d)},b.predelay);else c.show(d)}).bind(l[1],function(d){clearTimeout(j);if(b.delay)i=setTimeout(function(){c.hide(d)},b.delay);else c.hide(d)});if(m&&b.cancelDefault){a.removeAttr("title");a.data("title",m)}f.extend(c,{show:function(d){if(!e){if(m&&b.ignoreTitle==false)e=
f(b.layout).addClass(b.tipClass).appendTo(document.body).hide().append(m);else if(b.tip)e=f(b.tip).eq(0);else{e=a.next();e.length||(e=a.parent().next())}if(!e.length)throw"Cannot find tooltip for "+a;}if(c.isShown())return c;e.stop(true,true);var g=p(a,e,b);d=d||f.Event();d.type="onBeforeShow";h.trigger(d,[g]);if(d.isDefaultPrevented())return c;g=p(a,e,b);e.css({position:"absolute",top:g.top,left:g.left});k=true;q[0].call(c,function(){d.type="onShow";k="full";h.trigger(d)});g=b.events.tooltip.split(/,\s*/);
e.bind(g[0],function(){clearTimeout(i);clearTimeout(j)});g[1]&&!a.is("input:not(:checkbox, :radio), textarea")&&e.bind(g[1],function(o){o.relatedTarget!=a[0]&&a.trigger(l[1].split(" ")[0])});return c},hide:function(d){if(!e||!c.isShown())return c;d=d||f.Event();d.type="onBeforeHide";h.trigger(d);if(!d.isDefaultPrevented()){k=false;n[b.effect][1].call(c,function(){d.type="onHide";k=false;h.trigger(d)});return c}},isShown:function(d){return d?k=="full":k},getConf:function(){return b},getTip:function(){return e},
getTrigger:function(){return a}});f.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","),function(d,g){f.isFunction(b[g])&&f(c).bind(g,b[g]);c[g]=function(o){f(c).bind(g,o);return c}})}f.tools=f.tools||{version:"1.2.3"};f.tools.tooltip={conf:{effect:"toggle",fadeOutSpeed:"fast",predelay:0,delay:30,opacity:1,tip:0,position:["top","center"],offset:[0,0],relative:false,ignoreTitle:false,cancelDefault:true,events:{def:"mouseenter,mouseleave",input:"focus,blur",widget:"focus mouseenter,blur mouseleave",tooltip:"mouseenter,mouseleave"},
layout:"<div/>",tipClass:"tooltip"},addEffect:function(a,b,c){n[a]=[b,c]}};var n={toggle:[function(a){var b=this.getConf(),c=this.getTip();b=b.opacity;b<1&&c.css({opacity:b});c.show();a.call()},function(a){this.getTip().hide();a.call()}],fade:[function(a){var b=this.getConf();this.getTip().fadeTo(b.fadeInSpeed,b.opacity,a)},function(a){this.getTip().fadeOut(this.getConf().fadeOutSpeed,a)}]};f.fn.tooltip=function(a){var b=this.data("tooltip");if(b)return b;a=f.extend(true,{},f.tools.tooltip.conf,a);
if(typeof a.position=="string")a.position=a.position.split(/,?\s/);this.each(function(){b=new t(f(this),a);f(this).data("tooltip",b)});return a.api?b:this}})(jQuery);
(function(d){var i=d.tools.tooltip;d.extend(i.conf,{direction:"up",bounce:false,slideOffset:10,slideInSpeed:200,slideOutSpeed:200,slideFade:!d.browser.msie});var e={up:["-","top"],down:["+","top"],left:["-","left"],right:["+","left"]};i.addEffect("slide",function(g){var a=this.getConf(),f=this.getTip(),b=a.slideFade?{opacity:a.opacity}:{},c=e[a.direction]||e.up;b[c[1]]=c[0]+"="+a.slideOffset;a.slideFade&&f.css({opacity:0});f.show().animate(b,a.slideInSpeed,g)},function(g){var a=this.getConf(),f=a.slideOffset,
b=a.slideFade?{opacity:0}:{},c=e[a.direction]||e.up,h=""+c[0];if(a.bounce)h=h=="+"?"-":"+";b[c[1]]=h+"="+f;this.getTip().animate(b,a.slideOutSpeed,function(){d(this).hide();g.call()})})})(jQuery);
(function(g){function j(a){var c=g(window),d=c.width()+c.scrollLeft(),h=c.height()+c.scrollTop();return[a.offset().top<=c.scrollTop(),d<=a.offset().left+a.width(),h<=a.offset().top+a.height(),c.scrollLeft()>=a.offset().left]}function k(a){for(var c=a.length;c--;)if(a[c])return false;return true}var i=g.tools.tooltip;i.dynamic={conf:{classNames:"top right bottom left"}};g.fn.dynamic=function(a){if(typeof a=="number")a={speed:a};a=g.extend({},i.dynamic.conf,a);var c=a.classNames.split(/\s/),d;this.each(function(){var h=
g(this).tooltip().onBeforeShow(function(e,f){e=this.getTip();var b=this.getConf();d||(d=[b.position[0],b.position[1],b.offset[0],b.offset[1],g.extend({},b)]);g.extend(b,d[4]);b.position=[d[0],d[1]];b.offset=[d[2],d[3]];e.css({visibility:"hidden",position:"absolute",top:f.top,left:f.left}).show();f=j(e);if(!k(f)){if(f[2]){g.extend(b,a.top);b.position[0]="top";e.addClass(c[0])}if(f[3]){g.extend(b,a.right);b.position[1]="right";e.addClass(c[1])}if(f[0]){g.extend(b,a.bottom);b.position[0]="bottom";e.addClass(c[2])}if(f[1]){g.extend(b,
a.left);b.position[1]="left";e.addClass(c[3])}if(f[0]||f[2])b.offset[0]*=-1;if(f[1]||f[3])b.offset[1]*=-1}e.css({visibility:"visible"}).hide()});h.onBeforeShow(function(){var e=this.getConf();this.getTip();setTimeout(function(){e.position=[d[0],d[1]];e.offset=[d[2],d[3]]},0)});h.onHide(function(){var e=this.getTip();e.removeClass(a.classNames)});ret=h});return a.api?ret:this}})(jQuery);
(function(a){function t(d,b){var c=this,i=d.add(c),o=a(window),k,f,m,g=a.tools.expose&&(b.mask||b.expose),n=Math.random().toString().slice(10);if(g){if(typeof g=="string")g={color:g};g.closeOnClick=g.closeOnEsc=false}var p=b.target||d.attr("rel");f=p?a(p):d;if(!f.length)throw"Could not find Overlay: "+p;d&&d.index(f)==-1&&d.click(function(e){c.load(e);return e.preventDefault()});a.extend(c,{load:function(e){if(c.isOpened())return c;var h=q[b.effect];if(!h)throw'Overlay: cannot find effect : "'+b.effect+
'"';b.oneInstance&&a.each(s,function(){this.close(e)});e=e||a.Event();e.type="onBeforeLoad";i.trigger(e);if(e.isDefaultPrevented())return c;m=true;g&&a(f).expose(g);var j=b.top,r=b.left,u=f.outerWidth({margin:true}),v=f.outerHeight({margin:true});if(typeof j=="string")j=j=="center"?Math.max((o.height()-v)/2,0):parseInt(j,10)/100*o.height();if(r=="center")r=Math.max((o.width()-u)/2,0);h[0].call(c,{top:j,left:r},function(){if(m){e.type="onLoad";i.trigger(e)}});g&&b.closeOnClick&&a.mask.getMask().one("click",
c.close);b.closeOnClick&&a(document).bind("click."+n,function(l){a(l.target).parents(f).length||c.close(l)});b.closeOnEsc&&a(document).bind("keydown."+n,function(l){l.keyCode==27&&c.close(l)});return c},close:function(e){if(!c.isOpened())return c;e=e||a.Event();e.type="onBeforeClose";i.trigger(e);if(!e.isDefaultPrevented()){m=false;q[b.effect][1].call(c,function(){e.type="onClose";i.trigger(e)});a(document).unbind("click."+n).unbind("keydown."+n);g&&a.mask.close();return c}},getOverlay:function(){return f},
getTrigger:function(){return d},getClosers:function(){return k},isOpened:function(){return m},getConf:function(){return b}});a.each("onBeforeLoad,onStart,onLoad,onBeforeClose,onClose".split(","),function(e,h){a.isFunction(b[h])&&a(c).bind(h,b[h]);c[h]=function(j){a(c).bind(h,j);return c}});k=f.find(b.close||".close");if(!k.length&&!b.close){k=a('<a class="close"></a>');f.prepend(k)}k.click(function(e){c.close(e)});b.load&&c.load()}a.tools=a.tools||{version:"1.2.3"};a.tools.overlay={addEffect:function(d,
b,c){q[d]=[b,c]},conf:{close:null,closeOnClick:true,closeOnEsc:true,closeSpeed:"fast",effect:"default",fixed:!a.browser.msie||a.browser.version>6,left:"center",load:false,mask:null,oneInstance:true,speed:"normal",target:null,top:"10%"}};var s=[],q={};a.tools.overlay.addEffect("default",function(d,b){var c=this.getConf(),i=a(window);if(!c.fixed){d.top+=i.scrollTop();d.left+=i.scrollLeft()}d.position=c.fixed?"fixed":"absolute";this.getOverlay().css(d).fadeIn(c.speed,b)},function(d){this.getOverlay().fadeOut(this.getConf().closeSpeed,
d)});a.fn.overlay=function(d){var b=this.data("overlay");if(b)return b;if(a.isFunction(d))d={onBeforeLoad:d};d=a.extend(true,{},a.tools.overlay.conf,d);this.each(function(){b=new t(a(this),d);s.push(b);a(this).data("overlay",b)});return d.api?b:this}})(jQuery);
(function(i){function j(b){var d=b.offset();return{top:d.top+b.height()/2,left:d.left+b.width()/2}}var k=i.tools.overlay,f=i(window);i.extend(k.conf,{start:{top:null,left:null},fadeInSpeed:"fast",zIndex:9999});function n(b,d){var a=this.getOverlay(),c=this.getConf(),g=this.getTrigger(),o=this,l=a.outerWidth({margin:true}),h=a.data("img");if(!h){var e=a.css("backgroundImage");if(!e)throw"background-image CSS property not set for overlay";e=e.slice(e.indexOf("(")+1,e.indexOf(")")).replace(/\"/g,"");
a.css("backgroundImage","none");h=i('<img src="'+e+'"/>');h.css({border:0,display:"none"}).width(l);i("body").append(h);a.data("img",h)}e=c.start.top||Math.round(f.height()/2);var m=c.start.left||Math.round(f.width()/2);if(g){g=j(g);e=g.top;m=g.left}h.css({position:"absolute",top:e,left:m,width:0,zIndex:c.zIndex}).show();b.top+=f.scrollTop();b.left+=f.scrollLeft();b.position="absolute";a.css(b);h.animate({top:a.css("top"),left:a.css("left"),width:l},c.speed,function(){if(c.fixed){b.top-=f.scrollTop();
b.left-=f.scrollLeft();b.position="fixed";h.add(a).css(b)}a.css("zIndex",c.zIndex+1).fadeIn(c.fadeInSpeed,function(){o.isOpened()&&!i(this).index(a)?d.call():a.hide()})})}function p(b){var d=this.getOverlay().hide(),a=this.getConf(),c=this.getTrigger();d=d.data("img");var g={top:a.start.top,left:a.start.left,width:0};c&&i.extend(g,j(c));a.fixed&&d.css({position:"absolute"}).animate({top:"+="+f.scrollTop(),left:"+="+f.scrollLeft()},0);d.animate(g,a.closeSpeed,b)}k.addEffect("apple",n,p)})(jQuery);

// simple plugin to bind callbacks to $.enter()
(function ($) {
	$.fn.enter = function (callback) {
		return this.each(function () {
			$(this).keyup(function (e) {
				if (e.keyCode === 13 && typeof callback === 'function') {
					callback($(this));
				};
			});
		});
	};
})(jQuery);

// flow control for the chain
(function ($) {
	$.fn.iftrue = function (condition) {
		return (condition) ? this : $('#'+Math.random());
	};
})(jQuery);

/**
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
		// setting the path didn't make sense.  fixed @jalley
        var path = '; path=' + (options.path ? options.path : '/');
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*
* --------------------------------------------------
* new cart functionality -- replaces lib_cart_jquery
* --------------------------------------------------
*/

function post_and_update (args, target) {
	$.post('/shop.php', args, function (ret) {
		$(target).html(ret);
	});
}


/*
* ratings and reviews
* @TODO destroy antiquated system with prejudice
*/ 
function checkCharLength (objEvent, objField, intLimit) {
	if (objEvent.which)
		var intKeycode = objEvent.which; // mozilla
	else 
		var intKeycode = objEvent.keyCode; // ie

	if (objField.value.length >= intLimit &&
		((intKeycode >= 48 && intKeycode <= 57)
		|| (intKeycode >= 65 && intKeycode <= 90)
		|| (intKeycode == 9)
		|| (intKeycode == 13)
	)) {
		return false
	}

	return true;
}
function valFormField (objForm, strFieldId, blnExtraCriteria, strErrorMsg) {

	if (blnExtraCriteria == undefined || blnExtraCriteria == null) blnExtraCriteria = true;

	var objErrorMsg = $("#" + strFieldId + "Error");
	var objField = $(objForm).find('#' + strFieldId);

	if (!objErrorMsg.length) {
		alert("Error message container does not exist for field "+strFieldId);
		return;
	}

	if (objField.type == "select-one") {
		strValue = objField.options[objField.selectedIndex].value;
	}
	else if (objField.length > 0) {
		var opt = $(objField).find('option:checked');
		strValue = opt?opt.val():"";
	}
	else {
		strValue = objField.value;
	}

	if (strValue == "" || !blnExtraCriteria) {
		if (strErrorMsg != undefined && strErrorMsg != null) {
			objErrorMsg.innerHTML = strErrorMsg;
		}

		objErrorMsg.show();
		$(objForm).data('blnValid', false);
		
		return false;
	}
	else {
		objErrorMsg.hide();

		return true;
	}

}


/*
* product option selecting and sku building
* @eventually redo this ported js and make no JS necessary
*/
function build_skus (form) {
	var skus = [];

	for (var i = 0; i < form.elements.length; i++) {
		var field = form.elements[i];
		var value = '';

		if (!field.name) continue;

		if (form.elements[field.name].options) {
			if (field.type === 'select-one') {
				value = field.options[field.selectedIndex].value;
			}
			else {
				var vals = [];
				for (var n = 0; n < field.options.length; n++) {
					if (field.options[n].selected) {
						vals[vals.length] = field.options[n].value;
					}
				}

				value = vals;
			}
		}
		else {
			value = field.value;
		}

		value = value.split('|')[0];
		
		var matches = field.name.match(/^Option_(\w+?)(\d*)$/);
		if (matches) {
			var optgroup = (matches[2]) ? matches[2] : 1;

			if (!skus[optgroup - 1]) {
				skus[optgroup - 1] = '';
			}
			
			if (value.length === 6) {
				// not really an option, but a full SKU, so treat it as so
				skus.push(value);
			} else {
				skus[optgroup - 1] += value;
			}
		}

		var matches = field.name.match(/^SKU_(\w+?)(\d*)$/);
		if (matches) {
			skus[skus.length] = value;
		}
	}

	if (form.elements.strBaseSKUs.value) {
		var baseSKUs = $('input[name=strBaseSKUs]', form).val();
		var optionSKUs = skus.join(',');
		skus = [baseSKUs, optionSKUs].join(',');

		$('input[name=strSKUs]', form).val(skus);
	}

	return skus;
}

function check_quantity (e) {
	if ($(e).val() <= 0) {
		alert('Quantity must be greater than 0!');
		$(e).focus().val(1);
	}
}


/*
*  view cart page
*/

$('#view-cart-form').submit(function (e) {
	e.preventDefault();
	return false;
});

function update_cart_list () {
	post_and_update($('#view-cart-form').serialize(), '#view-cart');
};

// quantity field interaction
function sanitize_quantity (e) {
	$(e).val($(e).val().replace(/[^0-9]/g, ''));
}
function update_quantity (e, limit) {
	if (limit > 0 && $(e).val() > limit) {
		alert('Quantity can not be greater than ' + limit);
		$(e).val(limit).focus();
		update_cart_list();
	}
	if ($(e).val() <= 0) {
		alert('Quantity must be greater than 0');
		$(e).val('1').focus();
		update_cart_list();
	}
	else {
		update_cart_list();
	}
}

// remove from cart
function remove_cart (index) {
	post_and_update('action=remove&index=' + index, '#view-cart');
}

$(function() {
	$('#nav td:has(.nav-categories-container)').hover(
		function() {
			$(this).find('.nav-categories-container').stop(true, true).fadeIn();	
			$(this).find(".category-list")	.addClass('current');
			updateCurrentPage();
		},
		function() {
			$(".category-list").removeClass('current');
			$(this).find('.nav-categories-container').stop(true, true).fadeOut();				
		}
	);
	
	$('.prev-cats').click(function() {
		if ($(".category-list.current").position().left + 890 >= 0) {
			$(".category-list.current").stop(true, true).animate({ left: "0" }, 500, "easeOutQuint", function() {
				updateCurrentPage();
			});

		} else {
			$(".category-list.current").stop(true, true).animate({ left: "+=890" }, 500, "easeOutQuint", function() {
				updateCurrentPage();
			});
		}
		
	});
	$('.next-cats').click(function() {
		if ( $(".category-list.current").width() <= -1 * $(".category-list.current").position().left + 890 + 35) {
			$(".category-list.current").stop(true, true).animate({ left: "0" }, 500, "easeInQuint", function() {
				updateCurrentPage();
			});
		} else {
			$(".category-list.current").stop(true, true).animate({ left: "-=890" }, 500, "easeOutQuint", function() {
				updateCurrentPage();				
			});
		}
	});
	
});

function updateCurrentPage() {
	var current_page = Math.ceil(-1 * $(".category-list.current").position().left /  890);

	if (current_page > 0) {
		$('.category-list.current').parent().parent().find('.prev-cats').css('pointer-events', 'auto');
		$('.category-list.current').parent().parent().find('.prev-cats').css('opacity', '0.6');
	} else if (current_page == 0) {
		$('.category-list.current').parent().parent().find('.prev-cats').css('opacity', '0');
		$('.category-list.current').parent().parent().find('.prev-cats').css('pointer-events', 'none');
	}
	
	if (current_page < $('.category-list.current').parent().parent().find('.page').length -1) {
		$('.category-list.current').parent().parent().find('.next-cats').css('pointer-events', 'auto');
		$('.category-list.current').parent().parent().find('.next-cats').css('opacity', '0.6');
	} else {
		$('.category-list.current').parent().parent().find('.next-cats').css('opacity', '0');
		$('.category-list.current').parent().parent().find('.next-cats').css('pointer-events', 'none');
	}

	$('.category-list.current').parent().parent().find('.page').removeClass('current');
	$('.page:eq('+current_page+')', $('.category-list.current').parent().parent()).addClass('current');
}

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}
$(function () {
	// toolbar tooltips
	$('#toolbar a.socialize').tooltip({
		  effect:      'slide'
		, ignoreTitle: true
		, position:    'top center'
		, relative:    true
		, delay:       130
	});

	// intro video colorbox action
	$(function () {
		$('#whatisafl').colorbox({
			iframe: true,
			innerWidth: 320,
			innerHeight: 240,
			href: $('#whatisafl').data('href')
		});
		$('#howdoesitwork').colorbox({
			iframe: true,
			innerWidth: 682,
			innerHeight: 455,
			href: $('#howdoesitwork').data('href')
		});
		$('#seeit').colorbox({
			iframe: true,
			innerWidth: 445,
			innerHeight: 296,
			href: $('#seeit').data('href')
		});

	});

	$('#signup-email').on('focus', function() {
	    if ($(this).val() == 'My email is') {
		$(this).val('');
	    }
	});
	$('#signup-email').on('blur', function() {
	    if ($(this).val() == '') {
		$(this).val('My email is');
	    }
	});

});

var region = {
	  country:  ''
	, language: ''
	, set_country: function (v) {
		region.country = v;
		$('#region-tool .countries').fadeOut('fast', function () {
			$('#region-tool .languages').fadeIn('fast');
		});
	}
	, set_language: function (v) {
		region.language = v;
		region.redirect();
	}
	, load: function () {
		$('#region-tool').load('/includes/regional_settings_tool.php', function () {
			$(this).fadeIn('fast');
		});
	}
	, redirect: function () {
		$('#region-tool').fadeOut('fast', function () {
			//window.location = '/?geoCountryCode=' + region.country + '&lang=' + region.language;
			window.location = '/?lang=' + region.language;
		});
	}
	, close: function () {
		$('#region-tool').fadeOut('fast');
	}
};

String.prototype.htmlspecialchars = function ()	{
        return this.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
};

$(function () {

	// search functionality in header
	$('#utility a.search').mouseenter(function () {
		/*
		$('#q').show().animate({
			width: '80px'
		}, 300);
		*/
	}).click(function () {
		document.location = '/search/?q=' + $('#q').val();
	});
	$('#q').enter(function () {
		$('#utility a.search').click();
	}).val('search').focus(function () {
		if ($(this).val() == 'search') $(this).val('');
		$(this).css('color', '#000');
	}).click(function () {
		$(this).css('color', '#000');
	}).css('color', '#999');
	
	$('#signup-email').blur(function () {
		if ($(this).attr('value') == '') {
			$(this).attr('value', 'Email Signup');
		} 
	});

	$('#signup-email').focus(function () {
		$(this).attr('value', '');
		//$(this).attr('value', '').unbind('focus');
		// pop up a stupid box
	}).enter(function () {
		$('#signup-button').click();
	});

	$('#signup-button').click(function() {
	    $('#can-spam-content').data('source', 'toolbar');
	});

	// better breadcrumbing share feature
	$('#better-breadcrumbs .icon-share').click(function () {
		$(this).parent().find('.share-panel').toggle('fast');
	});

	// homepage & subcategory tiles
	$('.item-tile').click(function () {
		window.location = $(this).find('.bar a').attr('href');
	});

	// see it in action & see how it works
	$('.see-how-it-works').colorbox(    {iframe: true, innerWidth: 640, innerHeight: 385});
	$('.see-it-in-action-new').colorbox({iframe: true, innerWidth: 450, innerHeight: 300});

	// generic youtube embeds
	$('.youtube-video').colorbox({iframe: true, innerWidth: 853, innerHeight: 480});

	// generic colorbox init
	$('.colorbox').colorbox({scalePhotos:true, maxHeight:600});

	// generic videos.fleshlight colorbox init
	$('.videos-fleshlight').colorbox({
		innerHeight: '390px'
		, onComplete: function () {
			$('#colorbox').addClass('videos-fleshlight');
			$('#cboxTitle').css({
				'text-align': 'left'
			}).html('<a href="http://videos.fleshlight.com/" target="_blank"><img src="//static.fleshlight.com/images/video-banner.jpg" /></a>');
		}
	});

	// free shipping floater
	/*
	$('#free-shipping').mouseenter(function () {
		$(this).css('z-index', 1);
		$('#free-shipping, #free-shipping .bar').stop().animate({'width': '42px'}, 150);
	}).mouseleave(function () {
		$('#free-shipping').stop().animate({'width': '39px'}, 150, function () {
			$('#free-shipping .bar').css('width', '39px');
			$(this).css('z-index', 0);
		});
	}).click(function () {
		$(this).animate({'width': '342px'}, 150);
	});
	*/
	$('#sale-ship').mouseenter(function () {
		$(this).css('z-index', 666);
		if ($('#sale-ship').width() < 500) {
			$('#sale-ship, #sale-ship .bar').stop().animate({'width': '42px'}, 150);
		}
	}).mouseleave(function () {
		$('#sale-ship').stop().animate({'width': '39px'}, 150, function () {
			$('#sale-ship .bar').css('width', '39px');
			$(this).css('z-index', 666);
		});
	}).click(function () {
		$(this).animate({'width': '500px'}, 150);
	});

	$('#weekly-special').mouseenter(function () {
		$(this).css('z-index', 666);
		$('#weekly-special, #weekly-special .bar').stop().animate({'width': '42px'}, 150);
	}).mouseleave(function () {
		$('#weekly-special').stop().animate({'width': '39px'}, 150, function () {
			$('#weekly-special .bar').css('width', '39px');
			$(this).css('z-index', 666);
		});
	}).click(function () {
		$(this).animate({'width': '500px'}, 150);
	});


	// any rel=external? target=blank it
	$('a[rel="external"]').attr('target', '_blank');

	// finally, run any fl onloads
	if (typeof fl !== 'undefined') {
		for (var i in fl.onload) {
			if (typeof fl.onload[i] === 'function') fl.onload[i].call();
		}
	}

	// is this webkit?  if so, change positioning of certain elements
	// make this execute after onload since pageshow and certain content elements come before
	if ($.inArray(navigator.platform, ['iPad', 'iPhone', 'iPod']) > -1)
	{
		$('#toolbar').css({position: 'static', display: 'block'});
		$('#toolbar-small, .pageshow-controls').hide();
		//$('#homepage-boxes').css({top: '790px'});
		$('#nav .navtip li > a').unbind('mouseenter');
	};

});




// === cookie functions lifted from:
// http://techpatterns.com/downloads/javascript_cookies.php
function setCookie( name, value, expires, path, domain, secure ) {
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime( today.getTime() );
        /*
        if the expires variable is set, make the correct
        expires time, the current script below will set
        it for x number of days, to make it for hours,
        delete * 24, for minutes, delete * 60 * 24
        */
  	if ( expires )
        {
        expires = expires * 1000 * 60 * 60 * 24;
        }
        var expires_date = new Date( today.getTime() + (expires) );
        
        document.cookie = name + "=" +escape( value ) +  
        ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
        ( ( path ) ? ";path=" + path : "" ) +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ( ( secure ) ? ";secure" : "" );
                
}


function getCookie( check_name ) {
        
        // first we'll split this cookie up into name/value pairs
        // note: document.cookie only returns name=value, not the other components
        var a_all_cookies = document.cookie.split( ';' );
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f
                
        for ( i = 0; i < a_all_cookies.length; i++ )
        {
                // now we'll split apart each name=value pair
                a_temp_cookie = a_all_cookies[i].split( '=' );
                // and trim left/right whitespace while we're at it
                cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
                // if the extracted name matches passed check_name
                if ( cookie_name == check_name )
                {
                        b_cookie_found = true;
                        // we need to handle case where cookie has no value but exists (no = sign, that is):
                        if ( a_temp_cookie.length > 1 )
                        {
                                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
                        }
                        // note that in cases where cookie is initialized but no value, null is returned
                        return cookie_value;
                        break;
                }
                a_temp_cookie = null;
                cookie_name = '';
        }
        if ( !b_cookie_found )
        {
                return null;
        }
}

function deleteCookie( name, path, domain ) {
        if ( Get_Cookie( name ) )
                document.cookie = name + "=" +
                        ( ( path ) ? ";path=" + path : "") +
                        ( ( domain ) ? ";domain=" + domain : "" ) +
                        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}



function basename(path) {
	return path.replace(/\\/g,'/').replace( /.*\//, '' );
}


function STATIC_HOST() {
	// Break up the HTTP host into parts.  ignore the 'www' part if it's there.
	var parts = [];
	var x = location.host.toLowerCase().split('.');
	for(i=0; i<x.length; i++) {
		if ( x[i] != 'www' && x[i] != 'naughtyamerica' ) {
			parts.push(x[i]);
		}
	}
	x = parts;

	return  ((x.length > 2)  ?  x[0] + '.'  :  '')
			+ 'static.'
			+ x.slice(-2).join('.');
}


// smooth scrolling
$(function() {
    $('a[href*=#]').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
        && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({scrollTop: targetOffset}, 1000);
                return false;
            }
        }
    });
});



// Handy date shit.
Date.prototype.is_between = function(date1,date2) {
	return  (date1 <= this && this <= date2) // The calling scope passed the dates in chronological order
			||
			(date2 <= this && this <= date1); // or maybe the silly caller mixed them up.  doesn't change the between-ness.
}

// generic video action
$(function () {
	$('.videos-fleshlight-cdn').colorbox({
		  iframe: true
		, innerWidth: 648
		, innerHeight:395 
	});
});

function updateURLParam(url, param, value) {
	var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i");
    if (url.match(re))
        return url.replace(re,'$1' + param + "=" + value + '$2');
    else
    	return url + url.indexOf('?') > 0 ? '&' : '?' + param + '=' + value;
}
