/*

	Ecotrust FoodHub Global Javascript Functions
	ISITE Design
	
*/

var rotatorcontent = window.rotatorcontent || ""; 



//start the jQuery functions
$(document).ready(function() {

	$('html').addClass("js-on");
	var $body = $('body'), $form = $('form');
		
	fhHost = window.location.hostname;
	// Browser sniff. Adds class names. creates global var 'snuff' with browser name.
	$("html").sniff();
	
	//and encourage
	if (snuff == "ie ie6" || snuff == "ff ff2" || snuff == "sf sf2") {
		$('#header').before("<div id='get-a-new-browser'>Looks like you're using an older browser. That's no problem but if you have the option, consider <a href='http://download.cnet.com/windows/browsers/' title='Upgrade to the newest version of Firefox, Opera, Chrome, Safari or Internet Explorer'>upgrading to something shiny and new</a>.</div>");
	};
	
	// Fix IE6 :hover
	if(snuff == "ie ie6"){
	    $("#nav li, button, ul.actions li").hover(
			function() { $(this).addClass("ieover"); },
			function() { $(this).removeClass("ieover"); }
	    );
	}// IE Hovers

	// we're hijacking cakePHPs autoinserted inline confirm() function but need those links to return false
	//$("a[onclick*='confirm']").live("click", function(){		
	//	return false;	
	//});

	//auto hide message wrap after 12 seconds of allowed time for user to read and or close by hand.
	if($('#message-wrap').not('.error').is(':visible')){
		setTimeout(function(){ $('#message-wrap').fadeOut('slow'); },12000);
	}
	
	toolTipInit();

	// let's make tabs. results page tabs are built in search.js. they use a cookie that this messes up.
	$('.tabs').not('.results-page .tabs').not('.product-landing-page .tabs').idTabs();
	
	// grab the label, put it in the input
	$('#header form input').originalinputSetter(1);
	$('#product-name, #footer input').inputSetter(1);
	$('.sub-set input, #join-lightbox #email, #join-lightbox #pword').inputSetter();	
	$('.input-setter').inputSetter(0);
	
	//character limits. actual limit is part of the label text.
	$(".charactersremaining").charactersRemaining();
	$('.charactersremaining em').text("remaining");

	// make certain tables sortable via js. most tables are sorted via cake's server side sorting to support pagination
	$('.harvest-plan').tablesorter({sortList: [[0,0]]}).find('thead th span').append('<span class="sorter"></span>');
	$('table.sortable').tablesorter({sortList: [[0,0]]}).find('thead th span').append('<span class="sorter"></span>');
	
	//Profile Page's Product Table Sorting
	$('.product-table thead th:not(:first)').addClass('up').click(function(){
		//DEFINE REQUIRED INDEXS
		var $target = $(this);
		var columnIndex = $(this).index();
		var productIndex = $('.product-table tbody.opened').index()-1;
		$('.product-table thead th').each(function(i){
			if(i != columnIndex){
				$(this).removeClass('down').addClass('up');
			}
		});
		$target.toggleClass('up down');

		//GATHER SORTING ARRAY
		var $sortArray = $.makeArray();

		if($('.product-table tbody.opened').length){
			$('.product-table tbody.opened').insertBefore($('.product-table tbody:not(.opened)').eq(0));
			
			$('.product-table tbody').eq(productIndex)
			.find('tr.product-types').each(function(){
				$row = $(this);
				$absolute = $row.find('td').eq(columnIndex-1);
				if($absolute.find('img').length){
					$sortArray.push($absolute.parent().find('th span').text());
				}
			});

			if($target.is('.up')){
				$sortArray.sort();
			}else{
				$sortArray.sort().reverse();
			}
		
			$.each($sortArray,function(key,value){
				$row = $('.product-table tbody').eq(productIndex).find('tr.product-types th span:contains('+value+')').parents('tr').eq(0);
				$row.insertAfter($row.parents('tbody').eq(0).find('tr.category'));
			});
			
			$('.product-table tbody.opened').find('tr.sublisting').removeClass('sublisting');
			$('.product-table tbody.opened').find('tr.product-types').eq(0).addClass('sublisting');
		}else{
		
			$('.product-table tbody').each(function(){
				$row = $(this);
				$absolute = $row.find('.category td').eq(columnIndex-1);
				if($absolute.find('img').length){
					$sortArray.push($row.find('tr.category th').text());
				}
			});

			if($target.is('.up')){
				$sortArray.sort();
			}else{
				$sortArray.sort().reverse();
			}
			
			$.each($sortArray,function(key,value){
				$row = $('.product-table tbody').find('tr.category th:contains('+value+')').parents('tbody').eq(0);
				$row.insertAfter($('.product-table thead').eq(0));
			});			
		}
	});
	
	
	
	
	
	//Setup checkmarks
	$('table.product-table').find('.product-types').each(function(){
		$(this).find('td').each(function(i){
			if($(this).find('img').length > 0){
				$(this).parents('tbody').eq(0).find('tr.category td').eq(i).html('<img class="checked" src="/_resources/img/css/product-table-checkmark.png">');
			}
		});
	});	
	
	//setup quicker collapse and expand
	$('table.product-table .category td').each(function(){
		if($(this).find('img').length){
			$(this).addClass('consolidation');
		}
	});
	$('table.product-table .category th, table .category th').click(function(){
		$('table.product-table tbody.current').removeClass('current');
		$(this).parents('tbody').addClass('current');
		$obj = $(this).parents('tbody');
		if($obj.hasClass('opened')){
			$obj.removeClass('opened').addClass('closed');
			
			//COLLAPSES PRODUCT CHECKMARKS
			$obj.find('td.consolidation').each(function(){
				$(this).html('<img class="checked" src="/_resources/img/css/product-table-checkmark.png" />');
			});

		}else if($obj.hasClass('closed')){
			$obj.removeClass('closed').addClass('opened')
			.find('tr.product-types').eq(0).addClass('sublisting');
			$obj.find('tr.category td.consolidation').html('');
		}
		
		//RESET TO ONLY ALLOW ONE OPEN AT A TIME.
		$('.product-table tbody.opened').not('.current').each(function(i){
			$obj = $(this);
			$obj.removeClass('opened').addClass('closed');
			
			//COLLAPSES PRODUCT CHECKMARKS
			$obj.find('td.consolidation').each(function(){
				$(this).html('<img class="checked" src="/_resources/img/css/product-table-checkmark.png" />');
			});						
		});		
		
	});	

	// let's do some autocomplete
		// product search has a display field and an ID field that's populated on success.
		$('#product-name').focus(function () {
			$('#product-id-searched').val("");
		});

		// we need the ID from the add-product autocomplete form to send to the server.
		$("#product-name").result(function(event, data, formatted) {
			if (data){	$("#product-id-searched").val(data[1]);	}	
		}).blur(function(){
		    $(this).search(); //force a search afterwards 
		});

		$('#product-name').autocomplete("/products/autocomplete", {
			cacheLength: 1,
			matchContains: false,
			minChars: 1,
			max: 500,
			delay: 0,
			scrollHeight: 200
		});
	
		var searchmode = $('#mode').val();
		var acurl = "/search/autocomplete";
		if (searchmode == 'directory')
		{
			acurl = "/search/autocomplete_profile";
			$('div#facets form').submit(function ()
			{
				return false;
			});
		}
		$('.search-facets .search-input').autocomplete(acurl, {
			matchContains: true,
			minChars: 1,
			max: 500,
			scrollHeight: 300
		});
			$('#header-search').submit(function(){
				if($('#header-search-term').val() == 'search for products'){
					return false;
				}
			});
			
			$('form.advanced-search-form').submit(function(){
				if($('input#search-input').val() == 'search for products'){
					return false;
				}
			});

			
		$('#header form input, #search-terms input, .advanced-search-form #search-input').autocomplete("/search/autocomplete", {
			matchContains: true,
			minChars: 1,
			max: 500,
			scrollHeight: 300
		});

	
		// Shouldn't need to do this often, but if autocomplete results are not as expected uncomment the following temporarily
		// $('#header form input, #search-terms input, #product-name').flushCache();

	// faq expand/collapse
	enableExpand("dl.faq");
    // how it works expand/collapse
    enableExpand("dl.how");

	//LISTENER/Bubbler
	$body.click(function (event) {
		var $target = $(event.target);
		if ($target.is('.disabled') || $target.is('.disabled span')) {
			//if(!$body.is('.page-marketplace')){
			//	document.location.href="#";
			//}
			return false;
		}
		//toggle login wrap
		if($target.is('.login-link') || $target.is('.login-link span')){
			loginToggle($target);
			return false;
		}
		
		//toggle saved searches
		if ($target.is('#saved-searches-toggle')){
			$('#saved-searches').toggleClass('on');
			return false;
		}
		
		//close login wrap
		if($target.is('#login-wrap .close')){
			$target.parent().slideUp(300);
			return false;
		}
		
		//close flash notices by hand
		if($target.is('#message-wrap a.close')){
			$('#message-wrap').fadeOut('slow');
			return false;
		}
		return true;
	}); //bubbler/listener
	
	//hide stuff with the escape key. need to ensure there's not a message happening before we hide that window.
	$(document).keyup(function(event){
	    if (event.keyCode == 27) { //esc
			
			if($('.confirm').length){
				$('.confirm').remove();
				$('.jqmOverlay').remove();
			}
			if($('#login-wrap').length){
				$('#login-wrap').hide();
			}
			
			if($('.main #contact-list .contact-list')){
				$('.contact-list').remove();
			}
	    }
	});	
	
	//My Products - Table checkbox condition
	setTimeout(function(){
		$('#atable td.checked input').removeAttr('checked').attr('checked','checked');
	},1);
		
	$('#atable').click(function(e){
		var $target = $(e.target);
		var $inputParent = $target.parent('td');
		var $fullColumn = ($target.parents('tr').hasClass('check-all'))? $('#atable tbody tr').find('td:eq('+($inputParent.index()-1)+')') :false;
		var $fullRow = ($target.parent().hasClass('all-year'))? $target.parent().nextAll() : false;
		var $allColRow = $('#atable tbody td');
		var $allMatrixCheck = $('#atable tbody tr:not(.check-all) td:not(.all-year)');
		
		var $rowcount = $('#atable tbody tr').length - 1;
		
		//Add/Remove single "checked" class
		$inputParent[($inputParent.hasClass('checked')) ? 'removeClass' : 'addClass']('checked');
		
			//Add/Remove full column "checked" class
			if($fullColumn !== false){
				$fullColumn[($inputParent.hasClass('checked'))? 'addClass' : 'removeClass']('checked');
			}
			//Add/Remove full rows "checked" class	
			if($fullRow !== false){
				$fullRow[($inputParent.hasClass('checked'))? 'addClass' : 'removeClass']('checked');
			}
			
			//Add/Remove full column and row "checked" class
			if($fullColumn !== false && $fullRow !== false){
				$allColRow[($inputParent.hasClass('checked'))? 'addClass' : 'removeClass']('checked');
			}
			
			//rows matrix checking
			if($('#atable tbody td.all-year').length > 0){
				$allMatrixCheck.parent('tr').find('td.all-year').addClass('checked');
				$allMatrixCheck.not('.checked').parent('tr').find('td.all-year').removeClass('checked');
				$('#atable tbody tr.check-all td:first')[($allMatrixCheck.not('.checked').length > 0)?'removeClass':'addClass']('checked');
			}
			
			//column matrix checking
			var $changedIndex = $inputParent.index()-1;
				$('#atable tbody tr td:eq('+$changedIndex+')')[($('#atable tbody tr:not(.check-all)')
				.find('td:eq('+$changedIndex+')').not('.checked').length > 0)?'removeClass':'addClass']('checked');
			
			
			//final pass to check all checkboxes
			$('#atable td.checked input').attr('checked','checked');
			$('#atable td').not('.checked').find('input').removeAttr('checked');
		
			// save form after every toggle
			if($inputParent.is('td')){
				$(this).parents('.attr-form').each(function(){
					var data = $(this).serialize();
					var url = $(this).attr('action') + '/layout:ajax';
					$.post(url, data, function(e,a){
						//a = success	
					});
				});
			}
	});

	// save form after every toggle (attribute table done separately above)
	$('#form-product-attributes input').click(function(){
		var data = $('#form-product-attributes').serialize();
		var url = $('#form-product-attributes').attr('action') + '/layout:ajax';
		$.post(url, data, function(e,a){
			//a = success
		});
	});

	$('#saved-searches').hover(
		function(){ 
			$('#saved-searches').toggleClass('on');
		},
		function(){ 
			$('#saved-searches').toggleClass('on');
		}
	);


	if ($('body').is('.product-landing-page'))
	{
		
		$('.product-landing-page .tabs').idTabs();
		
		//if(getCookie('showsell') && getCookie('showsell') == "false" )
		//{
		//	$('.product-landing-page .tabs').idTabs(1);	
		//}
		//else
		//{
		//	$('.product-landing-page .tabs').idTabs();	
		//}
	}
	
	if ($body.is('.about-page'))
	{
		$('#sell-more').hide();
		$('#buy-more').hide();
		$('a.more').click(function(){
			var pane = $(this).attr('href');
			$(pane).toggle('fast');
			return false;
		});
		
		//all those how-to videos
		$('a.add-products').colorbox({inline:true, href: 'iframe.add-products', width:'690px', height:'415px', fixed:true});
		$('a.your-profile').colorbox({inline:true, href:'iframe.your-profile', width:'690px', height:'415px', fixed:true});
		$('a.orientation').colorbox({inline:true, href: 'iframe.orientation', width:'690px', height:'415px', fixed:true});
		$('a.hot-sheets').colorbox({inline:true, href: 'iframe.hot-sheets', width:'690px', height:'415px', fixed:true});
		$('a.video-marketplace').colorbox({inline:true, href: 'iframe.video-marketplace', width:'690px', height:'415px', fixed:true});
		$('a.video-knowledgebase').colorbox({inline:true, href: 'iframe.video-knowledgebase', width:'690px', height:'415px', fixed:true});
		$('a.video-search').colorbox({inline:true, href: 'iframe.video-search', width:'690px', height:'415px', fixed:true});
		$('a.video-directory').colorbox({inline:true, href: 'iframe.video-directory', width:'690px', height:'415px', fixed:true});
	}

	$('#resources-request-form').submit(
		function ()
		{
			var url = $(this).attr('action');
			var data = $(this).serialize();
			$.post(url, data, function (result){
				$('#resources-request-form-container').html(result);
			});
			return false;
		}
	);

	/*
		My Products/Add Products	
	*/
	
	// add product dropdown
	$('.add-product-type').hide();
	$('.add-product-button-wrap').hover(function(){
			$('.add-product-type').slideDown('fast');
		}, function(){
			$('.add-product-type').hide();
		}	
	);
	
	
	// add/edit product page
		$('select#attributes-copy').bind("change", copyProductAttributes);
		
		$('.product-list .delete').live("click", function(){
			if ($body.is('.auto-login')) 
			{
				document.location.href="#";
				return false;
			}
			var productID = $(this).parents("ul").parent("li").attr("id");
			var ul = $(this).parents("ul");
			var productName = $(this).parents("ul").next("label").find("a").html();
			var url = $(this).attr("href");
			var nameArray = '';
			
			$('.product-list input[type="checkbox"]:checked').each(function(i){
					nameArray = nameArray+$(this).prev('a').text()+',';
			});
			// if yes, go to url
			if($(this).parents('.actions').length){
				//SINGLE DELETE
				confirmIt("Are you sure you want to delete <strong>"+ productName +"</strong> from your product list?", url);
			}				
			return false;
		});	
		

		$('.product-list .deleteGeneric').live("click", function(){
			if ($body.is('.auto-login')) 
			{
				document.location.href="#";
				return false;
			}
			var productID = $(this).parents("ul").parent("li").attr("id");
			var productName = $(this).parents("ul").next("a").html();
			var children = $('li[rel='+productID+'] a.product-name');
			var url = $(this).attr("href");
			var ch = "";
			children.each(function (index) {
				if (index == 5) 
				{
					ch += '<li><strong>'+(children.length-5)+' more</strong></li>';
				}
				else if (index > 5)
				{
					return false;
				}
				else
				{
					ch += '<li><strong>' + $(this).text() + '</strong></li>';
				}
				return true;
			});
			

			// if yes, go to url
			confirmIt("Are you sure you want to delete <strong>"+ productName +"</strong> and all varieties from your product list?<br/><br/><ul>" + ch + "</ul> Please confirm that you want to delete these from your products.", url);
				
			return false;
		});		
	
		FH.areYouSure = '<span class="are-you-sure"><span class="sure-title">Are you sure?</span> <a href="#" class="sure-yes">Yes</a> <a href="#" class="sure-no">Cancel</a></span>';

		//bulk delete
		$('.product-list .list-footer button').click(function(e){
			if($('.product-list input[type="checkbox"]:checked').length > 0){

				$(this).hide();  
				
				$(FH.areYouSure).insertAfter($(this));
				
				$('.are-you-sure').find('a').bind('click', function(evt){
					if($(this).is('.sure-yes')){ 
						$(this).parents('.product-list').submit(); 
					}
					else{ 
						$('.are-you-sure').remove(); 
						$('.product-list .list-footer button').show(); 
					}
					evt.preventDefault();
				});
			}else{
				alert("No products selected");
			}

			e.preventDefault();
		});

	/*
		TODO: I think the next few lines can be moved into the product-landing-page section above
			  but that should be tested thoroughly to make sure these lines do nothing on other pages
	*/
	// what's fresh interactions
	$('#update-hot-sheet').hide();

	// $('.update-fresh').bind("click", showFresh);

	$('#update-hot-sheet').bind("submit", updateFresh);
	$('#update-hot-sheet .create-fresh').bind("click", updateAndSendFresh);
	
	$('#update-hot-sheet a.cancel').bind("click", function(){showFresh("hide");});



	//for page load
	if (location.hash == '#update-hot-sheet')
	{
		$('.product-landing-page .tabs').idTabs();	
		showFresh();
		if($('#message-wrap').length){ window.scroll(0,137); }
	}
	$(window).hashchange(function(){
		if(window.location.hash == "#update-hot-sheet"){
			showFresh();
		}
	});

			
	// Login Action
	//$('#btn_register span').live("click", registerUser);
	$('a.forgot-password').colorbox({inline:true,href:'div.forgot-password',onComplete:function(){
		
		//place already typed email into forgot password
		if($('form#form-login input[name="data[User][email]"]').val().length > 0){
			$('#cboxLoadedContent input[name="data[User][email]"]').val($('form#form-login input[name="data[User][email]"]').val());
		}
		
		//submit forgot password via ajax and return server side messages
		$('div.forgot-password a.yes').live('click',function(e){
			if($('#password-reminder').valid()){
				var $serial = $('#cboxLoadedContent .forgot-password form').serialize();
				var $theEmail = $('#cboxLoadedContent input[name="data[User][email]"]').val();
				$.ajax({
					type: "POST",
					url: "/users/reset_password",
					data: $serial,
					success: function(msg){
						passwordSuccess(msg, $theEmail);
						$.colorbox.close();
					},
					error: function(msg){
						alert('Something has gone wrong. Not helpful, we know. Please try again or contact us for help.');
					}	
				});
				e.preventDefault();
			}
		});
	},width:'375px'});

	//Registration stuff
	$('a.allaccess-info').colorbox({inline:true, href : 'div#allaccess-info', width:'500px',fixed:true});
	$('a.advantage-info').colorbox({inline:true, href : 'div#advantage-info', width:'500px',fixed:true});	
	
	$('.account-select .disabled a.select').click(function(e){
		e.preventDefault();
	});
	
	if($('form#registration-form').length){
		// $('#LocationZip').mask("99999");
		// $('.input-phone').mask("(999) 999-9999");
		$('#tos-wrap, #additional-business-categories').hide();
		$('.tos-link').click(function(){
			$('#tos-wrap').slideToggle();
			return false;	
		});

		//some basic validation
		// $('.registration-form form').bind('submit', checkRegistration);
		// $('.register-page #LocationStateId').bind('change', setCounties);
		// $('.register-page #LocationCounty').find("optgroup[label=Oregon] option:first").attr("selected", "selected"); //set the county to default to oregon on the register page
		// 
		// $('div.other').each(function(){
		// 	$this = $(this);
		// 	$this.hide();
		// 	var ip = $this.prev('div').find('input');
		// 	$this.prev('div').find('input').click(function(){
		// 		$(this).parent('div').next('div.other').toggle('fast', function () { $(this).children('input').focus(); });
		// 	});
		// });
		$('#registration-form #LocationZip,#CCBillingZip').mask("99999");
		$('#LocationZip,#LocationStateId,#LocationCity,#LocationZip,#CCBillingZip').blur(function(){
			$(this).inputSetter();
		}).inputSetter();
		$('#registration-form #ProfilePhone').mask("(999) 999-9999");
		
		$('#select-two-categories').click(function(e){
			$('#additional-business-categories').slideToggle();
			e.preventDefault();
		});
	}
	
		
 	//ADVERTISEMENT FORMS
 	
 	//PLACEMENT FORM
 	$('#contact-method').change(function(){
 		if($(this).find('option:selected').index() === 0){
 			$('.contact-info').find('ol li:eq(1)')
 			.removeClass('accessibility')
 			.next('li').addClass('accessibility');
 			$('.contact-info').find('ol li:eq(1) input').removeAttr('disabled');
 			$('.contact-info').find('ol li:eq(2) input').attr('disabled','disabled');
 			$('.contact-info li.accessibility input.error').removeClass('error');
 			$('.contact-info li.accessibility label.error').remove();	 			
 		}else{
 			$('.contact-info').find('ol li:eq(2)')
 			.removeClass('accessibility')
 			.prev('li').addClass('accessibility');
 			$('.contact-info').find('ol li:eq(2) input').removeAttr('disabled');
 			$('.contact-info').find('ol li:eq(1) input').attr('disabled','disabled'); 			
 			$('.contact-info li.accessibility input.error').removeClass('error');
 			$('.contact-info li.accessibility label.error').remove();			
 		}
 	});
 	$('a.add-placement').click(function(e){
 		$(this).prev('ol').clone().appendTo('.add-placements fieldset').insertBefore('a.add-placement');
 		$('.add-placements fieldset ol:last li label.error').remove();
 		$('.add-placements fieldset ol:last li select.error').removeClass('error');
 		e.preventDefault();
 	});
 	
 	//Hide display ad specs
 	$('ul.digital-specs').click(function(){
 		$(this).toggleClass('open');
 	});
 	
 	//Sample placement lightbox
 	$('a.sample-placements').colorbox({inline:true, href:'<img src="'+$('a.sample-placements').attr('href')+'" />',width:'800px',height:'75%'});
  
  	//Member Spotlight Image lightboxes
  	if($('.weekly-placements').length){
		$('a.freshsheet').colorbox({inline:true, href: '<img src="'+$('a.freshsheet').attr('href')+'" />',width:'800px',height:'75%'});
		$('a.members-spotlight').colorbox({inline:true, href : '<img src="'+$('a.members-spotlight').attr('href')+'" />',width:'800px',height:'75%'});
	}
  
	// email signup
	$('#individualSignupForm').submit(function () {
		var email = isValidEmailAddress($('#IndividualEmail').val());			
		if(email !== true) {
			$('#IndividualEmail').parents("div.input").addClass("error")
				.siblings('label').html('This email address doesn&#8217;t appear to have a valid format. Please take another look.')
				.addClass('error');	
		}			
		return email;			
	});

	
	$('a.farm-school').colorbox({inline : true, href : '<img src="'+$('a.farm-school').attr('href')+'" />',width:'800px',height:'75%'});
	$('a.search-preview').colorbox({inline : true,	href : '<img src="'+$('a.search-preview').attr('href')+'" />',width:'800px',height:'75%'});	
		
	///////////////////////////////////
	// Home 
	//////////////////////////////////
	if ($body.is('.home-page'))	{
		// Tabs
		$('.nav-tabbed li').each(function(i){
			i = i-1;
			$('.learn-more-container').hide().css({height:'0px'});

			$(this).click(function(e){
				$('.nav-tabbed li').removeClass('active');
				$(this).addClass('active');
				if($('.learn-more-container.showed').length){
					//Others Not Clicked
					$('.learn-more-container').not('eq('+i+')').css({display:'none',position:'absolute'}).addClass('accessibility');
					//Current Clicked
					$('.learn-more-wrap .learn-more-container').eq(i).show()
					.css({left:'922px',position:'relative',height:'294px'})
					.removeClass('accessibility').animate({
						left:'0px'
					},300);
					
				}else{
					//Frist Clicked
					$('.learn-more-wrap .learn-more-container').eq(i).css({display:'block'}).animate({height:'294px'},function(){
						$(this).addClass('showed');
					});					
				}
				e.preventDefault();
			});
		});
		
		//Close and Reset
		$('.close-learn-more').click( function(e){
			$('.learn-more-container').removeClass('showed accessibility').animate({height:'0'},function(){
				$(this).css('position','').hide();
				$('.nav-tabbed li.active').removeClass('active');			
			});
			e.preventDefault();
		});
		
		jQuery('.play-video').each(function() {
			var $this = $(this),
			type = $this.attr('class').replace(/-/g,'_').split(/\s/);				
			$(this).colorbox({
				href : '/home/' + type[1] + '/ajax',
				onComplete : function()  {
					clearInterval($.fn.rotatorTabs.rotate);				
				}
			});
		});	
		
		//Home page image lightboxes
		$('a.full-img-marketplace').colorbox({inline:true, href: '#img-marketplace img', width:'800px', height:'85%'});
		$('a.full-img-profile').colorbox({inline:true, href: '#img-profile img', width:'800px', height:'85%'});
		$('a.full-img-fresh-sheet').colorbox({inline:true, href: '#img-fresh-sheet img', width:'800px', height:'85%'});		
	}

	//CLOSE OR CANCEL ALL CREATE/EDIT A POST FORMS LIGHTBOXES
	$('#colorbox .user-cancel a, #colorbox a.user-cancel').live('click',function(e){ $.colorbox.close(); e.preventDefault(); });
			
	
	///////////////////////////////////
	//  Marketplace
	//////////////////////////////////

	if ($body.is('.requests-page') || 
		$body.is('.request-page') || 
		$body.is('.dashboard2-page')
		){
		prAddFormInit();
		
		////////////////////////
		// CREATE A POSTING
		////////////////////////		
		$('a.add-post').colorbox({href:'/marketplace/add/layout:ajax', 
			onComplete:function(){
				$('#cboxLoadedContent form:last').wrap('<div class="forms" />');	
				rteInit();	
			},
			height:'500px',
			width:'775px',
			fixed:true
		});	


		//SKIP THIS STEP
		$('.user-skip a').live('click',function(e){
			$('#cboxLoadingOverlay').show();
			var $lastform = $('#cboxLoadedContent form:last');
			$('#cboxLoadedContent').append('<div class="forms" />');
			var $lastformwrap = $('#cboxLoadedContent .forms:last');
			$.get($lastform.attr('action')+'/layout:ajax',function(data){
					$lastformwrap.html(data).prevAll('.forms').hide();
					$.colorbox.resize();
					$('#cboxLoadingOverlay').hide();						
			});	
			e.preventDefault();				
		});

		//EDIT PREVIOUS FORM
		$('a.edit-previous-form').live('click',function(e){
			$(this).parents('.forms').prev('.forms').show().end().remove();
			$.colorbox.resize();
			e.preventDefault();
		});
		
		//CREATE POST FORM'S HIDE/DISPLAY STEPS
		$('#ProductRequestMarketplaceCategoryId').live('change',function(){
			var optionvalue = $('option:selected',this).val();
			$('ol.dependent li:eq(0) select').val(0);//reset select option of product type
			
			if(optionvalue){
				$('ol.dependent > *').css({display:'none'}); //reset display of radios if you will
				if(optionvalue == '1'){
					$('ol.dependent li:first-child').css({display:'block'});
					$('ol.dependent li.product').show();
				}
				if(optionvalue == '2'){
					$('ol.dependent li.transport').show();
				}
				if(optionvalue == '4'){
					$('ol.dependent li.service').show();
				}
				
				$('ol.dependent button.secondary-action,span.user-cancel').css({display:'inline-block'});
				
			}else{
				$('ol.dependent > *').hide();
			}
			$.colorbox.resize();
		});	
		
		//AVAIBILITY TOGGLE
		$('#ProductRequestAvailability0,#ProductRequestAvailability1').live('click',function(){
			if($('#ProductRequestAvailability1').is(':checked')){
				$('fieldset.date-available').show();
			}else{
				$('fieldset.date-available').hide();
			}
		});				

		//////////////////////
		// EDIT A POSTING
		/////////////////////   		
		//OPEN LIGHTBOX ALSO ON CLICK
		$('a.edit-post').click(function(e){
			$.colorbox({href:$(this).attr('href')+'/layout:ajax',
				onComplete: function(){
					$('#cboxLoadedContent form:last').wrap('<div class="forms" />');
					$('input.input-phone').mask("(999) 999-9999");
					$('.input-setter').inputSetter(); 
					if($('input[name="data[ProductRequest][availability]"]').is(':checked')){
						$('.date-available').show();
					}
				},width:'800px',fixed:true
			});		
			e.preventDefault();
		});						
				
		$('input[name="data[post-remove]"]').live('click',function(){
			$('.post-actions ol.dependent').hide();
			$(this).parents('.label-full').next('ol.dependent').show().find('*').show();			
		});		


		//READ-POST LEFT HAND SEARCH FORM SUBMIT
		$('a.read-post').live('click',function(e){
			$('#facets form').attr('action',$(this).attr('href')).unbind('submit').submit();
			e.preventDefault();
		});	
		
		//NEXT AND PREVIOUS POST
		$('a.prev-post,a.next-post').click(function(e){
			$('form#view-pagination').attr('action',$(this).attr('href')).submit();
			e.preventDefault();
		});
	}
		
	
	///////////////////////////////////
	// MY Marketplace
	//////////////////////////////////		
	if($body.is('.my-marketplace')){
		$('#ProductRequestAutoRepost,#ProductRequestFulfilled').change(function(){
			$obj = $(this);
			$.ajax({
				type: "POST",
				url:$obj.parents('form').attr('action'),
				data:$('#ProductRequestAutoRepost,#ProductRequestFulfilled').parents('form').serialize()
			});
		});	
	}
	
	if($('.page-marketplace').length){
		marketPlaceInit();
	}

		$('.toggle td.title').live('click',function(e){
			if($(this).hasClass('open')){
				$(this).removeClass('open');
				$(this).parents('.toggle').next('tr.full-text').removeClass('open').hide();
			}else{
				$(this).addClass('open');
				$(this).parents('.toggle').next('tr.full-text').addClass('open').show();
			}
			
		});
			$('td.title a').click(function(e){
				e.preventDefault();
			});

		$("#radio-toggle li").buttonset();
		
	// Marketplace Lightboxes
	//marketplace - edit dashboard settings
	$('a.edit-display').colorbox({href: '/marketplace/edit_preferences/ajax', width:'770px', height:'88%'});
	
	//simple lightboxes for product management
	$('a.learn-more-hot-sheet').colorbox({inline:true, href:'#learn-more-hot-sheet',width:'600px', height:'51%', fixed:true,onComplete:function(){$('#colorbox #learn-more-hot-sheet').show();}});
	$('a.learn-more-about').colorbox({inline:true, href:'#learn-more',width:'600px', height:'35%', fixed:true,onComplete:function(){$('#colorbox #learn-more').show();}});

	//simple lighboxes for search/member dir
	$('a.learn-more-search').colorbox({width:'800px', height:'60%', inline:true, href: '#learn-more-search'});
	$('a.learn-more-directory').colorbox({width:'800px', height:'60%', inline:true, href: '#learn-more-directory'});
	
	//Product taxonomy Lightbox
	$('a.view-taxonomy').colorbox({href: '/categories/tree/layout:ajax', width:'800px', height:'460px', fixed:true});		
		

	
	
	///////////////////////////////////
	// Profile Page
	//////////////////////////////////
	if ($body.is('.profile-page'))
	{
		$('.ie7 .breadcrumbs li').not(':last').append('<span class="separator">></span>');
		//$('.ie7 .breadcrumbs .last').append('');
		
		//@TODO Move to GA_trackings.js
		$('a.email').live('click', function ()
		{
			try {
				_gaq.push(["_trackEvent", "Profile", "email", $(this).attr('href')]);
			}
			catch(err) {
				// fail silently if you have to
			}
		});
		$('a.url').live('click', function ()
		{
			try {
				_gaq.push(["_trackEvent", "Profile", "website", $(this).attr('href')]);
			}
			catch(err) {
				// fail silently if you have to
			}
		});
		
		$('.cross-reference li.show-more').showMoreList('cross-ref-overflow');
		var $xreftbody = $('#table-xref-edit tbody');
		$('#xref-filter').change(function(){
			var target = "xref-" + $(this).val();
			
			if(target != "xref-all"){
				$xreftbody.find('tr').hide();
				$xreftbody.find('.'+target).show();
			}else{
				$xreftbody.find('tr').show();
			}
			$('#table-xref-edit .check-all input').attr('checked', false);
		});
		
		$('#table-xref-edit .check-all input').live('change', function(){
			if($(this).is(':checked')){
				$xreftbody.find('tr:visible').find('input').attr('checked', 'checked');
			}else{
				$xreftbody.find('tr:visible').find('input').attr('checked', false);
			}
		});
		
		
		
		$('#products_buy > ul ul').hide();
		$('#products_buy ul').not(':visible').each(function(){
			$(this).parent().addClass('closed');
		});
		$('#products_buy ul > li').bind('click',function(e){
			if($(this).find('ul').is(':visible')){
				$(this).addClass('closed').removeClass('open').find('ul').hide();
			}else{
				$(this).addClass('open').removeClass('closed').find('ul').show();
			}
			e.preventDefault();
		});
	}
	
	// Profile Page Lightboxes
	//edit business info
	$('a.edit-info').colorbox({href:'/users/edit_profile_business_info/ajax',height:"95%", width:"800px", fixed:true});
	
	//edit about us
	$('a.edit-about-us').colorbox({href:'/users/edit_profile_about_us/ajax',height:"95%", width:"800px", fixed:true});
	
	//edit how to do business with us
	$('a.edit-how-to').colorbox({href:'/users/edit_profile_how_to_do_biz/ajax', height: "95%", width:"800px", fixed:true});
	
	//view members video
	$('.member-videos li:not(:eq(0))').each(function(){
		var $this = $(this),
			id = $this.find('a').attr('class'),
			$video = $this.find('#'+id);

		$this.find('a').colorbox({inline:true, href: $video, fixed:true});
			
	});
	
	//edit member videos
	$('a.edit-videos').colorbox({href:'/users/edit_profile_videos/ajax',height:'95%',width:'800px',fixed:true});
	
	//edit member images
	$('a.edit-images').colorbox({href: '/users/edit_profile_images/ajax',height:'95%',width:'800px',fixed:true});
	
	//edit member documents
	$('a.edit-documents').colorbox({href: '/users/edit_profile_documents/ajax'});
	
	//edit recommendations
	$('a.edit-recommendations').colorbox({href:$('a.edit-recommendations').attr('href')+'/layout:ajax'});	
	
	//edit references 
	$('a.edit-references').colorbox({href: '/users/edit_profile_references/layout:ajax',height:'95%',width:'800px',fixed:true});	

	//edit social
	$('a.edit-social').colorbox({href: '/users/edit_profile_media_badges/layout:ajax'});	
	
	//recommend this user
	$('a.recommend-user').colorbox({href: $('a.recommend-user').attr('href')+'/layout:ajax'});
	
	//If we're coming from the dashboard, open up some ajax windows
	if (window.location.hash == "#edit-info") {
		$.colorbox({href: '/users/edit_profile_business_info/ajax', width:'780px', height:'85%', fixed:true, opacity:'.75'});
	};

	if (window.location.hash == "#edit-about-us") {
		$.colorbox({href: '/users/edit_profile_about_us/ajax', width:'780px', height:'85%', fixed:true, opacity:'.75'});
	};
	
	if (window.location.hash == "#edit-how-to") {
		$.colorbox({href: '/users/edit_profile_how_to_do_biz/ajax', width:'760px',fixed:true, opacity:'.75'});
	};

	if (window.location.hash == "#edit-recommendations") {
		$.colorbox({href: $('a.edit-recommendations').attr('href')+'/layout:ajax', width:'760px',fixed:true, opacity:'.75'});
	};
	
	// profile page sidebar links. Forces breaks in the links so sidebar doesn't break.
	$("#user-data dl dd a").bnsp();
	
	if($('.requests-page #my-requests').length){
		$('.tabs li a').click(function(){
			return true;	
		});
	}		

	// nicEdit RTE
	rteInit();
	
	// initialize rating
	// expects foodhub_rating object to be on page
	if(typeof foodhub_rating !== 'undefined') {
		jQuery.each(foodhub_rating, function(i, val) {
			ratingInit(i,foodhub_rating[i]['data'],foodhub_rating[i]['rating'],foodhub_rating[i]['options'],foodhub_rating[i]['enable']);
		});
	}
	
	// Resources
	// show feedback form
	$('.feedback form').hide();
	$('.feedback a.trigger').click(function() {
		$('.feedback form').fadeIn('fast');
		var content = $(this).html();
		$(this).before('<span>' + content + '</span>').remove();
		return false;
	});

	// full content toggles
	$('.full-content, .toggle-content').hide();
	$('.preview h5').bind('click', function(){
		var obj = $(this).parents('li');
		if(!obj.is('.animated')) {
			obj.addClass('animated').toggleClass('open').find('.full-content').slideToggle('fast', function () {
				setTimeout(function() { obj.removeClass('animated'); }, 250);
			});
		}
		return false;
	});
	$('.toggle-categories > h3').prepend('<span class="indicator"></span>').bind('click', function () {
		var $this = $(this),
			obj = $this.next('div.toggle-content');
		if(!obj.is('.animated')) {
			$this.toggleClass('open');
			obj.addClass('animated').slideToggle('fast', function () {
				setTimeout(function() { obj.removeClass('animated'); }, 250);
			});
		}
		return false;	});
	
	// play video from thumbnail in various sized containers
	$('.video-trigger').bind('click', function () {
		var obj = $(this),
			url = obj.attr('href'),
			width = obj.parents('.resource-video').width();
			height = width * 0.5625;
		obj.parents('.resource-video').empty().html('<iframe src="' + url + '" width="' + width + '" height="' + height + '" frameborder="0"></iframe>');
		return false;
	});

	// profile picture filmstrip turn
	$('.profile-pictures .prev, .profile-pictures .next').click(function(e){
		var $obj = $(this),
			$first = $obj.parent().find('li').eq(1),
			$last = $obj.parent().find('li:last-child').prev();
		if($obj.is('.next')){
			$first.remove().appendTo('.profile-pictures ul');
			$obj.appendTo('.profile-pictures ul');
		}else{
			$obj.parent().prepend($last).prepend($obj);
		}
		e.preventDefault();
	});
		//profile picture large preview
		$('.profile-pictures li').not('.prev,.next').find('a').click(function(e){
			$(this).parents('ul:eq(0)').prev('div.large').find('img').attr('src',$(this).attr('href'));
			e.preventDefault();
		});	

	//profile recommended list
	$('.recommend-list > ul').children('li').each(function(i){
		if(i>2){
			$(this).hide();
		}
	});
		$('a.more-recommendations').click(function(e){
			$('.recommend-list > ul').children('li').show();
			$(this).hide();
			e.preventDefault();
		});
	
	$('.recommend-list h2').click(function(){
		if($('.recommend-list').hasClass('closed')){
			$('.recommend-list').removeClass('closed');
		}else{
			$('.recommend-list').addClass('closed');	
		}
	});

	//expand and collapse on profile page
		$('.toggle-wrap.closed').hide();
		
		$('.summary h2:first-child').click(function(){
			$(this).toggleClass('closed');
			$(this).parents('.summary').children('.toggle-wrap').toggle();
		});

	///////////////////////////////////
	// Account Page Lightboxes
	//////////////////////////////////
	
	//Edit Password
	$('a.edit-pass').colorbox({href: '/users/edit_account_password/ajax'});
	
	//Edit Credit Card
	$('a.card-edit').colorbox({href: $('a.card-edit').attr('href')+'/layout:ajax',width:'800px'});	
	
	//edit communication preferences
	$('a.edit-comm').colorbox({href: '/users/edit_account_communication/ajax'});

});// document ready / end jquery functions

marketPlaceInit = function(){
	$('#facets form').submit(function(e){
		if(!ajaxManager){
			var ajaxManager = $.manageAjax.create('hashQueue', { 
				queue: 'clear', 
				cacheResponse: true, 
				preventDoubleRequests: true,
				abortOld: true
			});						
		}
		ajaxManager.add({
			type: "POST",
			url: $('#facets form').attr('action'), 
			data: $("#facets form").serialize(),
			beforeSend:function(){
				$('#primary').find('*')
				.css({opacity:'0.6'}).end()
				.append('<div class="loading" />');
			},
			success: function(results){
				$('#primary')
				.html(results);
				$('#primary #marketplace-post').remove();
			}
		});	
		e.preventDefault();		
	});
	$('#facets input:not(.nohash), #facets select:not(.nohash)').hashhistory({
		onChange:function(){
			 //reset previously sent ajax requests
			if(!ajaxManager){
				var ajaxManager = $.manageAjax.create('hashQueue', { 
					queue: 'clear', 
					cacheResponse: true, 
					preventDoubleRequests: true,
					abortOld: true
				});						
			}
			$('#url-hash').val(window.location.href);	
			ajaxManager.add({
				type: "POST",
				url: $('#facets form').attr('action'), 
				data: $("#facets form").serialize(),
				beforeSend:function(){		
					$('#primary').find('*')
					.css({opacity:'0.6'}).end()
					.append('<div class="loading" />');
				},
				success: function(data){
					$('#primary')
						.html(data);
					$('#primary #marketplace-post').remove();
				}
			});
			
			//BLOCK FORM FROM SUBMITTING BUT RATHER FIRE OFF AJAX
			$('#facets form').submit(function(e){
				ajaxManager.add({
					type: "POST",
					url: $('#facets form').attr('action'), 
					data: $("#facets form").serialize(),
					beforeSend:function(){
						$('#primary').find('*')
						.css({opacity:'0.6'}).end()
						.append('<div class="loading" />');
					},
					success: function(data){
						$('#primary')
							.html(data).trigger('resultsLoaded');

						IX_scrollPage($('h1'), 'fast');
								
					}
				});				
				e.preventDefault();
			});
		}
	});
	
	/*
	* Redirect autocomplete url so it only shows the current tab.
	* Example:
	* Products
	* http://dev.foodhub.isitedesign.net/marketplace/autocomplete/1?q=sheep
	* Events
	* http://dev.foodhub.isitedesign.net/marketplace/autocomplete/6?q=sheep
	*
	* */

	// tab index and db cateogry numbers don't line up.
	var activeTabToMPCategory = {
		"0" : "1",
		"1" : "2",
		"2" : "4", 
		"3" : "6"

	};
	// default is product search
	var marketplaceACURL = "/marketplace/autocomplete/";

	// pretty round about way to do this
	if($('.nav-tabbed').find('.active')){
		var MPactiveTab = $('.nav-tabbed').find('.active').index();
		marketplaceACURL = "/marketplace/autocomplete/" + activeTabToMPCategory[MPactiveTab];
	}
	$('#facets .search input[type="text"]').autocomplete(marketplaceACURL, {
		matchContains: true,
		minChars: 1,  
		max: 500,
		scrollHeight: 300
	});
	
	//PAGEINATION
	$('.pagination a').live('click',function(e){
		e.preventDefault();
		if(!ajaxManager){
			var ajaxManager = $.manageAjax.create('paginationQueue', { 
				queue: true, 
				cacheResponse: true, 
				preventDoubleRequests: true,
				abortOld: true 
			});						
		}				
		ajaxManager.add({
			type: "POST",
			url: $(this).attr('href'), 
			data: $(".marketplace form.search").serialize(),
			beforeSend:function(){
				$('#primary').find('*')
				.css({opacity:'0.6'}).end()
				.append('<div class="loading" />');
			},					
			success: function(data){
				$('#primary')
					.html(data)
					.trigger('resultsLoaded');
				
				IX_scrollPage($('h1'), 'fast');

			},
			abortOld: true
		});
		
	});
	
	//Distance Helper
	$('a.distancehelp').colorbox({inline:true, href:'#distance-help'});
					
	//END CREATE POST
	$('#facets .range').slider({
		range: "max",
		value: 400,
		min: 0,
		max: 400,
		create: function(event, ui){
			$('input#distance').addClass('hashing');
		},
		slide: function(event, ui){
			$('input#distance').prev('label').text("0 to "+ui.value+" miles");					
		},
		change: function( event, ui ) {
			$('input#distance').val(ui.value).focus().blur();
		}
	});		

	

};


$.fn.showMoreList = function(className){
/*
	Pass a classname to toggle that class on click. 
	TODO: Should be extended so that if the param passed is a number, toggle everything beyond that number (ala search facets).
*/
	// Show more for cross referencing on profile pages. 
	return this.each(function() {
	
		var $this = $(this),
			// be safe.
			$target = $this.is('li') ? $this : $this.parent('li'),
			$parent = $target.parent('ul');
			$parent.find("."+className).hide();
			
			
			$target.click(function(){

				$parent.find("."+className).toggle();
				if($parent.is('.expanded')){
					$target.find('a').text('…show more');
					$parent.removeClass('expanded');
				}else{
					$target.find('a').text('…show less');
					$parent.addClass('expanded');
				}
				return false;
			});
			//$target.find('a').click(function(e){ e.preventDefault();});

	});		
};

$.fn.showMoreListAJAX = function(count){
	// Show more on profile pages. 
	// er, not used ATM (11/11). See http://fh-xref-dev/pages/proto/cross-referencing/cross-referencing to see it in action
	return this.each(function() {
		
		var $this = $(this),
			// be safe.
			$target = $this.is('li') ? $this : $this.parent('li'),
			$parent = $target.parent(),
			contentLink = $target.find('a').attr('href');
			contentLink = contentLink + '/layout:ajax';
			
		$this.position = $parent.find('li').index($target) - 1;
		

		$target.click(function(e){
				e.preventDefault();
				if($target.is('.loaded')){
					this.doToggle(e);
				}else{
					this.loadContent();
				}
		});
		
		this.doToggle = function(e){
			var $t = $(e.target);
			var $listitems = $parent.find('> li:gt('+$this.position+')').not('.show-more');
			
			if($parent.is('.expanded')){
				$target.find('a').text('…show more');
				$parent.removeClass('expanded');
			}else{
				$target.find('a').text('…show less');
				$parent.addClass('expanded');
			}
				$listitems.toggle();
		};

		this.loadContent = function(){
			$parent.addClass('loading');
			$.get(contentLink, function(ret){
				$target.addClass('loaded').find('a').text('show less');
				$this.$tempTarget = $target.clone();

				$parent.addClass('expanded').removeClass('loading').append(ret).append($target);
			
			});
		};

	});		
};


$.fn.hashhistory = function(options,onChange){
	var defaults = {
		indexAttribute: 'name',
		delimiter: ':',
		divider: '/',
		selectNull:0 
	};
    var options = $.extend({ 
    	onChange: function(){
    		
    	},
    	onReady: function(){
    		
    	}
    }, defaults, options);
    o = options;
    
	$(this).addClass('ajaxhist').live('change blur',function(){
		var $obj = $(this), type = $obj.get(0).tagName.toLowerCase();
		//INPUT TYPES
		if(type==='input'){
			//RADIO BUTTON
			if($obj.is('[type="radio"]')){
				$('input['+o.indexAttribute+'="'+$obj.attr(o.indexAttribute)+'"]').removeClass('hashing');
				if($obj.is(':checked')){
					$obj.addClass('hashing');
				}else{
					$obj.removeClass('hashing');
				}
			}
			
			//CHECKBOX			
			if($obj.is('[type="checkbox"]')){
				if($obj.is(':checked')){
					$obj.addClass('hashing');
				}else{
					$obj.removeClass('hashing');
				}		
			}
			//TEXT
			if($obj.is('[type="text"]')){
				if($obj.val().replace(/ /g,'').length !== 0){
					$('input['+o.indexAttribute+'="'+$obj.attr(o.indexAttribute)+'"]').removeClass('hashing');
					$obj.addClass('hashing');
				}else{
					$obj.removeClass('hashing');
				}
			}			
					
		//SELECT TYPES
		}else if(type==='select'){
				if($obj[0].selectedIndex != o.selectNull){
					$obj.addClass('hashing');
				}else{
					$obj.removeClass('hashing');
				}
		}
		
		var hash = '/';
		
		$('.hashing').each(function(i){
			var index = $(this).attr(o.indexAttribute),
			value = ($(this).val())? $(this).val(): $(this).attr('value');
			hash = 	hash+
					index+
					o.delimiter+
					value+
					o.divider; //index( (.*): ):value( :(.*) )
			// console.log('hashing hash', hash);
			
		});
		window.location.hash = hash;
	});
	 
	anychange();

	function anychange(){
		// console.log('anychange');
		
		//PARSER HASH AND DISTRIBUTE
		$('input.ajaxhist[type="checkbox"]').removeClass('hashing').removeAttr('checked');
		$('input.ajaxhist[type="radio"]').removeClass('hashing').removeAttr('checked');
		$('input.ajaxhist[type="text"]').removeClass('hashing').val('');
		if($('select.ajaxhist').length){
			$('select.ajaxhist').val($('select.ajaxhist option:first').val()).removeClass('hashing');
		}

		var hash = window.location.hash.replace(/(.*)#/g,'').split(o.divider);
		hash.shift();
		hash.pop();
		
		//remove empty array items
		$.each(hash,function(index,value){
			
			var trimedindex = new RegExp(o.delimiter+'(.*)','g'),
				trimedvalue = new RegExp('(.*)'+o.delimiter,'g');

			var valued = value.replace(trimedvalue,''),
				indexed = value.replace(trimedindex,'');

			//checkbox  
			$('.ajaxhist[type="checkbox"]['+o.indexAttribute+'="'+indexed+'"][value="'+valued+'"]')
			.attr('checked','checked').addClass('hashing');
			
			//radio
			$('.ajaxhist[type="radio"]['+o.indexAttribute+'="'+indexed+'"][value="'+valued+'"]')
			.attr('checked','checked').addClass('hashing');

			//text
			$('.ajaxhist[type="text"]['+o.indexAttribute+'="'+indexed+'"]')
			.val(valued).addClass('hashing');					

			//select
			$('select.ajaxhist['+o.indexAttribute+'="'+indexed+'"]').addClass('hashing')
			.find('option[value="'+valued+'"]').attr('selected','selected');
			
			//sliders
			if(indexed == 'data[Distance][type]'){
				//Condition for range sliders who may have an empty hashed value
				if(!valued.length){
					//console.log('hitting');
					setTimeout(function(){
						$('label[for="distance"]').text('0 to 400 miles');
						$(".range").slider('value',400);	
					},800);
				}		
			}										
		});
		
	}

	if($('body:not(.hashhistory)')){
		setTimeout(function(){
			options.onReady.call(this);	
		},500);
	} $('body').addClass('hashhistory');	

	$(window).hashchange(function(){
		anychange();
		options.onChange.call(this);
	});
};

//REBUILD SEARCH ELEMENTS FROM HASH
$.fn.hashToElement = function(){
	
    // extend the options from pre-defined values:
    var options = $.extend({
        callback: function() {}
    }, arguments[0] || {});
	if(window.location.hash){
		if(!ajaxManager){
			var ajaxManager = $.manageAjax.create('hashQueue', { 
				queue: 'clear', 
				cacheResponse: true, 
				preventDoubleRequests: true,
				abortOld: true
			});						
		}		
		ajaxManager.add({
			type:'post',
			url:'/search/build_facets/'+window.location.hash.replace(/\//g, '||').replace(/:/g,'!').replace('#',''),
			success:function(data){
				if(window.location.hash){
					$('#facets ol.services').html(data)
					.find('.locations').remove().end()
					.find('ol.services').unwrap();
					
					$('#facets ol.locations').html(data)
					.find('.services').remove().end()
					.find('ol.locations').unwrap();
				}
				
			    // call the callback and apply the scope:
				options.callback.call(this);
			}
		});		
	}else{
		options.callback.call(this);
	}
};


function toolTipInit(){
	$('a.help').tooltip({ 
	    bodyHandler: function() {
	        return '<p>'+$($(this).attr("href")).html()+'</p>'; 
	    }, 
	    showURL: false,
	    extraClass: 'help-tooltip',
	    top: -25
	}).click(function(e){ e.preventDefault();	});
	
	$('.help.buyer').tooltip({ 
		 bodyHandler: function() {
			  return '<p>'+$($(this).parent().find('div.buyer')).html()+'</p>'; 
		 }, 
		 showURL: false,
		 top: -25
	});
	
	$('.help.seller').tooltip({ 
		 bodyHandler: function() {
			  return '<p>'+$($(this).parent().find('div.seller')).html()+'</p>'; 
		 }, 
		 showURL: false,
		 top: -25
	});		
	
	$('#atable thead th[title]').tooltip({ 
		delay: 30,
		fade: 150,
		showURL: false,
		showBody: " - ",
		extraClass: 'help-tooltip help-tooltip-table-header',
		top: -25
	});
	
	//new form tool tip - facing the opposite way
	$('a.help.right').tooltip({ 
	    bodyHandler: function() {
	        return '<p>'+$($(this).attr("href")).html()+'</p>'; 
	    }, 
	    showURL: false,
	    extraClass:'help-tooltip right',
	    top:-25,
	    left:-380
	}).click(function(e){
		e.preventDefault();
	});
	$('a.help-title').tooltip({ 
	    bodyHandler: function() {
	        return '<p>'+$(this).attr("data-tooltip")+'</p>'; 
	    }, 
		delay: 0, 
		track: false,
	    showURL: false,
		positionLeft: true ,
	    extraClass:'help-tooltip right',
	    top:-25,
	    left:-40
	});

	$('.help-text').hide();
}

/*
	FoodHub JS Functions
*/

// initialize RTE
// run after DOM load and after AJAX request for interface html
// apply using custom by class function
function rteInit () {
		//set configuration
		var editors = nicEditors.applyToClass({
			iconsPath: '/_resources/img/css/nicEditorIcons.gif',
			buttonList: ['bold', 'italic', 'underline', 'ol', 'ul', 'removeformat', 'hr', 'image', 'upload', 'link', 'unlink', 'fontFormat', 'xhtml']
		}, 'nicEdit');
		
		//value setter into orignal textarea
		$('.nicEdit-main').keyup(function(){
			var $obj = $(this),
				$textarea = $obj.parent('div').next('textarea.nicEdit'),
				value = $obj.text();
			$textarea.val(value);
		});
}

function removeRte(elm){
	$(elm).html('');
}



/**
 * Use for displaying the unread message count in the nav menu item. 
 * TODO: update to include the iphone circle thing from the comp
 */
function getUnreadMessageCount(){
	url = "/messages/unreadMessageCount";
	$.ajax({
		type: "POST",
		url: url,
		success: function(msg){
			var num = parseInt(msg, 10);
			if (num > 0)
			{
				alert($('ul#nav a.nav-messages').text(num + " Messages"));
			}
		},
		error: function(msg){
			alert(msg);
		}	
	});	
}


// set some constants
function FHGlobalBits () {
	this.loader = '<h2 class="loader">Loading...</h2>';
	this.fevent = '';
	this.ftarget = '';	
	}


var FH = new FHGlobalBits;


function fhUserDashboard(){
	if($('body').is('.dashboard-page')){
		var widgetState, newVal;

		//attach the togglers
		$('.widget h2').prepend("<span class='toggler'></span>");

		//if a cookie has been set, let's hide those.
		if(getCookie('collapsedWidgets')){
			widgetState = getCookie('collapsedWidgets');
			$(widgetState).each(function(){
				$(this).toggleClass("closed").find('.content').hide();
			});
		}else{
			setCookie('collapsedWidgets','');
			widgetState = getCookie('collapsedWidgets');
		}
		
		
		// toggler clicks
		$('.widget h2 span').click(function(e){
			var $theWidget = $(this).parents('.widget');			
			widgetState = getCookie('collapsedWidgets');
			
			if($theWidget.is('.closed')){
				//don't think this matters
			}
			// toggle it
			toggleWidgets($theWidget);	
			
			// build the new cookie value
			newVal = "";
			$('.closed').each(function(){
				newVal = newVal + "#"+ $(this).attr('id') + ",";
			});
			
			setCookie('collapsedWidgets', newVal);

		});
		
	} //dashboard/myfoodhub-page
}

function prAddFormInit()
{
	jQuery("#ProductRequestMarketplaceCategoryId").change(prAddFormTypeChange);
	jQuery("#othercat").hide();
}

function prAddFormTypeChange()
{
	if (jQuery("#ProductRequestMarketplaceCategoryId option:selected").text() == 'Other')
	{
		jQuery("#othercat").show();
	}
	else
	{
		jQuery("#ProductRequestOtherCategoryName").val("");
		jQuery("#othercat").hide();
	}
}



/*
	// login functions	
*/
function loginToggle($target){	
	var $loginWrap = $('#login-wrap');

		if ( $loginWrap.find('h3.success').length) {
			 $loginWrap.find('h3.success').remove();
		}
		
	if ($target.attr('class') == 'login-link nav-item' || $target.is('#header-search button')) {
		var off = $target.offset(),
			top = off.top + 39,
			left = off.left;
		
		$loginWrap.appendTo('body').css({top: top, left: left}).show();
		$('.forgot-password').hide();
		
		
		if($loginWrap.find('.kicker-text').length < 1){
			$loginWrap.find('ul').after('<p class="kicker-text">Not a member? <a href="/users/register">Join now!</a></p>');
		}else{
			$loginWrap.find('.title-text').html('Not a member? <a href="/users/register">Join now!</a>');
		}
		
		if($loginWrap.find('.title-text').length < 1){
			$loginWrap.find('legend').after('<p class="title-text">Please sign in to access ' + $target.text() + '</p>');
		}else{
			$loginWrap.find('.title-text').text('Please sign in to access ' + $target.text());
		}

	}
	else {
		$('#login-wrap').find('p.title-text, p.kicker-text').remove();
		$('.forgot-password').show();
		$('#login-wrap').appendTo('#user-bar').css({top: '1.5em', right: '12em', left: ''}).slideDown(200).find('#email-login').focus();

	}

 	if($target.is('#header-search button') ){
		$loginWrap.css({left:left-180, top: off.top + 25});
	}
}


// login box registration
function registerUser(){
	var $obj = $('#form-login, #form-sign-in');
	// var inputs = $('#form-login').serialize();
	$obj.die("submit", fhCheckLogin);
	$obj.attr("action", "/users/register");
	$obj.submit();
	return false;
}


function passwordSuccess(msg, email){
	
	var message = {
			error : 'We could not find the email address <em>' + email +'</em>. Please check it and try again, or click the join button to sign up.',
			success : 'Success! <br />Please check your email. Password reset instructions have been sent to <em>' + email + '</em>.'
		};
	
	if ($('#login-wrap:visible').length) {
		
		if(msg == "0"){
			$('#login-wrap h4').remove(); //get rid of any existing error messages.
			$('#login-wrap label[for^=email]').before('<h4 class="error">' + message.error + '</h4>');
		}else if(msg == "1"){
			$('#login-wrap h3.success, #login-wrap h4').remove(); //get rid of any existing error messages.'
			$('#login-wrap .error').removeClass('error');
			$('#login-wrap').prepend('<h3></h3>');	
			$('#login-wrap h3').addClass('success').html(message.success);
		} else {
			$body.prepend(msg);
		}
		
	} else {
		
		var status = msg == "0" ? 'error' : 'success';
		$('#message-wrap').remove();
		$('#wrapper').prepend('<div class="' + status + '" id="message-wrap"><a class="close-window" title="Close this" href="#">close</a><div class="message success" id="flashMessage">' + message[status] + '</div></div>');
	}

}


//so we can confirm stuff first. this is called from confirmIt, generally.
function ajaxIt(url){
	// curently being used on delete product but only if specifically called - atm it's being skipped.
	
	var prodID = $('a[href='+url+']').parents(".actions").parent("li");
	
	$.ajax({
	  type: "POST",
	  url: url,
	  success: function(msg){
		$(prodID).hide("slow");
	  },
	  error: function(msg){
		alert(msg);
	}	
	});	
	
	//$(prodID).hide("slow")
	return true;	
}

//manage product functions

//update fresh sheet
function showFresh(hideIt){
	if(hideIt == "hide")
	{
		$('#primary div, #products-header, p.footer').show();
		// $('.product-landing-page .tabs').idTabs();	
		$('#update-hot-sheet').hide();
		window.location.hash = "";
	}
	else
	{
		$('#primary div, #products-header, p.footer').hide();
		$('#update-hot-sheet').show();
	}
	return false;
}

function updateFresh () {
	
}
// save the form, then send it. triggered from inside of the update-hot-sheet 'send' button
function updateAndSendFresh(e){
	var url = $('#update-hot-sheet').attr('action'),
		data = $('#update-hot-sheet').serialize();

	$.post(url,data,function(ret){
		window.location = $(e.target).attr('href');
	});
	e.preventDefault();

}

function copyProductAttributes() {
	// what are we sending
	var attributeSourceID = $("option:selected", this).attr("value");

	// clear out all the previously checked attributes
	$('fieldset input:checked').removeAttr("checked");
	// add a loading message
  	$(this).after("<p class='temp-message'>Loading Attributes. One Moment.</p>");

	$.ajax({
		type: "GET",
		dataType: "json",
		url: "/users_products/copyAttributes/" + attributeSourceID,
		success: function(msg){			
			$.each(msg, function(){				
				//find the input with 'this' as its value and check it				
				$("input[value='"+this+"']").attr("checked", "checked");
			});
		},
		error: function(msg){
			alert(msg);
		},
		complete: function(){
			$('.temp-message').remove(); //hide the loading message
		}
		
	});
	
	return false;
}

/*
		generics and resuables
*/

/*nicEdit in lightbox heading position fix*/
jQuery.nicEditModalFix = function(){

	$('.nicEdit-panelContain .nicEdit-panel > div, .nicEdit-panelContain .nicEdit-panel > div div').bind('click',function(){
		$top = parseInt(jQuery(this).offset().top, 10) + parseInt(jQuery(this).height(), 10);
		jQuery('body > div[unselectable="on"]').css({top:$top+'px',marginLeft:'5px'});	
	});		

	$('form.edit-profile').bind('scroll',function(){
		jQuery('body > div[unselectable="on"]').hide();
	});
		
	//copy height fix for rte that exceeds height of screen.
	$('.nicEdit-main').keyup(function(){
		$(this).parents('form').lightboxHeight();
	});	
};

// confirm modal
// pass in a message and a function to run if the user clicks "yes"
// if Callback is a string, it will redirect on "YES" click.
// 'args' are stuff you can pass to the callback function
// yes and no are button text. (not implemented)
function confirmIt(msg,callback,args,yes,no) {
	jQuery('body').append('');
	jQuery.colorbox({inline:true,href:'<div class="window" style="overflow:hidden;"><p class="confirm-message">'+msg+'</p><a href="#" class="tertiary-action yes">Yes</a><a href="#" class="tertiary-action user-cancel">Cancel</a></div>',
	onComplete:function(){

		if(yes)	{ jQuery('.window .yes').text(yes);	}
		if(no)	{ jQuery('.window .confirm-cancel').text(no); }
	
  		jQuery('#colorbox').find('a')
			.click(function(){
			if(this.className == 'tertiary-action yes'){			
				if(typeof callback == 'string'){ 
					window.location.href = callback;
				} else if (args){
					callback(args);
				} else {
					callback();
				}
			}	
		jQuery.colorbox.close();
		});	
	
	},width:'400px'});
};

//confirm modal
// same as above but with less action.
/* 
function confirm(msg, callback) {
	jQuery('body').append('<div class="confirm"><p class="confirm-message"></p><a href="#" class="yes" tabindex="1">Yes</a><a href="#" class="confirm-cancel jqmClose" tabindex="2">Cancel</a></div>');
	jQuery.colorbox({inline:true,href:'.confirm', width:"400px", height: "400px"});

  jQuery('#colorbox')
    .find('p.confirm-message')
      .html(msg).focus()
    .end()
    .find('a')
      .click(function(){
        if(this.className == 'yes'){			
			(typeof callback == 'string') 
					? window.location.href = callback 
					: callback();
		}
        jQuery.colorbox.close();
      });
}
*/

//Confirm modal for profile edit lightbox
function confirmEdits(msg, callback) {
	
	jQuery('form').append('<div class="confirm"><p class="confirm-message"></p><a href="#" class="confirm-save" tabindex="1">Save and Close</a><a href="#" class="confirm-continue jqmClose" tabindex="2">Continue Editing</a><a href="#" class="confirm-close" tabindex="3">Close Window</a></div>');
	jQuery.colorobx({inline:true,href:'.confirm'});

  jQuery('#colorbox')
    .find('p.confirm-message')
      .html(msg).focus()
    .end()
    .find('a')
      .click(function(){
        if(this.className == 'confirm-save'){
			
			$('.nicEdit-Content').next('textarea').text($('.nicEdit-main').html()); //set textarea with RTE contents
			$(this).closest('form').submit();//submit form
			
		} else if(this.className == 'confirm-close'){			
			(typeof callback == 'string') 
					? window.location.href = callback 
					: callback();
		}
        jQuery.colorbox.close();
      });
}

function checkRegistration(){
	var errors = false;
	
	$('label.error-help').remove();
	
	// if($('#jj993j2f2j3l').val() != ""){
	// 	cl("that's not empty");
	// }else{
	// 	cl("empty!");
	// }
	
	//how are our passwords?
	var pass1 = $('#UserPassword').val();
	var pass2 = $('#UserPasswordConfirm').val();
		
	if (pass1.length < 6) {
		$('#UserPassword').parent("div.input").addClass("error");
		errors = true;
	}
	else if (pass1 != pass2) {
		$('#UserPasswordConfirm').parent("div.input").addClass("error");
		$('#UserPasswordConfirm').before('<label class="error-help" for="UserPasswordConfirm">Please ensure that you&#8217;ve entered the same password both times.</label>');
		errors = true;
	}
	else if (pass1 !== "") {
		$('#UserPasswordConfirm').parents("div.input").removeClass("error");
		$('#UserPasswordConfirm').siblings("label.error-help").remove();
	};
	
	// you. must. comply.
	if($('#tos-agree').attr("checked") !== true) {
		errors = true;
		if($("#tos-agree-error").length < 1){
			$('#tos-agree').parents("fieldset.checkradio").prepend('<label for="tos-agree" id="tos-agree-error" class="error">You must read and agree to the FoodHub Terms of Service.</label>');
			// $('#tos-agree').parents("fieldset.checkradio").addClass("error").prepend('<label for="tos-agree" id="tos-agree-error" class="error">You must read and agree to the FoodHub Terms of Service.</label>');
			//$('#tos-agree').hide();
		}
	}
	
	// if you comply, let's be polite.
	if ($('#tos-agree:checked').length) {
		$("#tos-agree").parents("label").siblings("label.error").hide();
		// $("#tos-agree").parents("label").parent(".checkradio").removeClass("error");
	}	
	
	// nothing can be empty. well, nothing with a label. 
	$("#primary label").not('.optional,#jj993j2f2j3l-label').next("input,select").not('.optional').each(function() {
		if ($(this).val() === "" || $(this).val() == $(this).prev('label').text()) {
			errors = true;
			$(this).parents("div.input").addClass("error");
			$(this).parents('.sub-set').addClass("error");
		}
		else {
			$(this).not('#UserPasswordConfirm,#UserPassword').parents("div.input").removeClass("error");
			$(this).not('#UserPasswordConfirm,#UserPassword').parents(".sub-set").removeClass("error");
		}
	});
	
	// make sure something is checked
	$('.register-page #primary .checkradio').each(function () {		
		var legend = jQuery(this).find('legend');	
		if (jQuery(this).find('input:checked').length === 0) {
			errors = true;
			legend.addClass('error');
		} else {
			legend.removeClass('error');
		}		
	});
	
	// is that a real(ish) email?
	var email = $('#UserEmail').val();
	if (email !== "") {
		if(isValidEmailAddress(email) !== true) {
			$('#UserEmail').parents("div.input").addClass("error");	
			$('#UserEmail').prev("label").html("This email address doesn&#8217;t appear to have a valid format. Please take another look.");
			errors = true;
		}
	}		

	
	// if anything failed, you. shall. not. pass.
	if (errors === true){
		var firstError = $(this).find(".error:eq(0)");
		firstError.find('input:visible:first').focus();	//focus on the first error
		IX_scrollPage(firstError, 'fast');
		$(this).addClass("errors");
		return false;
	}
	
	return true;
	
}

function setCounties(){
	var $this = $(this);
	var selected = $this.find(":selected").text();
	//var countyFocus = $('#LocationCounty').find("optgroup[label="+selected+"] option:first")
	$('#LocationCounty').find("optgroup[label="+selected+"] option:first").attr("selected", "selected");
}

function IX_scrollPage(target, speed){
	speed !== "" ? speed : speed = fast;
	$('html, body').animate({
		scrollTop: $(target).offset().top
	}, speed);
}

function toggleWidgets(e){
	$(e.target).parent('h2').next('.content').slideToggle().end().end().parents('.widget').toggleClass("closed");
}

function redirect(location){
	window.location.href = location;
}

// returns true if email is valid.
function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function filterResults(){
	//insert the filter nav
	$('fieldset.sort').parent('form').before(resultsFilter);

	var toggled = "";

	$('#resultsFilter a').click(function(){
		resultsToggle($(this));

		$('#resultsFilter .active').each(function () {
			toggled = toggled + '.' + $('a', this).attr('class') + ',';
		});

		setCookie('results', toggled, 30);
		toggled = "";

		return false;
	});

	var toggleInit = getCookie('results');
	//console.log("toggleInit: "+ toggleInit);

	if(getCookie('results')){
		$(toggleInit).click();
	} else {
		$('.t-description').click();
	}	
}

var resultsFilter = '<div id="resultsFilter" style="float: right; font-size: .8em"> <ul class="actions"><li><h3 style="padding-top: 4px">Show:</h3></li><li><a href="#" class="t-description">description</a></li><li><a href="#" class="t-name">name</a></li><li><a href="#" class="t-phone">phone</a></li><li><a href="#" class="t-fax">fax</a></li><li><a href="#" class="t-email">email</a></li><li><a href="#" class="t-address">address</a></li></ul></div>';

function resultsToggle(clicked){
	var $clicked = $(clicked),
		cliClass = $clicked.attr('class'),
		toggle	 = cliClass.replace("t-", "c-");

	$('.'+toggle).toggle();
	$clicked.parent('li').toggleClass('active');

	return false;
}


// @cookie
// Cookies get/set/delete
// there is also a jQuery cookie plugin that does more magic but seems to usually be overkill
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) { return null;	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	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() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}
function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
// end cookies


// clean console.log
function cl(){ if(window.console) { var args = [].splice.call(arguments,0); console.log(args.join(" ")); } }//cl()
// example: cl("If you use cl() instead of console.log(), it won't break IE when you forget to take it out.");

// if exists, jq style.
// if ($('#foo').exists()){ action! }
jQuery.fn.exists = function(){return jQuery(this).length;};

// attach to an input, grab its label, insert the label into the input, hide the label.  
jQuery.fn.inputSetter = function(lower,text) {	
	return this.each(function() {
		
		var $input = $(this);
		var $label = $("label[for='"+$input.attr("id")+"']").not('.error');
		var labeltext = text ? text : $input.val() !== "" ? $input.val() : lower && lower==1 ? $label.text().toLowerCase() : $label.text();
		$label.hide();

		if($input.is(':password')) {
			var $fake = jQuery('<input value="' + labeltext + '" class="' + $input.attr('class') + '" />');
			$input.hide().addClass('settered');			
			$fake.focus(function() {
				jQuery(this).hide();
				$input.addClass('editmode').show().focus();
			}).insertBefore($input);
			$input.blur(function() {
				if (!this.value.length) {
					jQuery(this).removeClass('editmode').hide();
					$fake.show();
				}
			});				
		} else {		
			$input.val(labeltext).addClass('settered');	;		
			$input.focus(function() {
				jQuery(this).addClass('editmode');
				if (this.value == labeltext) {
					if (lower && this.value != $label.text().toLowerCase()) return;
					if (this.value != $label.text()) return;
					this.value = "";
				}
		
			}).change(function() {
				jQuery(this).addClass('changed');
			}).blur(function() {
				if (!this.value.length && !$(this).is('.changed')) {
					jQuery(this).removeClass('editmode');
					this.value = labeltext;
				}
			});			
		}
	});
};

// That's right, the ORIGINAL input setter, if you don't want your label value to stick. Could be merged into Input setter, but not sure how 
jQuery.fn.originalinputSetter = function(lower,text) {	
	return this.each(function() {
		var $input = $(this);
		var $label = $("label[for='"+$input.attr("id")+"']").not('');
		var labeltext = text ? text : $input.val() !== "" ? $input.val() : lower && lower==1 ? $label.text().toLowerCase() : $label.text();
		$label.hide();
	
			$input.val(labeltext).addClass('settered');	;		
			$input.focus(function() {
				jQuery(this).addClass('editmode');
				if (this.value == labeltext) {
					this.value = "";
				}
		
			}).blur(function() {
				if (!this.value.length) {
					jQuery(this).removeClass('editmode');
					this.value = labeltext;
				}
			});			
	});
};




jQuery.validator.addMethod("isEqualTo", function(value, element, param) {
	return $(element).val()==$(element).prev("label").text();
}, "error");



// generic tab builder
jQuery.fn.idTabs = function(tab) {	
	return this.each(function() {
		var $container = jQuery(this), 
			$tabs = jQuery("a", this),
	 		panes = new Array();

		$tabs.each(function () {
			var $this = jQuery(this);

			// using the href to make the collection of panes			
			var pane = $this.attr('href');
			if (pane.indexOf("#") !== 0) {
				return true;
			};
		 	panes.push(pane);

			$this.bind("click", function(){
				//build the jq selector. cheap.
				jQuery(panes.join(",")).hide();

				//do some class switching
				$container.find('.active').removeClass('active');
				$this.parent("li").addClass("active");

				jQuery(pane).show();

				///////////////////////////////////
				// Product Landing Page
				//////////////////////////////////
				//if ($('body').is('.product-landing-page'))
				//{
				//	
				//	$('div.sell-actions,div#whats-fresh')[(pane == '#products-buy')? 'hide' : 'show']();
				//	$('div.buy-actions')[(pane == '#products-buy')? 'show' : 'hide']();					
				//	if (pane == '#products-buy')
				//	{		
				//		setCookie('showsell', 'false', 30);	
				//	}
				//	else
				//	{
				//		setCookie('showsell', 'true', 30);	
				//	}
				//}


				return false;
			});
			return true;
		});
		
		// set which tab to show
		// if .default is available, get its index and set it. else, check for a tab index passed in or set to 0
		var show = jQuery('a.default',$container).length ? $tabs.index(jQuery('a.default')) : tab || 0;
		
		// optionally, use this to make tabs hashable. Note: doesn't make clicking the tabs hashable, only provides for linking directly to them
		// urltab = the hash in the url
		// show = if urltab isn't empty or a default link is checked, decide which of those two is true: if urltab, set it, otherwise set to a.default. If neither, set to tab or  0
		// this means the url hash is more important than the default class set in the html
		// 
		// var urltab = window.location.hash;
		// var show = urltab != "" || jQuery('a.default',$container).length ? urltab != "" ? $tabs.index(jQuery('a[href='+urltab+']')) : $tabs.index(jQuery('a.default')) : tab || 0;
		
		// this line is pretty gross, but cheap
		// make sure the tab we think we can show is actually there. if so, click it. else click the first tab
		$tabs.eq(show).length ? $tabs.eq(show).click() : $tabs.eq(0).click();
	});
};


	
// update text somewhere else.	
jQuery.fn.changeText = function(updatee) {	
	return this.each(function() {
		var newText = $(this).text();
		$(updatee).text(newText);
	});
};

// for replies, we want the cursor at postition 1, not the end of the text.
jQuery.fn.setCursorPosition = function(pos) {
	if (jQuery(this).get(0).setSelectionRange) {
		jQuery(this).get(0).setSelectionRange(pos, pos);
	} 
	else if (jQuery(this).get(0).createTextRange) {
		var range = jQuery(this).get(0).createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
};


//character counter for textareas
// requires a label with the quanity in a span <label class="charactersremaining" for="mytextareaid"><span>250</span> characters remaining</label>
// attach it like so: $(".charactersremaining").charactersRemaining();
jQuery.fn.charactersRemaining = function() {
	
    // prevent elem has no properties error
    if (this.length === 0) { return(this); }	
	
	function cr($obj) {

		var counter = {
			
			$target	 	: jQuery("#"+$obj.attr('for')),
			$span		: $obj.find("span:first"),
			maxvalue 	: $obj.children('span:first').text(),
			remaining	: null,
			
			init : function() {
				counter.remaining = counter.maxvalue - counter.$target.val().length;
				counter.$span.text(counter.remaining);
				counter.$target.bind("keyup keydown",counter.tally);			
			},
			
			tally : function() {
								
				if (counter.$target.val().length > counter.maxvalue) { 
					counter.$target.val(counter.$target.val().substring(0, counter.maxvalue));
				}
				counter.$span.text(counter.maxvalue - counter.$target.val().length);
				
			}
			
		};

		// init the counter
		counter.init($obj);

	};
	
	// return jquery - create new cr instance
	return this.each(function() {
		new cr(jQuery(this));		
	});	
	
};

// create open/close. receives dl.
var enableExpand = function(el) {
	$(el).addClass("expander").find("dd").hide().end()
		.find("dt").prepend('<a  class="toggle" href="#">+</a>').click(function(){
			var textinsert = $("a.toggle",this).text() == "+" ? "-" : "+";
			$(this).toggleClass("open").next("dd").slideToggle("fast").end()
			.find("a.toggle").text(textinsert);			
		}).hover(function(){
			$("a",this).addClass("hover"); $(this).addClass("hover"); }, function(){ $("a",this).removeClass("hover"); $(this).removeClass("hover");
		}).find("a.toggle").click(function(){ $(this).parents("dt").click(); return false; });		
};


/*
	
	@breakingNonSpace
	10.03.08 - pdf
	
	Breaking Non-Space
	
	Insert either &#8203; character or <wbr> tag for < IE7 to allow line
	break in the middle of email address, url, etc.
	
	apply bnsp to choosen elements.
	takes optional array of characters to break at which replaces the defaults,
	just be careful of regex special characters: $("a").bnsp(["$","domain"]);
	$(".bnsp a").bnsp();
	$(".bnsp li").bnsp(["sis","best","name"]);

*/
jQuery.fn.bnsp = function(options) {	
	// if array of characters, use it. else use default set.
	var c = options || ["@","/"];	
	// set bnsp entity based on browser support
	var b = jQuery.browser.msie && jQuery.browser.version < 7 ? "<wbr>" : "&#8203;";	
	// loop and return
	return this.each(function() {		
		var $this = jQuery(this); // store $(this) for use inside another function		
		// loop through each item in character array
		jQuery.each(c, function() {
			var rx = new RegExp(this,'g'); // create new regex object with current character
			$this.html($this.html().replace(rx,this+b)); // replace character with itself + nbsp entity
		}); // end array loop		
	});// end return
}; // end bnsp

// end breakingNonSpace

//browser sniffing to insert body classes. only use for css! except...
// var sniff set to be a global var for conditional testing for ie.
jQuery.fn.sniff=function(s){var platform,v=function(s){var ua=navigator.userAgent.toLowerCase();ua=ua.substring(ua.indexOf(s+'/')+(s.length+1));return ua.substring(0,1);};jQuery.browser.chrome=/chrome/.test(navigator.userAgent.toLowerCase());if($.browser.msie){snuff="ie ie"+jQuery.browser.version.substring(0,1);}
	else if($.browser.mozilla){if(navigator.userAgent.toLowerCase().indexOf('firefox')!=-1){var temp=v("firefox")==3&&!!document.createElement('video').canPlayType?"3-5":v("firefox");snuff="ff ff"+temp;}
	else{snuff="mz";}}
	else if($.browser.chrome){snuff="ch ch"+v("chrome");$.browser.safari=false;}
	else if($.browser.safari){snuff="sf sf"+v("version");}
	else if($.browser.opera){snuff="op";}
	if(navigator.platform.indexOf("Win")!=-1){platform="windows";}
	else if(navigator.platform.indexOf("Mac")!=-1){platform="mac";}
	else if(navigator.platform.indexOf("Linux")!=-1){platform="linux";}
	return this.each(function(){jQuery(this).addClass(platform+" "+snuff);});
};

//get text nodes
jQuery.fn.extend({
   textNodes: function() {
      return jQuery(
         jQuery.map( this, function(n){
            return jQuery.grep(n.childNodes, function(n) {
               return n.nodeType == 3;
            });
         })
      );
   }
});


// IX_rotator plugin
(function($) {
	// plugin definition
	$.fn.rotatorTabs = function() {
	
		var $this = $(this);
		
		$this.prepend('<li class="controller"><a class="btn-arrow btn-previous" href="#">Previous</a></li>').append('<li class="controller"><a class="btn-arrow btn-next" href="#">Next</a></li>');
	
		$.fn.rotatorTabs.rotate = setInterval(function() { $this.trigger('rotate'); }, 7000);

		var cycle = function(o,d) {
			var	current = o.find('.active'),
				items = o.find('li').not('.controller');
				target = current[d](':not(.controller)').length ? current[d]() : d == "next" ? items.eq(0) : items.eq(items.length-1);
						
			current.removeClass('active');
			target.find('a').click();
									
		};
		
		var pause =  function() {
			$this.parents('#tab-wrap').find('video').each(function(){
				this.pause();
			});
		};

		function isJQueryEvent(e){
		    return !(($.browser.msie ? "cancelBubble" : "bubbles") in e);
		}
		
		// return and iterate
		return this.each(function() {
			$('a.btn-arrow', this).live('click', function(e) {
				clearInterval($.fn.rotatorTabs.rotate);
				var dir = $(this).is('.btn-previous') ? 'prev' : 'next';
				cycle($(this).parents('ul.tabs'),dir);
				pause();
				e.preventDefault();
			});
			$(this).bind('rotate', function(e) {
				cycle($(e.target),'next');
				pause();
				e.preventDefault();
			});
			$('a',this).not('.btn-arrow').bind('click', function(e){
				if(!isJQueryEvent(e)) {
					clearInterval($.fn.rotatorTabs.rotate);
				}
				pause();
				e.preventDefault();
			});
		});
	
	};
	
})(jQuery);



////////////////////////////////////////
//	NEW PRODUCT ADDITION UI
////////////////////////////////////////
jQuery(function($) {
		
		$body = $('body');
		$('#atable table').tableHovers();
		
		var $addForm = $(".add-proto-add-products"),
		toggler = '<span class="toggler show">Show Types</span>';

		$("li>ul", $addForm).hide().parent('li').prepend(toggler);

		// tree action
		$('.toggler').live("click", function(){
			$(this).next('ul').toggle().end().toggleClass('show');
		});
		
	//$('#products-wrap').hide();
	//$('#add-products-checks-wrap select').bind("change", function(){$('#products-wrap').show();});
	$('#add-products-checks-wrap select').bind("change", function(){$('#category-select-form').submit();});
	$("#products-added")[($("#CategoryId option:selected").text() === '')? 'hide' : 'show' ]();

	//attribute tables
	$(".add-product-page-v2 #atable td")
		.each(function(){
			
			var $td = $(this),
				$tChk = $td.find("input[type='checkbox']");
				
			if($tChk.is(':checked')){ $td.addClass('checked'); }	

			$tChk.css("opacity","0");
			$tChk.focus(function(){
				$(this).parent('td').trigger('mouseenter');
			},function(){
				$(this).parent('td').trigger('mouseout');
			}
			);
		});

	//bubbler/listener

	//terrible.
	$('.check-all td').hover(
		function() {
			var $this 	= $(this),
				$tr 	= $this.parents('tr'),
				$table 	= $this.parents('table'),
				tdIndex	= $tr.children().index($this) - 1;
			
		$this.addClass('checked-dim');
		$("tr", $table).find("td:eq("+tdIndex+")").addClass('checked-dim');	
	},
	function() {
		var $this 	= $(this),
			$tr 	= $this.parents('tr'),
			$table 	= $this.parents('table'),
			tdIndex	= $tr.children().index($this) - 1;
	
		$this.removeClass('checked-dim');
		$("tr", $table).find("td:eq("+tdIndex+")").removeClass('checked-dim');
	});
		

	//Conditional close button for lightbox
	$.fn.conditionalClose = function(win){	
		var closeButton = $(this);
		closeButton.show().bind('click', function(){
			$.customClose(win);
		});
	};
	
	
	$.customClose = function(window){
		if ($('form').hasClass('edited')) { 
			confirmEdits('You have unsaved changes to your profile.', function(){
				$('.jqmWindow').jqmHide();
				$('.jqmOverlay').remove();
			});
			return false;			
		} 
		$(window).jqmHide();
		return true;
	};
	
	
	//Colorbox extending for default functionality
	$(document).bind('cbox_complete', function(){
		$('body').css({overflow:'hidden', overflowX:'hidden', overflowY:'hidden'});
		var $box = $('#cboxLoadedContent'),
		originalClose = $.colorbox.close;
		
		//if lightboxed form has class of detect-change 
		//we setup confirm messages upon and edit.
		$('#cboxLoadedContent form.detect-change').detectChanges();
      
		$.colorbox.close = function(){ 
			if($('form.edited.detect-change:visible',$box).length){     				
				$box.append('<div class="confirm"><p class="confirm-message">You have unsaved changes.</p><a href="#" class="confirm-save" tabindex="1">Save and Close</a><a href="#" class="confirm-continue jqmClose" tabindex="2">Continue Editing</a><a href="#" class="confirm-close" tabindex="3">Close Window</a></div>');
				$('.confirm',$box).show();
				$('.confirm').find('a').click(function(e){
						if(this.className == 'confirm-save'){
							$('#cboxLoadingOverlay').show().text('Saving, please wait ...');
							var $serial = $('form',$box).serialize();
							$.post($('form',$box).attr('action')+'/layout:ajax',$serial,function(data){
								$box.find('.forms').hide().end().append('<div class="forms">'+data+'</div>');
								$('#cboxLoadingOverlay').hide();
								$.colorbox.resize();
							});
							$('.confirm',$box).remove();
						}else if(this.className == 'confirm-close'){
							$('form',$box).removeClass('edited');			
							originalClose();
						}
						$('.confirm',$box).hide().remove();
					e.preventDefault();
				});   
				return; 
			}else{ originalClose(); }
		};
		rteInit();
		setTimeout(function(){	
			//IE7 / 8 RTE width fixing
			$('#colorbox div.input.textarea > div').css({width:'80%'});
		},100);     
	}).bind('cbox_open',function(){
		
		$('#cboxOverlay').css({opacity:'0.75'});
	}).bind('cbox_cleanup',function(){
		if($('#colorbox .refresh-page').length){
			window.location.reload(true);
		}
	}).bind('cbox_closed',function(){
		$('body').attr('style','');
	});	
	
	//Resize lightbox height to be smaller than the viewport
	$.fn.lightboxHeight = function(){
		var $obj = $(this).parents('.jqmWindow'),
		$objHeight = parseInt($(this).height(), 10),
		$winHeight = parseInt($(window).height(), 10);

		if($objHeight > $winHeight){
			$obj.find('div.form form').css({height:$winHeight - 50+'px'});
			$obj.scrollTop(0);
		}
	};
		
	//getCss()
	$.getCSS = function( url, media ) {
	  jQuery( document.createElement('link') ).attr({
				 href: url,
				 media: media || 'screen',
				 type: 'text/css',
				 rel: 'stylesheet'
	  }).appendTo('head');
	}; 

	//Detect form changes
	$.fn.detectChanges = function() {
		$('input, select, textarea, .nicEdit-main').change(function(){
			if($(this).parents('#colorbox').length){
				$('#colorbox form').addClass('edited');
			}else{
				$('form').addClass('edited');
			}
		});
		//doesn't work with the nicEdit rte, so making it really aggressive, but it still won't save.
		$('.input.textarea').click(function(){
			$('form').addClass('edited');		
		});
	};
});//jQuery ready


/*
 * $("foo").closer()	
 * attaches a 'close' link to any window. normally just hides the window. to remove it from the dom, add the "remove" param.
 * $("foo").closer("remove") 	
 */
jQuery.fn.closer = function(remove, callback) {
	return this.each(function() {
		var $closeWhat = jQuery(this);
		var closeit = '<a href="#" title="Close this" class="close-window">close</a>';
		$closeWhat.prepend(closeit);
		//var theID = $closeWhat.attr("id");	
		//cl(theID);
			
		//var closeit =	$('<a href="#" title="Close this" class="close-window">close</a>').click(function(){})
				
		$closeWhat.find('.close-window').click(function() {
			if(remove)	{ $closeWhat.hide("normal", function(){ $(this).remove(); }); } 
			else 		{ $closeWhat.hide();   }
			if (typeof callback == "function") { callback(); }
			return false;
		});
/*
		jQuery('.close-window').hover(function(){
			cl($(this).parent().attr("id"));
		})
*/

	});	
};



