$(function(){
	//category selection input change listener
	$('select.category-select').change(function(){
		var cat = parseInt($(this).val());
		if(cat !== 0){
			$.get('/includes/ajax-handler.php',{m:'cat_url',c:cat},function(data){
				if(data !== '') window.location.href=$.trim(data);
				return false;
			});
		}
	});	
	$('h2:not(.ignore)').kearning();
	$(':input.auto-submit').change(function(){$(this).parents('form').submit();});
	$('a.email-link').emailToFriend();
	$('a.pop-article').articlePopUp();
	$('a[rel=new-window]').attr('target','_blank');
	$('#ss').attr('autocomplete','off');
		/*
		.keyup(function(e){
			ajax_showOptions(this,'sterms',e);
		});*/
	$('#kcode,#dcode').keyup(function(e){
		if(e.keyCode !== 13) return;
		$('#CouponCodeButton').click();
	});
	runRCIForm('rci-contact-form');
	$('#MainNav').superfish();
	$('img.play-image').mouseover(function(){
		$('span.play').remove();
		$(this).before('<span class="play">&nbsp;</span>');
	});
	
	$('span.play').live('mouseout',function(){$(this).remove()});
	$("#FreeGiftForm").checkGiftForm();
	allergyProofBedroom();
	customURLBuilder();
});

function customURLBuilder(){
	var urlInput = $("#url");
	var affiliateInput = $("#affiliate_code");
	var finalInput = $("#final_url");

	$("#btn_gen").click(function(){
		var url = urlInput.val();
		var affiliate = affiliateInput.val();
		
		if(url == ''){
			alert('URL is required.');
			urlInput.focus();
			return;
		}
		if(affiliate == ''){
		    alert('Affiliate Code is required.');
		    affiliateInput.focus();
            return;
		}
		
		//get query string pieces from url
		var qstringStart = url.indexOf('?');
		var baseURL = url;
		var queryString = '';
		
		if(qstringStart !== -1){
             baseURL = url.substr(0,qstringStart);
             queryString = url.substr((url.indexOf('?') + 1));
		}

		var queryParams = optionsFromString(queryString,'&','=');
		queryParams['eid'] = affiliate;
		
		pieces = new Array();
		for(var i in queryParams){
			pieces[pieces.length] = i+'='+encodeURI(decodeURI(queryParams[i]));
		}

		finalInput.val(baseURL+'?'+pieces.join('&'));
	});

	$("#btn_clear").click(function(){
         urlInput.val("");
         affiliateInput.val("");
         finalInput.val("");
	});
}

function allergyProofBedroom(){
	$('#BedroomDiv img')
		.mouseover(function(){
			$('#BedroomTip').remove();
			var alt = $(this).attr('alt');
			if(alt != ''){
				$('#BedroomDiv').append('<div id="BedroomTip">'+alt+'</div>');
			}
		});
}

function optionsFromString(opstring,fieldsplit,opsplit){
	if(typeof(fieldsplit) == 'undefined') fieldsplit = ';'
	if(typeof(opsplit) == 'undefined') opsplit = '='
	var ret,opArr,op,lastIndex;
	ret = {};
	
	//check to see if field split is last character or not
	lastIndex = opstring.lastIndexOf(fieldsplit);
	if(lastIndex === (opstring.length - 1)){
		opstring = opstring.substring(0,lastIndex);
	}
	
	//exit if empty string
	if(opstring.length == '') return ret;
	
	//chop up options into object
	opArr = opstring.split(fieldsplit);
	for(var i in opArr){
		ops = opArr[i].split(opsplit);
		if(ops[0] != '') ret[ops[0]] = ops[1];
	}
	
	return ret;
}

function checkFreeGiftOffer(id){
	var num = 0;
	
	$(':input[name=fgc_'+id+'\\[\\]]').each(function(){
		var addValue = $("#fgc_"+id+"_"+$(this).val()).val();
		addValue = parseInt(addValue);
		if(isNaN(addValue)) addValue = 0;
		num += addValue;
	});
	
	return num;
}


//create our jquery extension here
(function($){
	$.fn.checkGiftForm = function(){
		return this.each(function(){
			$(this).submit(function(event){
				selectionsRemaining = false;
				tooManySelections = false;
				$('div.errMsgBig').remove();
				$(':input[id^=fgc_]').removeClass('over-select').removeClass('under-select');
				
				if(window.freeGifts == undefined){
					return true;
				}
				
				//check each offers total number - compare to target for form behavior
				for(var i in freeGifts){
					numInput = checkFreeGiftOffer(i);
					
					//customer has not maxed out their gifts - allow
					if(numInput < freeGifts[i]){
						selectionsRemaining = true;
						$(':input[id^=fgc_'+i+']').addClass('under-select');
					}
					
					//customer has selected too many gifts - prevent
					if(numInput > freeGifts[i]){
						tooManySelections = true;
						$(':input[id^=fgc_'+i+']').addClass('over-select');
					}
				}
				
				//error message if too many choices
				if(tooManySelections){
					$('#FreeGiftForm').before('<div class="errMsgBig">You have selected too many items, please double check your offers and resubmit.</div>');
					return false;
				}
				
				//confirm passing up free gifts
				if(selectionsRemaining) return(confirm('Please click "Ok" to decline your remaining free gifts'));
				
				return true;
			});
		});
	}
	
	$.fn.kearning = function(){                
		//for each matched element create new floater class
		return this.each(function(){
			var whole = $(this).html();
			if(whole.indexOf('<span>') < 0){
				var words = whole.split(' ');
				var first = words[0];
				var rest = whole.substring(((first.length) + 1));
				$(this).html(first+' <span>'+rest+'</span>');
			}
		});
	}
	
	$.fn.articlePopUp = function(){
		var popupMatch = /pop\[(.*)\]/;
		var defaults = {
			height:500,
			width:500,
			'scroll':'yes',
			'status':'no',
			name:'article'
		};
		
		return this.each(function(){
			$(this).click(function(event){
				event.preventDefault();
				
				var relattribute = $(this).attr('rel');
				var op = {};
				if(relattribute.length != 0){
					var popoptions = popupMatch.exec(relattribute);
					if(popoptions && popoptions[1]){
						op = optionsFromString(popoptions[1]);
					}
				}
				
				op = $.extend(defaults,op);
				
				fncCenteredChildWindow(op.name,$(this).attr('href'),op.height,op.width,op.scroll,op.status);
			});
		});
	}
	
	$.fn.emailToFriend = function(){
		var url = document.URL;
		var title = document.title;
		
		return this.each(function(){
			$(this).click(function(event){
				event.preventDefault();
				
				$.get('/includes/ajax.php',{m:'form'},function(data){
					$('body').append('<div id="EmailFriend" title="Send this page to a friend!">'+data+'<\/div>');
					$('#EmailFriend').data('sending',0).dialog({
						width:450,
						modal:true,
						'close':function(){$('#EmailFriend').remove();},
						buttons:{
							'Close':function(){$(this).dialog("close");},
							'Send':function(){
								//exit send if a message send is still processing
								if($(this).data('sending') == 1) return;
								
								//remove any existing errors
								$('#EmailFriend .ui-state-error').remove();
								$('#EmailFriend :input').removeClass('err');
								
								var sendOK = true;		//flag to denote if required fields are entered
								var toSend = {page:url,page_title:title};		//holds data to send to handler
								var missingErr = false;
								var emailErr = false;
								//add each input to the data to send
								$('#EmailFriend :input').each(function(){
									fieldValue = $(this).val();
									//check required fields
									if($(this).hasClass('req') && fieldValue == ''){
										missingErr = true;
										$(this).addClass('err');
									}
									
									if($(this).hasClass('emailchk') && !emailAddressIsValid(fieldValue)){
										emailErr = true;
										$(this).addClass('err');
									}
									
									//add data differently depending on type of field
									switch($(this).attr('type')){
										case 'checkbox':
											//must look at checked attribute
											toSend[$(this).attr('id')] = ($(this).attr('checked'))? 1:0;
										break;
										default:
											toSend[$(this).attr('id')] = fieldValue;
									}
								});
								
								if(missingErr || emailErr) sendOK = false;
								
								//exit if required fields aren't entered
								if(!sendOK){
									if(emailErr) $('#EmailFriend form').prepend('<div id="EmailError" class="ui-state-error">Please enter a valid email address.<\/div>');
									if(missingErr) $('#EmailFriend form').prepend('<div id="Error" class="ui-state-error">Some required fields are missing.<\/div>');
						
									return false;
								}
								
								//set sending variable to prevent double submission
								$(this).data('sending',1);
								var self = $(this);
								
								//send to handler
								$.post('/includes/ajax.php?m=h_form',toSend,function(data){
									//reset processing flag
									self.data('sending',0);
									var result = eval("("+data+")");
									
									//catch json not returning
									if(result.processed == undefined){
										$('#EmailFriend form').prepend('<div id="Error" class="ui-state-error">An error has occured during your request, please try again.<\/div>');
										return false;
									}
									
									//catch processing errors
									if(result.processed == 0){
										//show errors
										$('#EmailFriend form').prepend('<div id="Error" class="ui-state-error">'+result.errors.join("<br>")+'<\/div>');
										return false;
									}
									
									//send was successful
									self.dialog('close');
								});
							}
						}
					});
				});
			});
		});
	}
	
	$.fn.rateEditWidgit = function(){
		return this.each(function(){
			$(this).click(function(event){
				event.preventDefault();
				//get product id from 
				var product_id = $(this).attr('id').substring(10);
				$.get('/includes/ajax-handler.php',{m:'rate_edit','product_id':product_id},function(data){
					var result = eval("("+data+")");
					
					var rateDiv = ($('<div><\/div>'))
							.attr({'id':'RateWidgit','title':'Edit your product review'})
							.addClass('modal-form')
							.html(result.content)
							.appendTo('body')
							.data('sending',0)
					
					if(result.canReview == undefined){
						rateDiv.dialog({
							width:300,
							modal:true,
							'close':function(){$(this).remove();},
							buttons:{'Close':function(){$(this).dialog('close');}}
						});
					}
					
					if(result.canReview == 0){
						rateDiv.dialog({
							width:300,
							modal:true,
							'close':function(){$(this).remove();},
							buttons:{'Close':function(){$(this).dialog('close');}}
						});
					}
					
					rateDiv.dialog({
						width:500,
						modal:true,
						'close':function(){$(this).remove();},
						buttons:{
							'Close':function(){$(this).dialog('close');},
							'Submit':function(){
								//exit send if a message send is still processing
								if($(this).data('sending') == 1) return;
								
								//remove any existing errors
								$('#RateWidgit .ui-state-error').remove();
								$('#RateWidgit :input').removeClass('err');
								
								var sendOK = true;		//flag to denote if required fields are entered
								var toSend = {'product_id':product_id};		//holds data to send to handler
								var missingErr = false;
								
								//add each input to the data to send
								$('#RateWidgit :input').each(function(){
									fieldValue = $(this).val();
									//check required fields
									if($(this).hasClass('req') && fieldValue == ''){
										missingErr = true;
										$(this).addClass('err');
									}
									
									//add data differently depending on type of field
									switch($(this).attr('type')){
										case 'checkbox':
											//must look at checked attribute
											toSend[$(this).attr('id')] = ($(this).attr('checked'))? 1:0;
										break;
										default:
											toSend[$(this).attr('id')] = fieldValue;
									}
								});
								
								if(missingErr) sendOK = false;
								
								//exit if required fields aren't entered
								if(!sendOK){
									if(missingErr) $(this).prepend('<div id="Error" class="ui-state-error">Some required fields are missing.<\/div>');
									return false;
								}
								
								//set sending variable to prevent double submission
								$(this).data('sending',1);
								var self = $(this);
								
								//send to handler
								$.post('/includes/ajax-handler.php?m=s_rate_edit',toSend,function(data){
									//reset processing flag
									self.data('sending',0);
									
									result = eval("("+data+")");
									
									//catch json not returning
									if(result.processed == undefined){
										self.prepend('<div id="Error" class="ui-state-error">An error has occured during your request, please try again.<\/div>');
										return false;
									}
									
									//catch processing errors
									if(result.processed == 0){
										//show errors
										self.prepend('<div id="Error" class="ui-state-error">'+result.errors.join("<br><br>")+'<\/div>');
										if(result.errorLevel == 1){
											self.dialog('option', 'buttons', { "Close": function() { $(this).dialog("close"); } });
										}
										return false;
									}
									
									//send was successful
									window.location.reload(true);
								});
							}
						}
					});
				});
			});
		});
	}
	
	$.fn.rateWidgit = function(){
		return this.each(function(){
			$(this).click(function(event){
				event.preventDefault();
				
				//get product id from 
				var product_id = $(this).attr('id').substring(7);
				$.get('/includes/ajax-handler.php',{m:'rate_form','product_id':product_id},function(data){
					var result = eval("("+data+")");
					
					var rateDiv = ($('<div><\/div>'))
							.attr({'id':'RateWidgit','title':'Submit your product review'})
							.addClass('modal-form')
							.html(result.content)
							.appendTo('body')
							.data('sending',0)
					
					if(result.canReview == undefined){
						rateDiv.dialog({
							width:300,
							modal:true,
							'close':function(){$(this).remove();},
							buttons:{'Close':function(){$(this).dialog('close');}}
						});
					}
					
					if(result.canReview == 0){
						rateDiv.dialog({
							width:300,
							modal:true,
							'close':function(){$(this).remove();},
							buttons:{'Close':function(){$(this).dialog('close');}}
						});
					}
					
					rateDiv.dialog({
						width:500,
						modal:true,
						'close':function(){$(this).remove();},
						buttons:{
							'Close':function(){$(this).dialog('close');},
							'Submit':function(){
								//exit send if a message send is still processing
								if($(this).data('sending') == 1) return;
								
								//remove any existing errors
								$('#RateWidgit .ui-state-error').remove();
								$('#RateWidgit :input').removeClass('err');
								
								var sendOK = true;		//flag to denote if required fields are entered
								var toSend = {'product_id':product_id};		//holds data to send to handler
								var missingErr = false;
								
								//add each input to the data to send
								$('#RateWidgit :input').each(function(){
									fieldValue = $(this).val();
									//check required fields
									if($(this).hasClass('req') && fieldValue == ''){
										missingErr = true;
										$(this).addClass('err');
									}
									
									//add data differently depending on type of field
									switch($(this).attr('type')){
										case 'checkbox':
											//must look at checked attribute
											toSend[$(this).attr('id')] = ($(this).attr('checked'))? 1:0;
										break;
										default:
											toSend[$(this).attr('id')] = fieldValue;
									}
								});
								
								if(missingErr) sendOK = false;
								
								//exit if required fields aren't entered
								if(!sendOK){
									if(missingErr) $(this).prepend('<div id="Error" class="ui-state-error">Some required fields are missing.<\/div>');
									return false;
								}
								
								//set sending variable to prevent double submission
								$(this).data('sending',1);
								var self = $(this);
								
								//send to handler
								$.post('/includes/ajax-handler.php?m=rate_submit',toSend,function(data){
									//reset processing flag
									self.data('sending',0);
									
									result = eval("("+data+")");
									
									//catch json not returning
									if(result.processed == undefined){
										self.prepend('<div id="Error" class="ui-state-error">An error has occured during your request, please try again.<\/div>');
										return false;
									}
									
									//catch processing errors
									if(result.processed == 0){
										//show errors
										self.prepend('<div id="Error" class="ui-state-error">'+result.errors.join("<br><br>")+'<\/div>');
										if(result.errorLevel == 1){
											self.dialog('option', 'buttons', { "Close": function() { $(this).dialog("close"); } });
										}
										return false;
									}
									
									//send was successful
									window.location.reload(true);
								});
							}
						}
					});
				});
			})
		})
	}
	
	$.fn.bookmark = function(){
		var url = document.URL;
		var title = document.title;
		
		return this.each(function(){
			//add rel to link if browser is opera - opera will do the rest
			if(window.opera) $(this).attr('rel','sidebar');
			
			//perform bookmark on click
			$(this).click(function(){
				if(window.sidebar){//firefox
					window.sidebar.addPanel(title,url,'');
				}else if(window.external){//IE
					window.external.AddFavorite( url, title); 
				}else if(window.opera){// Opera 7+
					return false;
				}else{
					alert('Your browser does not support this method.  Please bookmark this page manually.');
				}
				
				//prevent basic click action
				return false;
			});
		});
	}
})(jQuery);

function setupAttributeSelects(){
	$('select.attribute-select').change(function(){
		//get data from id
		var data = $(this).attr('id').split('_');
		
		var parent = data[2];
		var level = parseInt(data[3]) + 1;
		var selection = parseInt($(this).val());
		
		//check for child attribute select
		if($('#att_child_'+parent+'_'+level).length > 0){
			//if user goes back to 0 option, reset select box
			if(selection == 0){
				$('#att_child_'+parent+'_'+level).attr('disabled','true')
					.children().removeAttr('selected').end()
					.children(':first').attr('selected','true');
				return null;
			}
			
			//update child attribute options
			$('#att_child_'+parent+'_'+level).load('/includes/ajax-handler.php?m=att_options&parent='+selection+'&level='+level,function(){
				if($(this).children().length > 1){
					$(this).removeAttr('disabled');
				}else{
					$(this).attr('disabled','true');
				}
			});
		}else{
			//allow attribute to be bought
			$('#att_id_'+parent).data('ready',1);
		}
	});
	
	$(':input[id^=qty_]').keyup(function(e){
		if(e.which == 13) $('form.na-cart').submit();
	});
	
	$('#MissedQuantity').dialog({
		'autoOpen':false,
		'modal':true,
		'draggable':false,
		'resizable':false,
		'width':400,
		'buttons':{
			'Ok':function(){$(this).dialog("close");}
		}
	});
	$('#MissedSelections').dialog({
		'autoOpen':false,
		'modal':true,
		'draggable':false,
		'resizable':false,
		'width':400,
		'buttons':{
			'Ok':function(){$(this).dialog("close");}
		}
	});
	
	$('#SpecialOrderMessage').dialog({
		'autoOpen':false,
		'modal':true,
		'draggable':false,
		'resizable':false,
		'width':600,
		'buttons':{
			'Acknowledged':function(){
					window.specialOrderFlag = false;
					$(this).dialog("close");
					$('form.na-cart').submit();
				}
		}
	});
}

function setupCartForm(){
	window.specialOrderFlag = true;
	$('#SubmitNAForm').click(function(){$('form.na-cart').submit();return false;})
	$('form.na-cart').submit(function(){
		var readyFlag = true;
		var hasSpecialOrders = false;
		
		//reset select css
		$('[id^=att_child_]').removeClass('err');
		$('[id^=qty_]').removeClass('err');
		
		//check to make sure all choices have been made
		var j = 0;
		var k = 0;
		$(this).find(':hidden[id^=att_id_]').each(function(i){
			var att_id = $(this).attr('id').substring(7);
			
			//only worry about products with quantity > 1
			if(parseInt($('#qty_'+att_id).val()) > 0){
				if($(this).hasClass('special-order') && window.specialOrderFlag) hasSpecialOrders = true;
				
				$('[id^=att_child_'+att_id+']').each(function(){
					if(parseInt($(this).val()) === 0){
						$(this).addClass('err');
						readyFlag = false;
					}
				});
			}else{
				//increment number not set
				j++;
			}
			
			//save total to function variable
			k = i;
		});
		
		//check to make sure a quantity was entered somewhere
		if(k == (j-1)){			
			$('#MissedQuantity').dialog("open");
			$('[id^=qty_]').addClass('err');
			return false;
		}
		
		//open up dialog for selections required
		if(!readyFlag) $('#MissedSelections').dialog("open");
 		
		if(hasSpecialOrders){
			$('#SpecialOrderMessage').dialog("open");
			return false;
		}
		
		return readyFlag;
	});
}

function setupAvailabilityLinks(){
	$("a.check-availability").click(function(e){
		//prevent anchor jump
		e.preventDefault();
		
		//get clicked attribute
		var ids = $(this).attr('id').substring(7).split('_');
		var att_id = parseInt(ids[0],10);
		var product_id = parseInt(ids[1],10);
		
		//make sure we are passing valid information
		if(isNaN(att_id) || isNaN(product_id) || att_id === 0 || product_id === 0) return;
		
		//get availability information
		$.get('/includes/ajax-handler.php',{m:'availability',id:product_id,att:att_id},function(data){
			//display availability information
			$('body').append('<div id="AvailabilityCheck" title="Product Availability">'+data+'<\/div>');
			$('#AvailabilityCheck').dialog({
				width:700,
				modal:true,
				'close':function(){$('#AvailabilityCheck').remove();},
				buttons:{
					'Close':function(){$(this).dialog("close");}
				}
			});
		});
	});
}

//open up photo pop up
function popPhotos(product_id){
	//base url of photo popup
	URL = '/cart/pf/photopop.php?p='+product_id;
	
	//get and add photo id to url as anchor
	var pactivephoto_id = $('#pactivephoto').val();
	if(pactivephoto_id){
		URL = URL + '#'+pactivephoto_id;
	}
	
	//open popup
	fncCenteredChildWindow('photodisplay',URL,'600','600','yes','yes');
}
function popAttribPhotos(product_id,att_id){
	//base url of photo popup
	URL = '/cart/pf/photopop.php?p='+product_id+'&att='+att_id;
	//open popup
	fncCenteredChildWindow('photodisplay',URL,'600','600','yes','yes');
}

//switch photo display on page
function pSwithImage(photo_id){
	//get hidden field of active photo id
	var pactivephoto_id = $('#pactivephoto'); 
	
	//change old image thumb to regular border
	$('#pthumb_'+pactivephoto_id.val()).attr('class','thumbPhoto');
	
	//change out medium image
	$('#pprimary').attr('src',$('#pmed_'+photo_id).val());
	//change active thumb border to active
	$('#pthumb_'+photo_id).attr('class','thumbActive');
	//store new active id to hidden field
	pactivephoto_id.val(photo_id);
	//change any caption value to image
	$('#pcap').html($('#pcap_'+photo_id).val());
}

//submit coupon code form
function applyCouponCode(xform){
	xform.action='/cart/basket.php?action=coupon';
	xform.submit();
}

//start checkout process
function beginCheckout(xform, checkout_url){
	if(checkout_url==''){
    	checkout_url = "/cart/checkout.php?m=login";
	}
	
	document.location=checkout_url;
}

//functions for various popup windows
function fncPF(URL){fncCCWindow(URL,'300','800','yes','no');}
function fncPrint(){window.print();}
function fncCloseWindow(){window.close();}
function fncCCWindow(URL,vHeight,vWidth,vScroll,vStatus) {fncCenteredChildWindow('ccv',URL,vHeight,vWidth,vScroll,vStatus)}
function fncCenteredChildWindow(name,URL,vHeight,vWidth,vScroll,vStatus) {
	if (screen.width) {
		var winl=(screen.width-vWidth)/2;
		var wint=(screen.height-vHeight)/2;
	} else { 
		winl=0;wint=0;
	}
	if(winl<0)winl=0;
	if(wint<0)wint=0;
	var child = window.open(URL,name,'height='+vHeight+',width='+vWidth+',scrollbars='+vScroll+',status='+vStatus+',top='+wint+',left='+winl+',resizable=no');
	child.focus();
}

function submitPaymentForm(btn,obj){
	obj.action='?m=s_payment';
	obj.target='_self';
	btn.disabled = true;
	obj.submit();
}

function submitPrintFaxForm(btn,obj){
	obj.action='/cart/pf/order_fax.php';
	obj.target='_blank';
	btn.disabled = true;
	obj.submit();
}

function runRCIForm(form_id){
	$('#'+form_id).find(':submit').each(function(){
		$(this).replaceWith('<input id="'+form_id+'_submit" type="button" value="'+$(this).attr('value')+'" onClick="submitRCIForm(\''+form_id+'\');" />');
	});
}
function submitRCIForm(form_id){
	var submitFlag = true;
	var fields = new Array();
	var first = true;
	var emailfields = new Array();
	var messages = new Array();
	
	$('#'+form_id+'_submit').attr('disabled','disabled');
	$('div.errorMsg,.positiveMsg,.infoMsg,.warningMsg').remove();
	$('div.err').removeClass('err');
	
	//test for entry in input fields
	$('#'+form_id).find(':input.req').each(function(){
		if($(this).val() == ''){
			if(first){
				$(this).focus();
				first = false;
			}
			fields[fields.length] = $('label[for=' + $(this).attr('id') +']').text();
			$(this).addClass('err');
			submitFlag = false;
		}
	});
	
	//test for valid email addresses
	$('#'+form_id).find(':input.emailchk').each(function(){
		fieldValue = $(this).val();
		if(!emailAddressIsValid(fieldValue)){
			if(first){
				$(this).focus();
				first = false;
			}
			emailfields[emailfields.length] = $('label[for=' + $(this).attr('id') +']').text();
			$(this).addClass('err');
			submitFlag = false;
		}
	});
		
	if(submitFlag){
		$('#'+form_id).submit();
	}else{
		$('#'+form_id+'_submit').removeAttr('disabled');
		
		if(fields.length > 0){
			messages[messages.length] = 'Some required fields are blank.  Please enter these fields: '+fields.join(', ')+' and resubmit.';
		}
		
		if(emailfields.length > 0){
			messages[messages.length] = 'Please enter valid email addresses for these fields: '+emailfields.join(', ')+' and resubmit.';
		}
		
		$('#'+form_id).prepend('<div class="errorMsg" style="display:none;">'+messages.join('<br><br>')+'</div>');
		$('div.errorMsg').fadeIn("slow");
	}
}

function emailAddressIsValid(email){
	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/;		//not valid
	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;		//valid
	
	if(reg1.test(email)) return false;
	return reg2.test(email);
}

function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	";path=/"+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name){
	if(document.cookie.length == 0) return '';
	
	c_start=document.cookie.indexOf(c_name + "=");
	if(c_start == -1) return '';
	
	c_start=c_start + c_name.length+1;
	c_end=document.cookie.indexOf(";",c_start);
	if (c_end==-1) c_end=document.cookie.length;
	return document.cookie.substring(c_start,c_end);
}

function meetsNewsletterPopUpRequirements(){
	var visitedBefore = getCookie('na_first_visit');
	setCookie('na_first_visit','1',365);
	return visitedBefore == '';
}

function runNewsLetterPopUp(){
	$.get('/includes/ajax-handler.php',{m:'newsletter_pop'},function(data){
		$('body').append('<div id="NewsletterSignUp" title="Interested in Special Offers?">'+data+'<\/div>');
		$('#NewsletterSignUp').data('sending',0).dialog({
			width:620,
			modal:true,
			'close':function(){$('#NewsletterSignUp').remove();},
			buttons:{
				'Close':function(){$(this).dialog("close");},
				'Send':function(){
					//exit send if a message send is still processing
					if($(this).data('sending') == 1) return;
					
					//remove any existing errors
					$('#NewsletterSignUp .ui-state-error').remove();
					$('#NewsletterSignUp :input').removeClass('err');
					
					var sendOK = true;		//flag to denote if required fields are entered
					var toSend = {};		//holds data to send to handler
					var emailErr = false;
					var missingErr = false;
					//add each input to the data to send
					$('#NewsletterSignUp :input').each(function(){
						fieldValue = $(this).val();
						//check required fields
						if($(this).hasClass('req') && fieldValue == ''){
							missingErr = true;
							$(this).addClass('err');
						}
						
						if($(this).hasClass('emailchk') && !emailAddressIsValid(fieldValue)){
							emailErr = true;
							$(this).addClass('err');
						}
						
						//add data differently depending on type of field
						switch($(this).attr('type')){
							case 'checkbox':
								//must look at checked attribute
								toSend[$(this).attr('id')] = ($(this).attr('checked'))? 1:0;
							break;
							default:
								toSend[$(this).attr('id')] = fieldValue;
						}
					});
					
					if(missingErr || emailErr) sendOK = false;
					
					//exit if required fields aren't entered
					if(!sendOK){
						if(emailErr) $('#NewsletterSignUp form').prepend('<div id="EmailError" class="ui-state-error">Please enter a valid email address.<\/div>');
						if(missingErr) $('#NewsletterSignUp form').prepend('<div id="Error" class="ui-state-error">Some required fields are missing.<\/div>');
						return false;
					}
					
					//set sending variable to prevent double submission
					$(this).data('sending',1);
					var self = $(this);
					
					//send to handler
					$.post('/includes/ajax-handler.php?m=s_newsletter_pop',toSend,function(data){
						//reset processing flag
						self.data('sending',0);
						var result = eval("("+data+")");
						
						//catch json not returning
						if(result.processed == undefined){
							$('#NewsletterSignUp form').prepend('<div id="Error" class="ui-state-error">An error has occured during your request, please try again.<\/div>');
							return false;
						}
						
						//catch processing errors
						if(result.processed == 0){
							//show errors
							$('#NewsletterSignUp form').prepend('<div id="Error" class="ui-state-error">'+result.errors.join("<br>")+'<\/div>');
							return false;
						}
						
						if(result.processed == 1){
							$('#NewsletterSignUp').html(result.message);
							$('#NewsletterSignUp ~ div.ui-dialog-buttonpane').children(':contains(Send)').remove();
							return true;
						}
					});
				}
			}
		});
	});
}

// textarea length limiter
function limitChars(textarea, limit, infodiv) {
  var text = textarea.value; 
  var textlength = text.length;
  var info = document.getElementById(infodiv);

  if (textlength > limit) {
    info.innerHTML = 'Comments<br>(You <span style="color:red; font-weight:bold;">cannot</span> write more than '+limit+' characters)';
    textarea.value = text.substr(0,limit);
    return false;
  } else if (textlength == 0) {
    info.innerHTML = 'Comments<br>('+ limit +' characters max)';
  } else {
    info.innerHTML = 'Comments<br>(' + (limit - textlength) +' characters left)';
    return true;
  }

}

// Flash Player Version Detection - Rev 1.6
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE=(navigator.appVersion.indexOf("MSIE")!=-1)?true:false;var isWin=(navigator.appVersion.toLowerCase().indexOf("win")!=-1)?true:false;var isOpera=(navigator.userAgent.indexOf("Opera")!=-1)?true:false;function ControlVersion(){var version;var axo;var e;try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");version=axo.GetVariable("$version");}catch(e){}if(!version){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");version="WIN 6,0,21,0";axo.AllowScriptAccess="always";version=axo.GetVariable("$version");}catch(e){}}if(!version){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");version=axo.GetVariable("$version");}catch(e){}}if(!version){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");version="WIN 3,0,18,0";}catch(e){}}if(!version){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");version="WIN 2,0,0,11";}catch(e){version=-1;}}return version;}function GetSwfVer(){var flashVer=-1;if(navigator.plugins!=null&&navigator.plugins.length>0){if(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]){var swVer2=navigator.plugins["Shockwave Flash 2.0"]?" 2.0":"";var flashDescription=navigator.plugins["Shockwave Flash"+swVer2].description;var descArray=flashDescription.split(" ");var tempArrayMajor=descArray[2].split(".");var versionMajor=tempArrayMajor[0];var versionMinor=tempArrayMajor[1];var versionRevision=descArray[3];if(versionRevision==""){versionRevision=descArray[4];}if(versionRevision[0]=="d"){versionRevision=versionRevision.substring(1);}else{if(versionRevision[0]=="r"){versionRevision=versionRevision.substring(1);if(versionRevision.indexOf("d")>0){versionRevision=versionRevision.substring(0,versionRevision.indexOf("d"));}}}var flashVer=versionMajor+"."+versionMinor+"."+versionRevision;}}else{if(navigator.userAgent.toLowerCase().indexOf("webtv/2.6")!=-1){flashVer=4;}else{if(navigator.userAgent.toLowerCase().indexOf("webtv/2.5")!=-1){flashVer=3;}else{if(navigator.userAgent.toLowerCase().indexOf("webtv")!=-1){flashVer=2;}else{if(isIE&&isWin&&!isOpera){flashVer=ControlVersion();}}}}}return flashVer;}function DetectFlashVer(reqMajorVer,reqMinorVer,reqRevision){versionStr=GetSwfVer();if(versionStr==-1){return false;}else{if(versionStr!=0){if(isIE&&isWin&&!isOpera){tempArray=versionStr.split(" ");tempString=tempArray[1];versionArray=tempString.split(",");}else{versionArray=versionStr.split(".");}var versionMajor=versionArray[0];var versionMinor=versionArray[1];var versionRevision=versionArray[2];if(versionMajor>parseFloat(reqMajorVer)){return true;}else{if(versionMajor==parseFloat(reqMajorVer)){if(versionMinor>parseFloat(reqMinorVer)){return true;}else{if(versionMinor==parseFloat(reqMinorVer)){if(versionRevision>=parseFloat(reqRevision)){return true;}}}}}return false;}}}function AC_AddExtension(src,ext){if(src.indexOf("?")!=-1){return src.replace(/\?/,ext+"?");}else{return src+ext;}}function AC_Generateobj(objAttrs,params,embedAttrs){var str="";if(isIE&&isWin&&!isOpera){str+="<object ";for(var i in objAttrs){str+=i+'="'+objAttrs[i]+'" ';}for(var i in params){str+='><param name="'+i+'" value="'+params[i]+'" /> ';}str+="></object>";}else{str+="<embed ";for(var i in embedAttrs){str+=i+'="'+embedAttrs[i]+'" ';}str+="> </embed>";}document.write(str);}function AC_FL_RunContent(){var ret=AC_GetArgs(arguments,".swf","movie","clsid:d27cdb6e-ae6d-11cf-96b8-444553540000","application/x-shockwave-flash");AC_Generateobj(ret.objAttrs,ret.params,ret.embedAttrs);}function AC_GetArgs(args,ext,srcParamName,classid,mimeType){var ret=new Object();ret.embedAttrs=new Object();ret.params=new Object();ret.objAttrs=new Object();for(var i=0;i<args.length;i=i+2){var currArg=args[i].toLowerCase();switch(currArg){case"classid":break;case"pluginspage":ret.embedAttrs[args[i]]=args[i+1];break;case"src":case"movie":args[i+1]=AC_AddExtension(args[i+1],ext);ret.embedAttrs["src"]=args[i+1];ret.params[srcParamName]=args[i+1];break;case"onafterupdate":case"onbeforeupdate":case"onblur":case"oncellchange":case"onclick":case"ondblClick":case"ondrag":case"ondragend":case"ondragenter":case"ondragleave":case"ondragover":case"ondrop":case"onfinish":case"onfocus":case"onhelp":case"onmousedown":case"onmouseup":case"onmouseover":case"onmousemove":case"onmouseout":case"onkeypress":case"onkeydown":case"onkeyup":case"onload":case"onlosecapture":case"onpropertychange":case"onreadystatechange":case"onrowsdelete":case"onrowenter":case"onrowexit":case"onrowsinserted":case"onstart":case"onscroll":case"onbeforeeditfocus":case"onactivate":case"onbeforedeactivate":case"ondeactivate":case"type":case"codebase":ret.objAttrs[args[i]]=args[i+1];break;case"id":case"width":case"height":case"align":case"vspace":case"hspace":case"class":case"title":case"accesskey":case"name":case"tabindex":ret.embedAttrs[args[i]]=ret.objAttrs[args[i]]=args[i+1];break;default:ret.embedAttrs[args[i]]=ret.params[args[i]]=args[i+1];}}ret.objAttrs["classid"]=classid;if(mimeType){ret.embedAttrs["type"]=mimeType;}return ret;}

/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */
(function($){$.fn.superfish=function(op){var sf=$.fn.superfish,c=sf.c,$arrow=$(['<span class="',c.arrowClass,'"> &#187;</span>'].join("")),over=function(){var $$=$(this),menu=getMenu($$);clearTimeout(menu.sfTimer);$$.showSuperfishUl().siblings().hideSuperfishUl();},out=function(){var $$=$(this),menu=getMenu($$),o=sf.op;clearTimeout(menu.sfTimer);menu.sfTimer=setTimeout(function(){o.retainPath=($.inArray($$[0],o.$path)>-1);$$.hideSuperfishUl();if(o.$path.length&&$$.parents(["li.",o.hoverClass].join("")).length<1){over.call(o.$path);}},o.delay);},getMenu=function($menu){var menu=$menu.parents(["ul.",c.menuClass,":first"].join(""))[0];sf.op=sf.o[menu.serial];return menu;},addArrow=function($a){return;};return this.each(function(){var s=this.serial=sf.o.length;var o=$.extend({},sf.defaults,op);o.$path=$("li."+o.pathClass,this).slice(0,o.pathLevels).each(function(){$(this).addClass([o.hoverClass,c.bcClass].join(" ")).filter("li:has(ul)").removeClass(o.pathClass);});sf.o[s]=sf.op=o;$("li:has(ul)",this)[($.fn.hoverIntent&&!o.disableHI)?"hoverIntent":"hover"](over,out).each(function(){if(o.autoArrows){addArrow($(">a:first-child",this));}}).not("."+c.bcClass).hideSuperfishUl();var $a=$("a",this);$a.each(function(i){var $li=$a.eq(i).parents("li");$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});});o.onInit.call(this);}).each(function(){menuClasses=[c.menuClass];if(sf.op.dropShadows&&!($.browser.msie&&$.browser.version<7)){menuClasses.push(c.shadowClass);}$(this).addClass(menuClasses.join(" "));});};var sf=$.fn.superfish;sf.o=[];sf.op={};sf.IE7fix=function(){var o=sf.op;if($.browser.msie&&$.browser.version>6&&o.dropShadows&&o.animation.opacity!=undefined){this.toggleClass(sf.c.shadowClass+"-off");}};sf.c={bcClass:"sf-breadcrumb",menuClass:"sf-js-enabled",anchorClass:"sf-with-ul",arrowClass:"sf-sub-indicator",shadowClass:"sf-shadow"};sf.defaults={hoverClass:"sfHover",pathClass:"overideThisToUse",pathLevels:1,delay:300,animation:{opacity:"show"},speed:"normal",autoArrows:true,dropShadows:true,disableHI:false,onInit:function(){},onBeforeShow:function(){},onShow:function(){},onHide:function(){}};$.fn.extend({hideSuperfishUl:function(){var o=sf.op,not=(o.retainPath===true)?o.$path:"";o.retainPath=false;var $ul=$(["li.",o.hoverClass].join(""),this).add(this).not(not).removeClass(o.hoverClass).find(">ul").hide().css("visibility","hidden");o.onHide.call($ul);return this;},showSuperfishUl:function(){var o=sf.op,sh=sf.c.shadowClass+"-off",$ul=this.addClass(o.hoverClass).find(">ul:hidden").css("visibility","visible");sf.IE7fix.call($ul);o.onBeforeShow.call($ul);$ul.animate(o.animation,o.speed,function(){sf.IE7fix.call($ul);o.onShow.call($ul);});return this;}});})(jQuery);