/* Global Variables */

var loggedIn = false;
var zipcode = "Enter ZIP Code";

/* jquery controls */
$(window).load(function()
{

	/*
	var tabContainers = $('div.tabs > div');
	tabContainers.hide().filter(':first').show();
	$('div.tabs ul.tabNavigation a').click(function () {
		tabContainers.hide();
		tabContainers.filter(this.hash).show();
		$('div.tabs ul.tabNavigation a').removeClass('selected');
		$(this).addClass('selected');
		return false;
	}).filter(':first').click();
*/

    //tab content
	$(".tab_content").hide();
	$(".tab_content:first").show();

	$(".tabnav a").click(function() {
		$(".tab_content").hide();
		var activeTab = $(this).attr("href");
		$(activeTab).show();
		return false;
	});

	
	$("#submitBtn").mouseover(function(){
    	$(this).removeClass().addClass("buttonSubmit_hover");
    }).mouseout(function(){
    	$(this).removeClass().addClass("buttonSubmit");		
    });	
	
	$(".findPasta2_button").mouseover(function(){
    	$(this).removeClass().addClass("findPasta2_button_hover");
    }).mouseout(function(){
    	$(this).removeClass().addClass("findPasta2_button");		
    });
	
	$("#advancedSearchBtn").click(function () {
      $("#advancedSearchOptions").slideToggle("fast");
    });

	var delayfade =
    {};
    /* toggle control */
    $('#login-btn,#closeBtn,#viewRecipeBox').click(function(event)
    {
    	event.stopPropagation();
        $('#login_controls,#login_controls_recipeBox').toggle();

    });


    /* Drop ShaDow for text elements */

    $(document).bind('reveal.facebox', function() 
    { 
		if ($('#printContainer').length)
		{

		// put in browser check, then if ie7 start pause - 5 seconds
		//	if ((navigator.appVersion.indexOf("MSIE 7") != 1)){
		//		setTimeout("$.jPrintArea('#printContainer')", 4000);
		//	} else {
		//	
		//		$.jPrintArea('#printContainer');
		//	}

		window.print();
		window.close();


		}
    });
    
    
    if ($('form[name=advRecipeForm]').length && $('form[name=recipeResultsForm]').length) 
    {
        updateAdvRecipeForm();
    }
    
    if ($('form[name=siteSearch]').length)
    {
        if ($('form[name=siteSearch] input[type:checkbox]:checked').length == 3)
        {
            $('form[name=siteSearch] input[name=all]').attr('checked', 'true');
        }
    }
    
    if ($('form[name=simpleProdSearch]').length && $('form[name=prodResultsForm]').length)
    {
        if ($('#searchResultsField').val() != '') 
        {
            $('form[name=simpleProdSearch] input[name=searchField]').val($('form[name=prodResultsForm] input[name=searchField]').val());
        }
        var shapes = $('form[name=prodResultsForm] input[name=shapes]').val().split(',');
    
        if (shapes.length > 0) 
        {
            for (var i = 0; i < shapes.length; ++i)
            {
                $('form[name=simpleProdSearch] input[value=' + shapes[i] + ']').attr('checked', 'true');
            }
        }
        
    }
    
    loadProductLocatorZipcode();

		//$('.printItemLink').facebox();
    $('.sendtoFriendItemLink').facebox();
    $('.rateItemLink').facebox();
    $('.reviewItemLink').facebox();
    //$('.changePassword').facebox();
    
    if ( window.usetinymce != undefined )
    {
	    $('.tinymce').tinymce({
	        // Location of TinyMCE script
	        script_url :  contextPath + 'js/tiny_mce/tiny_mce.js',
	        force_p_newlines : false,
	        force_br_newlines : true,
	        forced_root_block: false,
	        
	        // General options
	        theme : "advanced",
	        plugins : "table,contextmenu,advlist",
	
	        // Theme options
	        theme_advanced_buttons1 : "bold,italic,underline,charmap,|,bullist,numlist",
	        theme_advanced_buttons2 : "",
	        theme_advanced_buttons3 : "",
	        theme_advanced_buttons4 : "",
	        theme_advanced_toolbar_location : "top",
	        theme_advanced_toolbar_align : "left",
	        theme_advanced_statusbar_location : "bottom",
	        theme_advanced_resizing : true,
	        theme_advanced_path : false,
	
	        // Example content CSS (should be your site CSS)
	        content_css : contextPath + "css/heartland.css",
	        
	        setup : function(editor) {
	            editor.onKeyUp.add(function(editor){ limitTinyMCEChars(editor); });
	            editor.onChange.add(function(editor){ limitTinyMCEChars(editor); });
	        }
	
	    });
    }
    gapi.plusone.go(); 
});

function viewTab(tab){
    $(".tab_content").hide();
    var whichTab = "#tab" + tab;
    $(whichTab).fadeIn();
}


function limitTinyMCEChars(editor)
{
   var max = $("#" + editor.id).attr("maxTextLength");
   limitChars(editor.id,  max, editor.id + "_path_row");
}

function limitChars(id, max, countId)
{
   var text = $('#' + id).val();
   // Regex to account for line ending translation from "\n" to "\n\r" over http
   var len = text.replace(/\n/g, "\n\r").length;
   if ( len > max )
   {
       $('#' + countId).html("You have reached the max limit of " + max + " characters.  You  are now " + (len - max) + " characters above what will pass validation.");
       //alert(text);
       //$('#' + id).val(text.substr(0,max));
       return false;
   }
   else
   {
       $('#' + countId).html("You have " + (max - len ) + " characters remaining.");
       return true;
   }
}
   
function loadProductLocatorZipcode()
{
    if ($('#product-zip').length) 
    {
        $('#product-zip input[name=prodLocatorZip]').val(zipcode);
    }
}


function clickclear(thisfield, defaulttext)
{
    if (thisfield.value == defaulttext)
    {
        thisfield.value = "";
    }
}
function clickrecall(thisfield, defaulttext)
{
    if (thisfield.value == "")
    {
        thisfield.value = defaulttext;
    }
}

function processPostLogin(data)
{
	var path = location.href;
	var item = path.substring(path.lastIndexOf('/') + 1)
	var article = (path.indexOf("articles") != -1);
	var recipe = (path.indexOf("recipe") != -1);
	
    if (data.message == "Success")
    {
        $('#login_controls,#login_controls_recipeBox').hide();
        reloadLoginHeader();
        
        if(article)
        	reloadArticleRating(item);
		if(recipe)
        reloadRating(item);
		$.getJSON(contextPath + "users/login/content-update", function(data)
        {
            $.each(data, function(i,item){
                $('.' + item.type + "_" + item.key + "_removeFavorite").show();
                $('.' + item.type + "_" + item.key + "_addFavorite").hide();
              });
        });
	    window.location.reload();
    }
    else
    {
        $('#loginErrorMsg').html(data.message);
        $('#loginError').show();
    }
    

}

function reloadLoginHeader()
{
	var url = contextPath + "tiles/header/login-header-include?nocache=" + new Date().getTime();

    $.get(url, function(data)
    {
        $('#login-container').html(data);
        
        $('#login-btn,#viewRecipeBox').click(function(event)
        {
        	event.stopPropagation();
            $('#login_controls,#login_controls_recipeBox').toggle();
        });
        loadProductLocatorZipcode();

    });
}

function login()
{
    var options =
    {
        dataType : 'json',
        success : processPostLogin
    };

    $('#loginForm').ajaxSubmit(options);
}



function reloadContentBottom(url, idx)
{

$("#pagination").fadeOut();
$("#pagingControls").html("<ul><li>Loading...</li></ul>");

$.get(url, function(data)
    {
        $('#mainBody').html(data);
	    if ( idx != undefined )
	    {
		    $(".tab_content").hide();
		    $("#content_"+ idx).html($("#recipeTabContent").html());
		    $("#recipeTabIndex").html(idx);
		  
			$("#tab"+idx).show();
			
	    }
	    gapi.plusone.go(); 
    });

}

	
function getSearchPage(formName, url, page)
{
    $('#page').val(page);
    $.post(url, $('#' + formName).serialize(), function(data)
    {
        $('#contentBottom').html(data);
		
    });
	
}

function submitSearch(formName)
{

    var completed = false;

    if ($('form[name=' + formName + '] input[name=searchField]').val() != "Enter Keywords e.g. chicken"
            && $('form[name=' + formName + '] input[name=searchField]').val() != '')
    {
        completed = true;
    }

    $('form[name=' + formName + '] input[type=checkbox][class=required]:checked').each(function()
    {
        completed = true;
    });

    if (!completed)
    {
        $('#searchError').show();
        return false;
    }

    $('form[name=' + formName + ']').submit();

}

function addToFavorites(type, key)
{
    if (loggedIn)
    {
        $.getJSON(contextPath + type + "/" + key + "/favorite", function(data)
        {
            $.facebox(data.message); 
            $('.' + type + "_" + key + "_removeFavorite").show();
            $('.' + type + "_" + key + "_addFavorite").hide();
            reloadLoginHeader();
        });
    }
    else
    {
        $.facebox('<p>Please login to add a recipe to your recipe box.</p><p>If you are a current member, please <a href="../users/login">login</a>.</p><p>If you are not yet a member, please <a href="../users/registration">register</a> to enjoy coupons, other online promotions and store your favorite recipes.</p>');
    }
}

function removeFromFavorites(type, key)
{
    if (loggedIn)
    {
        $.getJSON(contextPath + type + "/" + key + "/not_favorite", function(data)
        {
            $.facebox(data.message);
            $('.' + type + "_" + key + "_removeFavorite").hide();
            $('.' + type + "_" + key + "_addFavorite").show();
            reloadLoginHeader();
        });
    }
    else
    {
        $.facebox('Remove from Recipe Box: Not logged on.  Become a member');
    }
}

function reloadArticleRating(article)
{
	if ($('#rateContainer').length)
	{
    $.get(contextPath + "articles/articlerate/" + article, function(data)
    {
        $('#rateContainer').html(data);
					});
	}
}

function reloadRating(recipe)
{
	if ($('#rateRecipeContainer').length)
	{
		var url = contextPath + "recipes/reciperate/" + recipe + "?nocache=" + new Date().getTime();

	    $.get(url, function(data) { $('#rateRecipeContainer').html(data); });
	}
}

function rateThisRecipe(name)
{
    $.getJSON(contextPath + "recipes/" + name + "/rating/" + jQuery('#rate:checked').val(),
            function(data)
            {
				 $.facebox(data.message);
                $("#recipes_" + name + "_rating").html('User rating is ' + jQuery('#rate:checked').val());
            });

}

function rateThisArticle(name)
{
    $.getJSON(contextPath + "articles/" + name + "/rating/" + jQuery('#rate:checked').val(),
            function(data)
            {
				$.facebox(data.message);
                $("#articles_" + name + "_rating").html('User rating is ' + jQuery('#rate:checked').val());
            });

}

function doSiteSearch(form)
{

    var ok = true;

    if (form == 'siteSearch')
    {
        if ($('form[name=siteSearch] input[type=checkbox]:not(input[name=all]):checked').length == 0)
        {
            ok = false;
        }
    }

    if (ok && $('#' + form + "  #searchField").val() != 'Enter Keywords e.g. chicken')
    {
        $('#' + form).submit();
    }
    else if (!ok)
    {
        $('#siteSearchError').show();
    }
}

function clickAllSiteSearch()
{
    if ($('input[name=all]:checked').val() == 'true')
    {
        $('form[name=siteSearch] input[type=checkbox]').each(function()
        {
            $(this).attr('checked', 'true');
        });

    }

}

function checkSiteSearchAll()
{
    if ($('form[name=siteSearch] input[type=checkbox]:not(input[name=all]):checked').length != 3)
    {
        $('input[name=all]').removeAttr('checked');
    }
}

function processSendtoFriend()
{
    var form = $('form[name=sendToFriend]');
    $.post(form.attr("action"), form.serialize(), function(data) {
        $.facebox(data);
    });
}

function searchProduct()
{
    if ( ! $('#prodLocatorZip').val().match(/^\d{5}$/)) {
        $('#prodLocatorError').show();
		return false;
    }
    else
    {
		$('#product-zip').submit(); 
    }
}

function updateAdvRecipeForm()
{
    if ($('form[name=recipeResultsForm] input[name=searchField]').val() != '') 
    {
        $('form[name=advRecipeForm] input[name=searchField]').val($('form[name=recipeResultsForm] input[name=searchField]').val());
    }
    var cats = $('form[name=recipeResultsForm] input[name=categories]').val().split(',');
    var cuisine = $('form[name=recipeResultsForm] input[name=cuisine]').val().split(',');
    var shapes = $('form[name=recipeResultsForm] input[name=shapes]').val().split(',');
    if (cats.length > 0) 
    {
        for (var i = 0; i < cats.length; ++i) 
        {
            $('form[name=advRecipeForm] input[value=' + cats[i] + ']').attr('checked', 'true');
        }
    }

    if (shapes.length > 0) 
    {
        for (var i = 0; i < shapes.length; ++i)
        {
            $('form[name=advRecipeForm] input[value=' + shapes[i] + ']').attr('checked', 'true');
        }
    }

    if (cuisine.length > 0) 
    {
        for (var i = 0; i < cuisine.length; ++i)
        {
            $('form[name=advRecipeForm] input[value=' + cuisine[i] + ']').attr('checked', 'true');
        }
    }
}

function submitRecipeReview() 
{
    var form = $('form[id=recipeReviewForm]');
    $.post(form.attr("action"), form.serialize(), function(data) {
        $.facebox(data);
    });
}

function pause(secs) 
{
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); } 
		while(curDate-date < (secs * 1000));
} 

function isImageLoaded(img) {

    if (!img.complete) 
    {
        return false;
    }
    
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) 
    {
        return false;
    }

    return true;
}

function printSomething(printWhat,printPath){
	if (printWhat == 'article'){
			window.open(printPath, "articlePrint", "menubar=no,width=650,height=600,toolbar=no,scrollbars=yes,status=yes,resizable=yes");
		}
	else if (printWhat == 'coupon'){
			window.open(printPath, "couponPrint", "menubar=no,width=400,height=200,toolbar=no,status=no");
		}
	else if (printWhat == 'recipe'){
			window.open(printPath, "recipePrint", "menubar=no,width=650,height=600,toolbar=no,scrollbars=yes,status=yes,resizable=yes");
		}
	
}


function printStuff(){
		window.print();
		window.close();		
}

//JavaScript Document
//From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
var emailRegEx = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;

function isValidEmail(sEmail) {
	
	  var reValidEmail = new RegExp(emailRegEx);
	  
	  if (reValidEmail.test(sEmail)) {
	    return true;
	  }
	  
	  return false;
	}

