/* Search field with dropdown filter list */

var searchFiltersValue = new Array("","type:Recipe","type:Testing","type:Tasting","type:How To Cook","type:Video");
var searchFiltersText = new Array("Search All","Search Recipes","Search Equipment Reviews","Search Taste Tests","Search How to Cook","Search Videos");

function setSearchFieldContents(n) {
	//alert($("#global_search_query").val()+", "+searchFiltersText[n]+", "+n);
	if ($.inArray($("#global_search_query").val(), searchFiltersText) > -1) {
		$("#global_search_query").val(searchFiltersText[n]);
	};
};

/* ------------------------------------------------------------------------------------------------------------------------------------------------------------------------  */
/* Functions to care form validation / popup / form submit for the marketing ad at the bottom of the home page */

function popUpMessage ( url, w, h ) { 
	args = "width=" + w + ",";
	args += "height=" + h + ",";
	args += "location=0" + ","
	args += "menubar=0" + ","
	args += "resizable=0" + ","
	args += "scrollbars=0" + ","
	args += "status=0" + ","
	args += "titlebar=0" + ","
	args += "toolbar=0" + ","
	args += "hotkeys=0" + ","
	
	var demo_window = window.open(url, "main", args);
	demo_window.focus();
}

function pop_conf (myform) {
    var browser_name = navigator.appName;
	var width = 450;
	var height = 600;
	if (browser_name.indexOf("WebTV") != -1) return null;
	if (parseInt(navigator.appVersion) >= 4 )
	{xposition = (screen.width - width) / 2;
		yposition = (screen.height - height) / 2;
	}

	args = "innerWidth=" + width + ",";
	args += "innerHeight=" + height + ",";
	args += "location=0" + ","
	args += "menubar=0" + ","
	args += "resizable=0" + ","
	args += "scrollbars=0" + ","
	args += "status=0" + ","
	args += "titlebar=0" + ","
	args += "toolbar=0" + ","
	args += "hotkeys=0" + ","
	args += "screenx=" + xposition + ",";
	args += "screeny=" + yposition + ",";
	args += "left=" + xposition + ",";
	args += "top=" + yposition;

	var name = myform.cds_name_b.value;
	var address1 = myform.cds_address_1_b.value;
	var address2 = myform.cds_address_2_b.value;
	var city = myform.cds_city_b.value;
	var state = myform.cds_state_b.value;
	var zip = myform.cds_zip_b.value;
	var email = myform.cds_email_b.value;
	var incode = myform.free_trial_incode.value;
	
	var error = validateform(name, address1, address2, city, state, zip, email);
	
	if (error){
		alert(error);}
	else{

		if (address2 == "Address (Line 2)"){address2 = "";}
	
		var fields = "cds_name=" + name + "&cds_address_1=" + address1 + "&cds_address_2=" + address2 +"&cds_city=" + city + "&cds_state=" + state + "&cds_zip=" + zip + "&cds_email=" + email +"&cds_response_key=" + incode;
	
		var conf_page = "/ads/freetrial_CID_conf.asp?";
		var conf_page = conf_page + fields;
		
		var demo_window = window.open(conf_page, "main", args);
			demo_window.focus();
	}
}

function validateform(name, address1, address2, city, state, zip, email)
{
    var error = '';
	var descriptionType = '';

	if ((name == "") || (name == "Name"))
	{ error = error + 'Please enter Full Name.\n' }
	
	if ((address1 == "") || (address1 == "Address (Line 1)"))
	{error = error + 'Please enter Address.\n'; }
	
	if ((city == "") || (city == "City")) 
	{error = error + 'Please enter City.\n'; }

	if ((state == "") || (state == "State")) 
	{error = error + 'Please enter State.\n'; }

	if ((zip == "") || (zip == "Zip Code")) 
	{error = error + 'Please enter Zip.\n'; }
	
	if ((email == "") || (email == "E-mail (required)") )
	{error = error + 'Please enter Email.\n'; }

	if (!isEmail(email))
	{error = error + 'Please enter valid Email.\n'; }

	if(error) {
	error = 'The following error(s) occurred:\n'+error;}
	else {error = ''; }
	
	return error;
}

function isEmail(str) {
	  // are regular expressions supported?
	  var supported = 0;
	  if (window.RegExp) {
		var tempStr = "a";
		var tempReg = new RegExp(tempStr);
		if (tempReg.test(tempStr)) supported = 1;
	  }
	  if (!supported) 
		return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
	  return (!r1.test(str) && r2.test(str));
}
function collectcdsb(myform,link)
{
//pull data from the CDS form to send to the Prepop Gateway
var name = myform.cds_name_b.value;
var address1 = myform.cds_address_1_b.value;
var address2 = myform.cds_address_2_b.value
var city = myform.cds_city_b.value;
var state = myform.cds_state_b.value;
var zip = myform.cds_zip_b.value;
var email = myform.cds_email_b.value;

var error = validateform(name, address1, address2, city, state, zip, email);

if (error){
	alert(error);}
else{
	if (address2 == "Address (Line 2)"){address2 = "";}

	var fields = "&cds_name=" + name + "&cds_address_1=" + address1 + "&cds_address_2=" + address2 +"&cds_city=" + city + "&cds_state=" + state + "&cds_zip=" + zip + "&cds_email=" + email;
	var cdslink = link + fields
	
	window.open(cdslink, "window");
	}

}
/* -------------------------------------------------------------------------------------------------------------------------------------------------------------------  */

$(document).ready(function() {

	// SEARCH

	$("#btn_search_filter_select").click(function() {
		$("#search_filter_select").show();
		$("#search_filter_select").focus();
	});
	
	$("li.search_filter_option").hover(function() {$(this).addClass("hover");}, function () {$(this).removeClass("hover");});

	
	$("#search_filter_select li:first").click(function() {
		$("#search_filter_select").hide();
	});
	
	$("li.search_filter_option a").click(function() {
	   
		var catID = $("li.search_filter_option").index($(this).parent());
		$("input[name=filters]").val(searchFiltersValue[catID]);
		if ($.inArray($("#global_search_query").val(), searchFiltersText) > -1) 
			{ $("#global_search_query").val(searchFiltersText[catID]); }
		$("#search_filter_select").hide();
	});
	

	
	$('#global_search').validate({

			    rules: {
			        query: {
			            required: true,
			            goodSearchQuery: true
			        }
			    },
			    invalidHandler: function(form, validator) {
                    var errors = validator.numberOfInvalids();
                    if (errors) {
                        alert('Please enter a search term.');
                    }
                },
                messages: {
                	query: {
                		required: ""
                	}
                }
			});
			
	$("#global_search_query").focus(function() { 
		lastVal = $(this).val();
		$(this).val("");
		$(this).attr("style","color:#000");
	});
	
	$("#global_search_query").blur(function(){
		if ($(this).val() == ""){
			$(this).val(lastVal);
			$(this).attr("style","color:#555");
		} else { 
			$(this).unbind('focus');
		}
	});
	
  	// SHOW/HIDE register panel
  	
	$("a.form_toggle").click(function(){
		$("#utilities li #join").hide();
		$(this).parent().children('div').show().children('div').show();
		$(this).parent().find('input.email').focus();
		return false;
	});
	$('#utilities li div').click(function(e) {
		e.stopPropagation();
	});
	$(document).click(function() {
		$('#utilities li div').hide();
	});
	$(".faq").click(function(){
		$('#utilities li div').hide();
	});
			
	$(".close a").click(function(){
                $(this).parent().parent('#utilities li div').hide();
                return false;
	});
    
	//$("input[type=text]", $('form:not(.form_submission)')).label().keydown(function(e){e.stopPropagation();});
    

/* Other jQuery Stuff */
	var lastVal = ""; // Global var to hold the last state of a field contents
	$(".shadowedInput:not(.static), .dropdown").focus(function(){
		lastVal = $(this).val();
		$(this).val("");
	});
	$(".shadowedInput:not(.static), .dropdown").blur(function(){
		if ($(this).val() == ""){
		$(this).val(lastVal);
		} else { 
			$(this).unbind('focus');
	}
	});
	

	
	$("#ciehide").click(function(){
		/*ciehideurl = $.query.SET("disableCIE", "y"); alert(ciehideurl);*/
		tb_show('','/search/cieask.html?width=598&height=200&TB_iframe=true',false);

		 });	
		 
	$("#cieconfirm").click(function(){
		document.cookie = "disableCIE=y"; "expires=Mon, 1 Jun 2020 20:20:20 UTC";
		parent.location.reload();
		});
		
	$('#paywallSignupForm').validate({
		rules: {
			cds_email: {
				required:true,
				email: true
			}
		},
		invalidHandler: function (form, validator) {
			var errors = validator.numberOfInvalids();
			if (errors)  {
				alert('Please enter your e-mail.');
				$('#paywallSignupForm input.error').val('');
			}
		}
	});
	
	$('#signupForm').validate({
		rules: {
			email: {
				required:true,
				email: true
			}
		}, 
		messages: {
			email: ""
		},
		invalidHandler: function (form, validator) {
			var errors = validator.numberOfInvalids();
			if (errors)  {
				alert('Please enter your e-mail.');
				$('#paywallSignupForm input.error').val('');
			}
		}
	});
	
	$('#paywallSignupForm').submit(function() {
	
    addToRegistration_Abandonment_WithForm(this.attr('action'), this.get()[0]);
    
    return true;
  });
	
	jQuery.validator.addMethod("goodSearchQuery", function(value, element) {
		return this.optional(element) || jQuery.inArray(value,searchFiltersText) < 0;
	}, "");
	
	$('#searchBoxForm ').validate({
	rules: {
		query: {
			required: true
		}
	},
	invalidHandler: function(form, validator) {
		var errors = validator.numberOfInvalids();
		if (errors) {
			alert('Please enter a search term.');
			$('input.error').val('');
		}
	}

	});
	
	
		$('#joinOverlay').validate();
	

	$('#searchAgain').validate({
	rules: {
		query: {
			required: true
		}
	},
	invalidHandler: function(form, validator) {
		var errors = validator.numberOfInvalids();
		if (errors) {
			alert('Please enter a search term.');
		}
	}

	});	
	
	try {
   $('#WTRW p').truncate({max_length: 250});
	} catch(err) { }
	
	$(".stackList li:last-child, div.relatedContent ul:last").css("border","none");
	$(".stackList li:first-child, .ingredientSectionTitle:first").css("padding-top","0");
	$(".pageSection .stepSection").find(">:first-child").css("margin-top","20px");

	
	//Looking for siblings of the CIE paywall to expand the page content
	$(".activeCIOnonCIE").parent().parent().css("height", "1230px");
	
	// Use jQuery to fix the SBS layout by finding the 5th sibling 
	// and clearing it all the way to the left. 
	$("#rightCol > .pageSection > .detailColumn:first").next().next().next().next().attr("style","clear: left;");
});




