     	    
$(document).ready ( function() {
	
	if ( badBrowser() )
	{
		if ( confirm ( "You are using an unsupported browser.  The NAFC recommends Google Chrome.  Click OK to go to the Chrome download site." ) )
		{
			location = "http://www.google.com/chrome";
		}
		return;
	}
	
    $.getScript("https://platform.twitter.com/widgets.js");              
    $.getScript("https://apis.google.com/js/plusone.js"); 	
	preinit();
});	

var centerAll = function () { $(".centermiddle").each ( function ( ) { $(this).center() } );  }; 

function preinit ()
{
   	$('#logintop').corner('bl br 5px');
   	$('#footer').corner('tl tr 5px');
	$('#sidebar .blck').corner('3px');
	$('.block').corner("8px");
	$('h2,h1').corner("5px");//corner('6px');
	$('.productEntry').corner('6px');
	$('.productHeader').corner('tl bl 10px');
	
	$('#headerActions ul li a').corner('3px');
	//$('div.prodimg').corner('6px');

	$("#fuzz").css("height", "100%" );
	$("#fuzz").css("width", "100%" );
	$(".cartObject").corner("5px");

	centerAll(); $(window).resize ( centerAll );

	//$("#menu li a.clsWork").mouseenter ( showSubMenu );
	//$("#menu li a.clsCont").mouseenter ( showSubMenu );
	//$("#menu li a.clsCert").mouseenter ( showSubMenu );
	//$("#menu li a.clsResources").mouseenter ( showSubMenu );
	//$("#menu li>a.clsAbout").mouseenter ( showSubMenu );
	$("#menu li a").mouseenter ( showSubMenu  );
	$("#menu li").mouseleave ( hideSubMenu  );
	//$("#menu li a.clsWork").mouseenter ( showSubMenu );			
	//$("*").replaceText( /NAFC/gi, "<span class=\"nafctext\">NAFC</span>" );	   
	if ( typeof pageInit != "undefined" ) pageInit();
}

function showSubMenu ( )
{
	var pos = $(this).position();
	var parent = $(this).parent('li');
	var sub = parent.find("ul.submenubox");
	
	var header = parent.first();
	if ( parent.parent().hasClass("submenubox") ) header = parent.parent().parent().first();
	header.find('a:first').addClass("hover");
	
	if ( sub )
	{
		//sub.css ( "top", pos.top + 30 );
		//sub.css ( "left", pos.left );
		//$(this).css ( "z-index", 10);
		//sub.css ( "height", "200px" );
		//sub.css ( "display", "block" );	
		sub.show();
		//$(this).find("a").css ( "outline", "red solid 1px" );		
		
		//sub.mouseleave ( function () { sub.slideUp(100); } );
		//$(this).mouseleave ( function () { sub.hide(); } );
	}
}

function hideSubMenu ( )
{
	var pos = $(this).position();
	var parent = $(this);
	var sub = $(this).parent().find("ul.submenubox");
	
	var header = parent.first();
	if ( parent.parent().hasClass("submenubox") ) header = parent.parent().parent().first();
	header.find('a:first').removeClass("hover");
	
	if ( sub )
	{
		//sub.css ( "top", pos.top );
		//sub.css ( "left", pos.left );
		//$(this).css ( "z-index", 10);
		//sub.css ( "height", "200px" );
		//sub.css ( "display", "block" );	
		//sub.slideUp(200);
		sub.hide();
		//sub.css ( "outline", "red solid 1px" );		
		//sub.mouseleave ( function () { sub.slideUp(100); } );
		//$(this).mouseleave ( function () { sub.hide(); } );
	}
}

function setBusy ( flag )
{
	if ( flag )
	{
		$("#busy").css("height", "100%");
		$("#busy").fadeTo ( 200, .8 );
		//$("#busy").show();
	}
	else
	{		
		$("#busy").fadeTo( 200, 0,  function() { $("#busy").css("height", "1");	});	
		//$("#busy").hide();		
	}		
}
	
function postAction ( actionData, callback )
{
	if ( actionData['notBusy']!==true )
		setBusy ( true );
	
	//$("#nafcActionFrame")[0].contentWindow["postData"]();
	//return;
	//document.getElementById('nafcActionFrame').contentWindow.postData();
	//$.post("https://" + document.domain + "/action.php", actionData, function(data){
	$.post("/action.php", actionData, function(data){
		try
		{
			var obj = jQuery.parseJSON(data);
			if ( obj && obj.fatal )
			{
				setBusy ( false );
				showError ( obj.fatal );
			}
			else
			{								
				if ( actionData['stayBusy']!=true ) setBusy ( false );
				//if ( $("#debugDiv") ) $("#debugDiv").html ( data );
				//if ( typeof(console) != "undefined" ) console.debug ( data );
				callback ( obj );
			}
		}
		catch (e)
		{
			showError ( e );
			setBusy ( false );
		}
	});
}


function getAction ( actionData, callback )
{
	if ( actionData['notBusy']!==true )
		setBusy ( true );

	$.get("/action.php", actionData, function(data){
		try
		{
			var obj = jQuery.parseJSON(data);
			if ( obj && obj.fatal )
			{
				setBusy ( false );
				showError ( obj.fatal );
			}
			else
			{
				if ( actionData['stayBusy']!==true ) setBusy ( false );
				callback ( obj );
			}
		}
		catch (e)
		{
			showError ( e );
			setBusy ( false );
		}
	});
}

	
function showError ( error )
{ 
	showWindow ( '#divErrorArea' );
	$('#frmComment').val ( error );
}

function closeError ()
{
	hideWindow ( '#divErrorArea' );
}

function showWindow ( divName )
{							
	$("#fuzz").show();			
	$(divName).fadeIn();
	$(divName + " input:text:visible:first").focus();				
}

function hideWindow ( divName )
{							
	$("#fuzz").hide();			
	$(divName).fadeOut();				
}		

function loadJSFile(filename)
{		 
	var oHead = document.getElementsByTagName('HEAD').item(0);
	var oScript = document.createElement( "script" );
	oScript.language = "javascript";
	oScript.type = "text/javascript";
	oScript.src = filename;
	oHead.appendChild( oScript );
}
		
jQuery.fn.center = function () {
    this.css("position","fixed");
    this.css("top", (($(window).height() - this.height())/2 )  + "px"); // / 2+$(window).scrollTop() 
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}			

function doLogout ()
{
	postAction ( { action: "doLogout", "stayBusy": true }, function(data) { location="/"; });	
}
	
function postLogin ()
{
	var fieldError = checkFields( "#loginForm" );
	if (fieldError) 
	{
		$("#loginDiv .buttonresult").html(fieldError);
	}	
	else
	{
		var postdata = $("#loginForm").serializeArray();
		postdata["stayBusy"] = true;

		postAction ( postdata, 
			function (data) {
				if ( data.status == "SUCCESS" && data.content.role )
				{
					if ( location && location.toString().indexOf ( "/cart" ) != -1 ) location = "/cart";
					else if ( data.content.role == "ADMIN" ) location = "/admin";
					else location = "/mynafc";
				}	
				else 
				{
					$("#loginDiv .buttonresult").html ( "Invalid Login/Password" );
					setBusy ( false );
				}
		}); 
	}
}

function resetPassword ()
{
	var email = $("#loginForm #loginemail").val();
	var loginResultDiv = $("#loginDiv .buttonresult");
	
	$("#loginForm #loginemail").css("outline", "0");
	
	if ( !email || email.length < 5 )
	{
		$("#loginForm #loginemail").css("outline", "1px solid red");
		loginResultDiv.html ( "Enter your email address to reset..." );
	}
	else
	{
		postAction ( { action: "resetPassword", "email": email }, 
			function ( data ) { 
				if ( data.status != "SUCCESS" ) loginResultDiv.html ( "Invalid email address\n\n" ); 
				else loginResultDiv.html ( "Success! Please check your email." );
		});  
	}
}

	
function addToCart ( key )
{
	cartChange ( "addToCart", key );
}

function removeFromCart ( key )
{
	cartChange ( "removeFromCart", key );
}

function clearCart ( )
{
	cartChange ( "clearCart", 0 );
}

function cartChange ( action, key )
{
	if ( key instanceof Array ) key = key.join(",");
	postAction ( { "action": action,  "key": key }, 
		function ( data ) { 
			$('#shoppingCart').hide(); 
			$('#shoppingCart').fadeIn(500); 
			scrollUpTo ( '#shoppingCart' );
			$('#shoppingCart').html ( data.content.carthtml );
			
			if ( data.content.count > 0 ) 
			{
				$('.hideWhenCartEmpty').show(500);
				$("#cartHeaderLink").html ( 'Shopping Cart (' + data.content.count + ')' );
			}
			else 
			{
				$('.hideWhenCartEmpty').hide(500);
				$("#cartHeaderLink").html ( '' );
			}
			$(".cartObject").corner("5px");
			$('h2').corner("5px");
	});  
			
}

(function($) {
    $.QueryString = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i)
        {
            var p=a[i].split('=');
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))
})(jQuery);


function checkFields ( formName )
{
	$(formName +" input").css("outline", "0");
	$(formName +" select").css("outline", "0");
	$(formName +" textarea").css("outline", "0");
	
	var formError;

	$(formName + " .requiredField").each(function(index) 
	{
		var fieldError = null;
		var val = $(this).val();
		var name = $(this).attr('id');

	    if ( val.length < 2 )
		{
			fieldError = "Missing Required Field.";
		}
		else
		{			
			if ( name == "email" && !validateEmail ( val ) ) fieldError = "Email Address is invalid.";				
		}
		
		if (fieldError != null) 
		{
			$(this).css("outline", "1px solid red");				
			$(this).select(); 
			$(this).focus(); 
			formError = fieldError;
			return false;
		}
	});			
	return formError;
}

function validateEmail(email) 
{ 
	 var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 
	 return email.match(re) 
}

function goToByScroll(id)
{
	var topOff = $(id).offset().top - 107;
    $('html,body').animate({scrollTop: topOff},'fast');
}

function scrollUpTo ( id )
{
	if ( $(id) && $(id).offset() )
	{	
		var topY = $(id).offset().top;
		var targetY = $(window).height() - 300 + $(window).scrollTop();
		var scroll = topY - $(window).height() + 300;
		if ( topY < targetY ) $('html,body').animate({scrollTop: scroll }, 500); 
	} 		
}

function scrollDownTo (id )
{
	if ( $(id) && $(id).offset() )
	{
		var topY = $(id).offset().top;
		var targetY = $(window).height() - 500 + $(window).scrollTop();
		var scroll = topY - $(window).height() + 500;
		if ( topY > targetY ) $('html,body').animate({scrollTop: scroll }, 500);   
	}
}

function gotoProduct ( name )
{
	location = "/offerings/" + nameToURL ( name );
}

function nameToURL ( str )
{
	var str = str.replace ( /\s/g, "-" );
	str = str.replace ( /\&/g, "_" );
	str = str.toLowerCase();
	return str; 
}

function doFlush()
{
	postAction ( { action: "doFlush" }, function(data) { location="/index" });	
}

function doValidate()
{
    location = "http://validator.w3.org/check?uri=" + location;
}

function badBrowser()
{
    if($.browser.msie && parseInt($.browser.version) <= 6){ return true;}                  //IE ab ver. 6.0

    if($.browser.opera && ($.browser.version *10) <= 95) { return true;}                //Opera ab ver. 9.5

  	if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
  	{
	    var ffversion=new Number(RegExp.$1)
	    if (ffversion<=2) { return true;}
    }                                                   //Firefox ab ver. 2.0

    if ($.browser.safari && (navigator.appVersion.indexOf("1.") == 0) ){return true;}    //Safari ver. 1.0
    if ($.browser.safari && (navigator.appVersion.indexOf("2.") == 0) ){return true;}    //Safari ver. 2.0
    if ($.browser.safari && (navigator.appVersion.indexOf("3.") == 0) ){return true;}    //Safari ver. 3.0

    return false;
}

function randomNum(max)
{
	var d = new Date();
	var ms = d.getMilliseconds();
	return Math.floor(Math.random(ms)*max);	
}


/**
* 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);

