/* Global Variables */

var loggedIn = false;
var zipcode = "Your 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");
    });

	var delayfade =
    {};
    /* toggle control */
    $('#signin_button,#closeLogin,#viewRecipeBox_button').click(function()
    {
        $('#login_controls').toggle();
    });

    /* Drop Shadow for text elements */
    setRoundedStyle();
    setRoundedStyleStatic();

	// -- Paused for Lasagne Coupon - will be removed long term
	/*
    $(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") == "17")){ 
				setTimeout("$.jPrintArea('#printContainer')", 4000);
			} else {
				$.jPrintArea('#printContainer');
			}
			
		}
    });
    

	
		if ($('#printCouponLink').length) 
    {
        $('#printCouponLink').facebox();
    }
	*/

    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();

});

function loadProductLocatorZipcode()
{
    if ($('#sideProdLocator').length) 
    {
        $('#sideProdLocator input[name=prodLocatorZip]').val(zipcode);
    }
}

function setRoundedStyleStatic()
{
    $("#product_locator").liquidCanvas(
            "[gradient{from:rgba(255,255,255,.3); to:rgba(0,0,0,0.0);}] => roundedRect{radius:6}");
	
    $("#sharebox").liquidCanvas(
            "[fill{color:rgba(0, 0, 0, 0.25)}] => roundedRect{radius:6}");	
}

function setRoundedStyle()
{

    initCorners();
    $('h1, h2').FontEffect(
    {
        shadow : true,
        shadowColor : "#000",
        shadowOffsetTop : 1,
        shadowOffsetLeft : 1,
        shadowBlur : 2
    });

    /* Drop Shadow/Rounded corners for elements */
    $(".ds_container").liquidCanvas(
            "[shadow{width:5;color:#4a070a;shift:5}] => roundedRect{radius:15}");

    $(".signin_container").liquidCanvas(
            "[gradient{from:rgba(205,112,1,1.0); to:rgba(244,192,21,1.0);}] => roundany{tl:0; bl:8; br:8; tr:8}");

    $(".recipeList").liquidCanvas(
            "[fill{color:rgba(0, 0, 0, 0.25)}] => roundedRect{radius:6}");
}

function initCorners()
{
    var setting1 =
    {
        tl :
        {
            radius : 10
        },
        tr :
        {
            radius : 10
        },
        bl :
        {
            radius : 10
        },
        br :
        {
            radius : 10
        },
        antiAlias : true
    }
    var setting2 =
    {
        tl :
        {
            radius : 6
        },
        tr :
        {
            radius : 6
        },
        bl :
        {
            radius : 6
        },
        br :
        {
            radius : 6
        },
        antiAlias : true
    }

    curvyCorners(setting1, ".rounded_image, .footer_container");
    curvyCorners(setting2, ".rounded, .search");
}

/* 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);
	
    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();
              });
        });

    }
    else
    {
        $('#loginErrorMsg').html(data.message);
        $('#loginError').show();
    }
}

function reloadLoginHeader()
{
    $.get(contextPath + "tiles/header/login-header-include", function(data)
    {
        $('#login_header_include').html(data);
        $('#closeLogin,#viewRecipeBox_button').click(function()
        {
            $('#login_controls').toggle();
        });
        setRoundedStyle();
        loadProductLocatorZipcode();
    });
}

function login()
{
    var options =
    {
        dataType : 'json',
        success : processPostLogin
    };

    $('#loginForm').ajaxSubmit(options);
}

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);
		
			setRoundedStyle();
    });
	
}

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="../users/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 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();		
}
