/* Global Variables */

var loggedIn = false;
var zipcode = "Zip Code";

/* jquery controls */
$(window).load(function()
{

	$("#login_red").mouseover(function(){
    	$(this).removeClass().addClass("signInButtonRed_hover");
    }).mouseout(function(){
    	$(this).removeClass().addClass("signInButtonRed");		
    });
	
	$("#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");
  //});

	$('.hp_search #searchtoggle').click(function () {
	//		$('#top-search form').slideToggle(200, function(){
			$('#top-search form').slideToggle(200, function(){
			});
			$('#searchtoggle').toggleClass('up');
	});

    var delayfade =
    {};
    /* toggle control */
    $('#signin,#closeLogin').click(function()
    {
        $('#login_controls').toggle();
    });


    setRoundedStyle();

    setRecipeFavorites();
    


  
    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();
    
    $('.sendtoFriendItemLink').facebox();
    $('.rateItemLink').facebox();
    //$('.reviewItemLink').facebox();

});

function loadProductLocatorZipcode()
{
    if ($('#sideProdLocator').length) 
    {
        $('#sideProdLocator input[name=prodLocatorZip]').val(zipcode);
    }
}


function setRoundedStyle()
{

    $('.rounded a, .tabs a').FontEffect(
    {
        shadow : true,
        shadowColor : "#5c5c5b",
        shadowOffsetTop : 1,
        shadowOffsetLeft : 1,
        shadowBlur : 1
    });

    /* Drop Shadow/Rounded corners for elements */
    $(".signin_container").liquidCanvas("fill{color:#e5af38} => roundany{tl:0; bl:8; br:8; tr:8}");	
    $(".ds_container,.tabs").liquidCanvas("fill{color:#e5af38} => roundany{tl:10; bl:0; br:0; tr:10}");
    $(".rounded, .rounded_image").liquidCanvas("fill{color:#e5af38} => roundedRect{radius:10}");
    $(".searchred").liquidCanvas("fill{color:#d5363d} => roundedRect{radius:10}");
    $(".search").liquidCanvas("[gradient{from:rgba(198,198,198,1.0); to:rgba(255,255,255,1.0);} ] => roundedRect{radius:10}");
    $("#sharebox,.recipeList").liquidCanvas("[fill{color:#ffffff}] => roundedRect{radius:6}");

}




/* menu controls */
function MM_swapImgRestore()
{ // v3.0
    var i, x, a = document.MM_sr;
    for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++)
        x.src = x.oSrc;
}
function MM_preloadImages()
{ // v3.0
    var d = document;
    if (d.images)
    {
        if (!d.MM_p)
            d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
        for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0)
            {
                d.MM_p[j] = new Image;
                d.MM_p[j++].src = a[i];
            }
    }
}

function MM_findObj(n, d)
{ // v4.01
    var p, i, x;
    if (!d)
        d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length)
    {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all)
        x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++)
        x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++)
        x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById)
        x = d.getElementById(n);
    return x;
}

function MM_swapImage()
{ // v3.0
    var i, j = 0, x, a = MM_swapImage.arguments;
    document.MM_sr = new Array;
    for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObj(a[i])) != null)
        {
            document.MM_sr[j++] = x;
            if (!x.oSrc)
                x.oSrc = x.src;
            x.src = a[i + 2];
        }
}

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);
	var coupon = (path.indexOf("coupon") != -1);
	
    if (data.message == "Success")
    {
        $('#login_controls').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();
              });
        });
		
		if(coupon)
		{
			window.location.reload();
		}

    }
    else
    {
        $('#loginErrorMsg').html(data.message);
        $('#loginError').show();
    }
}

function reloadLoginHeader()
{ 
    $.get(contextPath + "tiles/header/login-header-include", function(data)
    {;
        $('#login_header_include').html(data);
        $('#signin').click(function()
        {
					$('#login_controls').toggle();
        });
        loadProductLocatorZipcode();
        setRoundedStyle();
        setRecipeFavorites();
    });
}

function login()
{
    var options =
    {
        dataType : 'json',
        success : processPostLogin
    };
    $('#loginForm').ajaxSubmit(options);    
//	$('<div id="loginAlert"/>').insertBefore("#login_include");
//	$("#loginAlert").text("Logging In....Please wait");
//	$("#login_include").hide();	
}

function reloadContentBottom(url, terms)
{
$('<div id="pagingAlert"/>').insertBefore("#pagination");
$("#pagination").hide();
$("#pagingAlert").text("Loading...").fadeIn(30);
$.get(url, function(data)
    {
        $('#contentBottom').html(data);
        setRoundedStyle();
    });

}

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('Please login to add an article or recipe to your Favorites. <br/> <br/>If you are a current member, please <a href="../users/login">login</a>. <br/> <br/>If you are not yet a member, please <a href="../promos/freepasta/registration">register</a> to enjoy coupons, other online promotions and store your favorite recipes and articles.');
    }
}

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 Favorites: 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)
	{
		$.get(contextPath + "recipes/reciperate/" + recipe, 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 setRecipeFavorites()
{

    if ($('.contentItem_recipes').length)
    {
        $('.contentItem_recipes').each(
                function()
                {
                    var recipeKey = $(this).attr("id");
                    if ($(this).find('#favoriteItemLink').length)
                    {
                        var link = $(this).find('#favoriteItemLink');
    
                        link.attr('onClick',
                                'addToFavorites(\'recipes\', \'' + recipeKey + '\'); return false;');
    
                        link.html("<image src='" + contextPath + "images/Plus.png' /> Add to recipe box");
                    }
                    
                    if ($(this).find('#sendtoFriendItemLink').length)
                    {
                        var link =$(this).find('#sendtoFriendItemLink');
                        link.attr("href", contextPath + "promote/send-to-friend/recipes/" + recipeKey);
                        link.facebox();
                    }
                    
                    if ($(this).find('#printItemLink').length)
                    {
                        var link =$(this).find('#printItemLink');
                        link.attr("href", contextPath + "recipes/" + recipeKey + "/print");
                        link.facebox();
                    }
                });
        
        $('.recipeList').each(
                function()
                {
                    var recipeKey = $(this).attr("id");
                    
                    if ($(this).find('#favoriteItemLink').html().length)
                    {
                        var link = $(this).find('#favoriteItemLink');
                        
                        link.attr('onClick', 
                                'addToFavorites(\'recipes\', \'' + recipeKey + '\'); return false;');
                        link.attr('title', 'Add to recipe box');
                        link.html("<image src='" + contextPath + "images/Plus.png' />");
                    }
                    
                    if ($(this).find('#sendtoFriendItemLink').length)
                    {
                        var link =$(this).find('#sendtoFriendItemLink');
                        link.attr("href", contextPath + "promote/send-to-friend/recipes/" + recipeKey);
                        link.facebox();
                    }
                    
                    if ($(this).find('#printItemLink').length)
                    {
                        var link =$(this).find('#printItemLink');
                        link.attr("href", contextPath + "recipes/" + recipeKey + "/print");
                        link.facebox();
                    }
                });
    }

    if (loggedIn)
    {
        $.getJSON(contextPath + "recipes/favorite", function(data)
        {
            $.each(data, function(i, item)
            {
                if ($('div[id=' + item.key + ']').length)
                {
                    
                    if ($('div[id=' + item.key + '] #favoriteItemLink').length)
                    {
                        var link = $('div[id=' + item.key + '] #favoriteItemLink');
                    
                        link.attr('onClick', 'removeFromFavorites(\'recipes\', \'' + item.key + '\'); return false;');
                        link.html("<image src='" + contextPath + "images/Minus.png' /> Remove from recipe box");
                    }
                    
                    if ($('div[id=' + item.key + '] #favoriteItemLink').length)
                    {
                        var link = $('div[id=' + item.key + '] #favoriteItemLink');
                            
                        link.attr('onClick', 'removeFromFavorites(\'recipes\', \'' + item.key + '\'); return false;');
                        link.attr('title', 'Remove from recipe box');
                        link.html("<image src='" + contextPath + "images/Minus.png' />");
                    }
                }
            });

        });
    }
}


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
    {
				$('#sideProdLocator').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();		
}