/* JS for Progresso Soup */

var WEB_SITE_URL = 'http://www.progressobroth.com';
var SWEEP_POST_URL = "/Sweepstakes.ashx";
var EMAIL_POST_URL = "/TAF/Default.aspx";
var SWEEP_EMAIL_POST_URL = "/TAF/Default.aspx"; 
var RATINGS_API_URL = "/Api/Api.ashx";
var RULES_URL = "http://www.progressobroth.com/rules.aspx";

var expDate = new Date("December 31, 2010");

var homePageName = "Default.aspx"   // change for live site
var curRecipe = 1;
var curShortRecipe = 0;
var randomRecipe = 0;
var slideRecipe = 0;

var curRatings = [0,0,0,0,0,0,0,0,0,0,0,0,0] ;  // testing data
var rateCounts = [0,0,0,0,0,0,0,0,0,0,0,0,0] ;   // testing data
var recipesWithVideos = [1,2,3,11,12,13];
var userRecipesRated = [false,false,false,false,false,false,false,false,false,false,false,false,false];   

var recipeShortDescriptions = [
	"Chiarello's Herb Roasted Turkey and Gravy Recipe",
	"Chiarello's Next Day Turkey Soup", 
	"Chiarello's Roasted Butternut Squash Soup",
	"Chiarello's Crispy Seafood Salad with Citrus Vinaigrette",
	"Chiarello's Cauliflower alla Parmigiana",
	"Mama Chiarello's Stuffed Eggplant",
	"Chiarello's Pumpkin Pastina",
	"Chiarello's Turkey Scallopini and Squash Ravioli with Cranberry Brown Butter",
	"Chiarello's Seared Lemon Pepper Tilapia with Creamy Pumpkin Seed Vinaigrette Salad topped with Pomegranate Seeds",
	"Chiarello's Pastina Risotto with Peas and Prosciutto"
	, "Prime Rib Eye Steaks with Savory Beef Gravy"
	, "Polenta Spinach Gratin with Panko"
	, "Turkey Thigh Osso Buco"
	];
var maxRecipes = recipeShortDescriptions.length;

function updateRatingsArrays(ratingObject) {
	for(i=0;i<ratingObject.length;i++)	{
		curRatings[ratingObject[i].id - 1] = ratingObject[i].rating;
		rateCounts[ratingObject[i].id - 1] = ratingObject[i].count;
	}
}

function getRatings()	{
	urlParams = "action=getStats";

	$.ajax({
	    type: "POST",
	    url: RATINGS_API_URL,
	    dataType: "html",
	    data: urlParams,
	    success: function(data) {
	        var response = eval(data);
	        // Set local arrays with values
	        updateRatingsArrays(response);
	    }
	});
}

function isRated()	{
	return userRecipesRated[curRecipe - 1];
}

function hasVideo()	{
	var hasVideoFlag = false;
	for(i=0;i<recipesWithVideos.length + 1;i++)	{
		if (recipesWithVideos[i] == curShortRecipe + 1)	{
			hasVideoFlag = true;
			return hasVideoFlag;
		} else {
			hasVideoFlag = false;
		}
	}
	return hasVideoFlag;
}	
function hasVideo2()	{
	var hasVideoFlag = false;
	for(i=0;i<recipesWithVideos.length + 1;i++)	{
		if (recipesWithVideos[i] == curRecipe)	{
			hasVideoFlag = true;
			return hasVideoFlag;
		} else {
			hasVideoFlag = false;
		}
	}
	return hasVideoFlag;
}	

function playVideo()	{

    // Google event tracking
    _gaq.push(['_trackEvent', 'Video', 'Click', 'Play Recipe Video']);

	if($("#recipe-details").is(":visible")) {
		$("#recipe-details").hide();
	}
//	var videos = [ "Turkey_426x286","Turkey_Soup_426x286","SquashSoup_426x286"];
	
//	var flashvars = {};
//	if (swfobject.getQueryParamValue("v")) {
//		flashvars.v = swfobject.getQueryParamValue("v");
//	}
//	flashvars.v = videos[curRecipe - 1];
//	var params = {
//		menu: "false",
//		wmode: "transparent",
//		allowFullScreen: "true"
//	};
//	var attributes = {
//		id: "swfContent",
//		quality: "best"
//};
     //  Title that is displayed at bottom left of jquery window.
     var sDes = recipeShortDescriptions[curRecipe - 1];
     switch (curRecipe) {
         case 1:
             if (sDes.length > 46)
             // make sure the title isn't too long
                 $("#video-footer-text").html(sDes.substr(0, 46) + "...");
             else
                 $("#video-footer-text").html(sDes);
             $("#recipe-video").show();
              break;
          case 2:
              if (sDes.length > 46)
              // make sure the title isn't too long
                  $("#video-footer-text1").html(sDes.substr(0, 46) + "...");
              else
                  $("#video-footer-text1").html(sDes);
              $("#soup-recipe-video").show();
              break;
          case 3:
              if (sDes.length > 46)
              // make sure the title isn't too long
                  $("#video-footer-text2").html(sDes.substr(0, 46) + "...");
              else
                  $("#video-footer-text2").html(sDes);
              $("#squash-recipe-video").show();
              break;
          case 11:
              if (sDes.length > 46)
              // make sure the title isn't too long
                  $("#video-footer-text11").html(sDes.substr(0, 46) + "...");
              else
                  $("#video-footer-text11").html(sDes);
              $("#primeRib-recipe-video").show();
              break;
          case 12:
              if (sDes.length > 46)
              // make sure the title isn't too long
                  $("#video-footer-text12").html(sDes.substr(0, 46) + "...");
              else
                  $("#video-footer-text12").html(sDes);
              $("#polentaSpinach-recipe-video").show();
              break;
          case 13:
              if (sDes.length > 46)
              // make sure the title isn't too long
                  $("#video-footer-text13").html(sDes.substr(0, 46) + "...");
              else
                  $("#video-footer-text13").html(sDes);
              $("#turkeyThigh-recipe-video").show();
              break;
          default:
              break;
      };
//alert('JS file');
//	$("#recipe-video").append('<div id="swfContent"></div>');
//	swfobject.embedSWF("ProgressoVideoPlayer.swf", "swfContent", '426', '286', "9.0.0", "global/expressInstall.swf", flashvars, params, attributes);
	
//	var sDes = recipeShortDescriptions[curRecipe -1];
//	if(sDes.length > 46)
//		// make sure the title isn't too long
//		$("#video-footer-text").html(sDes.substr(0,46) + "...");
//	else
//		$("#video-footer-text").html(sDes);
	
//	$("#recipe-video").show();
}

function closeVideo()	{
//	$("#swfContent").remove();
    //	$("#recipe-video").hide();
    function closeVideo() {
        switch (curRecipe) {
            case 1:
                $("#recipe-video").hide();
                break;
            case 2:
                $("#soup-recipe-video").hide();
                break;
            case 3:
                $("#squash-recipe-video").hide();
                break;
            case 11:
                $("#primeRib-recipe-video").hide();
                break;
            case 12:
                $("#polentaSpinach-recipe-video").hide();
                break;
            case 13:
                $("#turkeyThigh-recipe-video").hide();
                break;
            default:
                break;
        };
    }
}

function emailRecipe()	{
    //	if($("#recipe-video").is(":visible")) closeVideo();
    //    closeVideo();
    switch (curRecipe) {
        case 1:
            $("#recipe-video").hide();
            break;
        case 2:
            $("#soup-recipe-video").hide();
            break;
        case 3:
            $("#squash-recipe-video").hide();
            break;
        case 11:
            $("#primeRib-recipe-video").hide();
            break;
        case 12:
            $("#polentaSpinach-recipe-video").hide();
            break;
        case 13:
            $("#turkeyThigh-recipe-video").hide();
            break;
        default:
            break;
    }
	$("#recipe-details").hide();
	$("#email-thumb").attr("src","images/recipe" + curRecipe + "_detail.jpg");
	$("#email-recipe-title").html(recipeShortDescriptions[curRecipe -1]);
	$("#recipe-email-form").show();
	$("#email-form").show();
	$("input#send-name").val('');
	$("input#send-email").val('');
	$("input#friend-name").val('');
	$("input#friend-email").val('');
}

function sendRecipe()	{
//    alert('sendRecipe is called');
    // Google event tracking
    _gaq.push(['_trackEvent', 'Email', 'Click', 'Email Recipe']);
	var allValidFlag = true;
	var send_name = $('input#send-name').val();
	var send_email = $('input#send-email').val();
	var friend_name = $('input#friend-name').val();
	var friend_email = $('input#friend-email').val();
	var deepLink = "?load-recipe=" + curRecipe;
	var recipeTitle = recipeShortDescriptions[curRecipe - 1];
	
	// Check email address
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(send_email) == false) {
		$('input#send-email').val('');
		$("#send-email-label").css("color","red");
		allValidFlag = false;
	} else {
		$("#send-email-label").css("color","#6a6a6a");
	}

	if(reg.test(friend_email) == false) {
		$('input#friend-email').val('');
		$("#friend-email-label").css("color","red");
		allValidFlag = false;
	} else {
		$("#friend-email-label").css("color","#6a6a6a");
	}

	if(send_name == '')	{
		$('input#send-name').val('');
		$("#send-name-label").css("color","red");
		allValidFlag = false;
	} else {
		$("#send-name-label").css("color","#6a6a6a");
	}
	if(friend_name == '')	{
		$('input#friend-name').val('');
		$("#friend-name-label").css("color","red");
		allValidFlag = false;
	} else {
		$("#friend-name-label").css("color","#6a6a6a");
	}
	
	if (!allValidFlag)	{
		return;
	}
//	alert('Before dataParams');
	// set data to send via POST ajax
	dataParams = "sname=" + send_name + "&semail=" + send_email + "&rname=" + friend_name + "&remail=" + friend_email + "&rtype=" + curRecipe + "&mtype=r";
	
	$.ajax({
		type: "GET",
		url: EMAIL_POST_URL,
		dataType: "html",
		data: dataParams,
		success: function(returnValue) {
		    $("#recipe-email-form  h1").html("Thanks for sharing...");
		    $("#email-form").hide();
		    $("#recipe-email-form").append("<div id='getcoupon'><br/><br />And, don't forget to download the $1 off coupon to help you get started on this recipe!</div>");
		},
		error: function() {
			//alert("ERROR");
			$("#recipe-email-form  h1").html("Thanks for sharing...");
			$("#email-form").hide();
			$("#recipe-email-form").append("<div id='getcoupon'><br/><br />And, don't forget to download the $1 off coupon to help you get started on this recipe!</div>");
		}
	});
  return false;
}

function closeEmail() {
	$("#recipe-email-form").hide();
	$("#recipe-email-form h1").html("Email this recipe to a friend");
	$("#send-email-label").css("color","#6a6a6a");
	$("#friend-email-label").css("color","#6a6a6a");
	$("#send-name-label").css("color","#6a6a6a");
	$("#friend-name-label").css("color","#6a6a6a");
	
	$('input#send-email').val('');
	$('input#friend-email').val('');
	$('input#send-name').val('');
	$('input#friend-name').val('');

	$('#getcoupon').remove();
}

function emailSweepstakes()	{
	//if($("#recipe-video").is(":visible")) closeVideo();
	$('input#send-name2').val('');
	$('input#send-email2').val('');
	$('input#friend-name2').val('');
	$('input#friend-email2').val('');
	$("#sweepstakes3").hide();
	$("#email-sweepstakes-form").show();
}

function sendSweepstakesEmail()	{	
	var allValidFlag = true;
	var send_name = $('input#send-name2').val();
	var send_email = $('input#send-email2').val();
	var friend_name = $('input#friend-name2').val();
	var friend_email = $('input#friend-email2').val();
	
	// Check email address
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(send_email) == false) {
		$('input#send-email2').val('');
		$("#send-email-label2").css("color","red");
		allValidFlag = false;
	} else {
		$("#send-email-label2").css("color","#6a6a6a");
	}

	if(reg.test(friend_email) == false) {
		$('input#friend-email2').val('');
		$("#friend-email-label2").css("color","red");
		allValidFlag = false;
	} else {
		$("#friend-email-label2").css("color","#6a6a6a");
	}

	if(send_name == '')	{
		$('input#send-name2').val('');
		$("#send-name-label2").css("color","red");
		allValidFlag = false;
	} else {
		$("#send-name-label2").css("color","#6a6a6a");
	}
	if(friend_name == '')	{
		$('input#friend-name2').val('');
		$("#friend-name-label2").css("color","red");
		allValidFlag = false;
	} else {
		$("#friend-name-label2").css("color","#6a6a6a");
	}
	
	if (!allValidFlag)	{
		return;
	}
	
	// set data to send via POST ajax
    dataParams = "sname=" + send_name + "&semail=" + send_email + "&rname=" + friend_name + "&remail=" + friend_email + "&mtype=s";

    $.ajax({
        type: "GET",
        url: SWEEP_EMAIL_POST_URL,
        dataType: "html",
        data: dataParams,
        success: function (returnValue) {
            $("#email-sweepstakes-form").css("background", "url(images/sweeps_email_thanks_bg.gif) no-repeat");
            $("#sweep-email-fields").hide();
            $("#thankyouresponse").html("<br/><br/></div><br/><br/><br/></div><br/>");
        },
        error: function () {
            $("#email-sweepstakes-form").css("background", "url(images/sweeps_email_thanks_bg.gif) no-repeat");
            $("#sweep-email-fields").hide();
            $("#thankyouresponse").html("<br/><br/></div><br/><br/><br/></div><br/>");
        }
    });
  return false;
}

function closeSweepstakesEmail() {
	$("#email-sweepstakes-form").hide();
	$("#shader").fadeOut();
	//$("#recipe-email-form h1").html("Email this recipe to a friend");
	$("#send-email-label2").css("color","#6a6a6a");
	$("#friend-email-label2").css("color","#6a6a6a");
	$("#send-name-label2").css("color","#6a6a6a");
	$("#friend-name-label2").css("color","#6a6a6a");
	
	$('input#send-email2').val('');
	$('input#friend-email2').val('');
	$('input#send-name2').val('');
	$('input#friend-name2').val('');

	$('#getcoupon').remove();
}


function loadNextShortRecipe()	{
	if(curShortRecipe < maxRecipes - 1)	{
		curShortRecipe++;
	} else {
		curShortRecipe=0;
	}
	showShortRecipe(curShortRecipe);
	recipeImage = "url(images/recipe" + (curShortRecipe + 1) + "_main.jpg) no-repeat";
	$("#hero").css("background",recipeImage);
	if (hasVideo()) {
		$("#play-video-button").show()
	} else {
		$("#play-video-button").hide()
	}
}
function loadPrevShortRecipe()	{
	if(curShortRecipe == 0)	{
		curShortRecipe = maxRecipes - 1;
	} else {
		curShortRecipe--;		
	}
	showShortRecipe(curShortRecipe);
	recipeImage = "url(images/recipe" + (curShortRecipe + 1) + "_main.jpg) no-repeat";
	$("#hero").css("background",recipeImage);
	if (hasVideo()) {
		$("#play-video-button").show()
	} else {
		$("#play-video-button").hide()
	}
}
function showShortRecipe()	{
	deactivateRating();
	curRecipe = curShortRecipe + 1;
	$("#short-recipe-text").html(recipeShortDescriptions[curShortRecipe]);
	$("#counter").html( (curShortRecipe + 1) + '/' + maxRecipes + '&nbsp;&nbsp;<a href="#" onClick="showAll();return false;">View All</a>');
	resetStars("star-rating-c1");
	if (hasVideo()) {
		$("#play-video-button").show()
	} else {
		$("#play-video-button").hide()
	}
	if(!isRated()) {
		initRating();
		$(".rate-thanks").html("Rate It");
	} else {
		$(".rate-thanks").html("Thanks");
	}
	$("#numOfRatings_sm").html('(' + rateCounts[curShortRecipe] + ')');
}
	
function loadNextRecipe()	{
	$("#recipe-details").hide();
	if(curRecipe < maxRecipes)	{
		curRecipe++;
	} else {
		curRecipe=1;
	}
	showRecipe(curRecipe);
	$("#hero").css("background",recipeImage);
}

function loadPrevRecipe()	{
	$("#recipe-details").hide();
	if(curRecipe == 1)	{
		curRecipe = maxRecipes;
	} else {
		curRecipe--;		
	}
	showRecipe(curRecipe);
	$("#hero").css("background",recipeImage);
}

//function showRecipe()	{
function showRecipe()	{
    deactivateRating();
    view_recipe(); 
	recipeImage = "url(images/recipe" + curRecipe + "_main.jpg) no-repeat";
	$("#hero").css("background",recipeImage);
	$("#recipe-details").show();
	$("#recipe-details").load("recipes/recipe-" + curRecipe + ".html", '', initRecipeScroll);
	// Google event tracking - take out the word Charello's in recipe short name
	_gaq.push(['_trackEvent', 'View Recipe', 'Click', 'View ' + recipeShortDescriptions[curRecipe - 1].substring(12)]);
}

function closeDetails()	{
	curShortRecipe = curRecipe - 1;
	showShortRecipe();
	$('#recipe-details').hide();
}

initRecipeScroll = function() {
	$("div.scrollable").jScrollPane({showArrows:false, scrollbarWidth: 9});
	$("#counter2").html( curRecipe + '/' + maxRecipes);
	if ($.browser.msie && $.browser.version.substr(0,1)<7) {	
		$(function(){$(document).pngFix();});			
	}
	if (hasVideo2()) {
		$("#play-video-btn-details").show()
	} else {
		$("#play-video-btn-details").hide()
	}
	if(!isRated()) {
		initRating();
		$(".rate-thanks").html("Rate It");
	} else {
		$(".rate-thanks").html("Thanks");
	}
	resetStars("star-rating");
	$("#numOfRatings").html('(' + rateCounts[curRecipe - 1] + ')');
}

function showAll()	{
	$("#recipe-viewall").show();
}

//function openSweepstakes1() {
//    // Tracking Enter Sweepstakes
//    _gaq.push(['_trackEvent', 'Sweepstakes', 'Click', 'Enter Sweepstakes']);
//    sweep();
//	if($("#recipe-details").is(":visible")) closeDetails();
//	if($("#recipe-video").is(":visible")) closeVideo();
//	if($("#recipe-viewall").is(":visible")) $("#recipe-viewall").fadeOut("slow");
//	if($("#recipe-email-form").is(":visible")) closeEmail();
//	if (!($.browser.msie && $.browser.version.substr(0, 1) < 7)) {
//	    $("#shader").fadeTo(1000, .4);
//	}

	// show error message for under age
//	if ($.cookie("PB_AGE_CHECK") != null) {
//	    isCookieUnderAgeSet = $.cookie("PB_AGE_CHECK");
//	    isCookieUnderAgeSet = true;
//	}  else {
//	    isCookieUnderAgeSet = false;
//	}
//	if(isCookieUnderAgeSet)	{
//	    $('#enter-btn').hide();
//	    $('#sw-enter-button').hide(); 
//		$('#age-prompt').html('Sorry, you are not eligible for this contest.  <br/>For more information, please visit the <a href="' + RULES_URL + '" target="_blank">' + "official rules" + '</a>.')
//		$('#age-prompt').css({'color':'red','font-weight':'bold'});		
//	}

//	$("#sweepstakes1").show();
//}

function closeSweepstakes1() {
	$("#sweepstakes1").hide();
	$("#shader").fadeOut("slow");
}

function openSweepstakes2()	{
	$("#sweepstakes1").hide();
	//isCookieUnderAgeSet = $.cookie("PB_AGE_CHECK");
	if($.cookie("PB_AGE_CHECK") != null)  
		isCookieUnderAgeSet = $.cookie("PB_AGE_CHECK");
	else
		isCookieUnderAgeSet = false;

	if($("#age-select option:selected").val() == 0)	{
		// under age
		isCookieUnderAgeSet = true;
		// Set cookie
		$.cookie("PB_AGE_CHECK", true);
	}

	if(isCookieUnderAgeSet)	{
	    $("#error-message").html('Sorry, you are not eligible for this contest.  <br/>For more information, please visit the <a href="' + RULES_URL + '" target="_blank">' + "official rules" + '</a>.');
		$("#sweepstakes2 #error-message").css({'width':'460px','margin-bottom':'100px'});
		$(".sweep_table").hide();
	} else {
		$("#error-message").html("");
		$(".sweep_table").show();
	}
	
	$("#sweepstakes2").show();
}
function closeSweepstakes2() {
	$("#sweepstakes2").hide();
	$("#shader").fadeOut("slow");
	resetForm();
}

function openSweepstakes3() {    
    // Tracking Submission of  Sweepstakes Completed
    _gaq.push(['_trackEvent', 'Sweepstakes', 'Click', 'Completed Sweepstakes']);

    $("#sweepstakes2").hide();
	var index = Math.floor(Math.random()*10);
	ranRecipe = recipeShortDescriptions[index - 1 ];
	//randomRecipe = ranRecipe;
	$("#random-recipe").html(ranRecipe);
	$("#sweepstakes3").show();
	sweep_ty();
	$("#sweepstakes3 .randomLink").attr("onClick","gotoRecipe(" + index +");return false;");
}
function closeSweepstakes3() {
	$("#sweepstakes3").hide();
	$("#shader").fadeOut("slow");
}

function rateRecipe(rNum)	 {
	deactivateRating();   // can't vote again
	userRecipesRated[curRecipe - 1] = true;

	var dataParams = 'action=setRating&id=' + curRecipe + '&rating=' + rNum + '&format=query';
	$.ajax({
	    type: "POST",
	    url: RATINGS_API_URL,
	    dataType: "html",
	    data: dataParams,
	    success: function(data) {
	        var params = data.split('&');

	        var rating = params[1].split('=');
	        var count = params[2].split('=');
	        $(".rate-thanks").html("Thanks");
	        
	        // update count on screen
	        curRatings[curRecipe - 1] = rating[1];
	        rateCounts[curRecipe - 1] = count[1];

	        // alert('rating: ' + curRatings[curRecipe - 1] + '\ncount: ' + rateCounts[curRecipe - 1]);

	        // alert('current rating: ' + curRatings[curRecipe - 1]);
	        if ($("#numOfRatings").is(":visible")) {
	            $("#numOfRatings").html('(' + rateCounts[curRecipe - 1] + ')');
	        }
	        $("#numOfRatings_sm").html('(' + rateCounts[curShortRecipe] + ')');
	    }
	});
}
stimer = '';
function initRating()	{
	$(".star").live("mouseover", 
		function () {
			clearTimeout(stimer);
			stopSlideShow();   
			var parentID = $(this).parent().attr("id");
			rID = $(this).attr("id").substring(1,2);
			showRating(rID, parentID);
			$(this).css("cursor","pointer");
		});
		
	$(".star").live("mouseleave", function () {
		$(this).attr("src","images/star_dim.png");
		stimer = setTimeout("resetStars()", 3000);
	});
	
	$(".star").live("click", 
		function()	{
			var rNum = '';
			var parentID = $(this).parent().attr("id");
			rNum = $(this).attr("id").substring(1,2);
			rateRecipe(rNum);
		}
	)
}

function deactivateRating()	{
	$(".star").die("mouseover");
	$(".star").die("mouseleave");
	$(".star").die("click");
	$(".star").css("cursor","");
}

function showRating(sCount, pID)	{
	for(i=1;i<6;i++)	{
		if(pID == "star-rating") {
			sID = "#s" + i;
		} else {
			sID = "#s" + i + "-c1";
		}
		if(i < (parseInt(sCount) + 1))	{
			$(sID).attr("src","images/star.png");
		} else {
			$(sID).attr("src","images/star_dim.png");
		}
	}	
}

function resetStars(pID)	{
	var ave = parseInt(getAverageRating());
	for(i=1;i<6;i++)	{
		if(pID == "star-rating") {
			sID = "#s" + i;
		} else {
			sID = "#s" + i + "-c1";
		}
		if(i <  ave + 1)	{
			//if ($(sID).attr("src").indexOf("star_dim.") != -1) $(sID).attr("src","images/star.png");
			$(sID).attr("src","images/star.png");
		} else {
			//if ($(sID).attr("src").indexOf("star.") != -1) $(sID).attr("src","images/star_dim.png");
			$(sID).attr("src","images/star_dim.png");
		}
	}
}

function getAverageRating()	{
	// Shows actual (current vote) or average of 4
	if(curRatings[curRecipe - 1] > 0)	{
		return curRatings[curRecipe - 1];
	}
}

function gotoRecipe(index)	{
	closeSweepstakes3()
	curRecipe = index;
	showRecipe(index);
}

function closeViewAll() {
	$("#recipe-viewall").hide();
}

function thumbClick(index)	{
	//closeViewAll();
	curRecipe = index;
	showRecipe(index);
}

var slideShowTimer = '';
function startSlideShow()	{
	slideShowTimer = setInterval("loadNextShortRecipe()",8000);
}
function stopSlideShow()	{
	clearInterval(slideShowTimer);
}

function validateForm()	{
	var allValidFlag = true;
	var theForm = document.getElementById('contest_form');
	var firstName = $('input#first-name').val();
	var lastName = $('input#last-name').val();
	var phoneNumber = $('input#phone').val();
	var emailAddress = $('input#email-address').val();
	var city = $('input#city').val();
	var zip = $('input#zip').val();
	var stateObj = document.getElementById('state');
	var stateIndex = stateObj.selectedIndex;
	var state = stateObj.options[stateIndex].value;
	//var ageChecked = document.getElementById('age-verification').checked;
	// check first name
	if ( firstName.length < 1)	{
		$("#fNameLabel").css("color","red");
		allValidFlag = false;
	} else {
		$("#fNameLabel").css("color","#6a6a6a");
	}

	// check last name
	if ( lastName.length < 1)	{
		$("#lNameLabel").css("color","red");
		allValidFlag = false;
	} else {
		$("#lNameLabel").css("color","#6a6a6a");
	}
	// Check email address
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(emailAddress) == false) {
		emailAddress.value = '';
		$("#emailLabel").css("color","red");
		allValidFlag = false;
	} else {
		$("#emailLabel").css("color","#6a6a6a");
	}

	// check phone
	var reg = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/;
	if(reg.test(phoneNumber) == false)	{
		phoneNumber.value = '';
		$("#phoneLabel").css("color","red");
		allValidFlag = false;		
	} else {
		$("#phoneLabel").css("color","#6a6a6a");
	}

	// check city
	if ( city.length < 1)	{
		city.value = '';
		$("#cityLabel").css("color","red");
		allValidFlag = false;
	} else {
		$("#cityLabel").css("color","#6a6a6a");
	}

	// check zip code
    var zipCodePattern = /^\d{5}$|^\d{5}-\d{4}$/;
	if(zipCodePattern.test(zip) == false) {
		zip.value = '';
		$("#zipLabel").css("color","red");
		allValidFlag = false;
	} else {
		$("#zipLabel").css("color","#6a6a6a");
	}

	// check state
	if(state == '') {
		//stateObj.selectedIndex = 0;
		$("#stateLabel").css("color","red");
		allValidFlag = false;
	} else {
		$("#stateLabel").css("color","#6a6a6a");
	}

	// check age checkbox
	/* if ((ageChecked == false) && !allValidFlag)	{
		//$("#ageLabel").css("color","red");
		// Set cookie to prevent the user from entering the form
		$.cookie("PB_AGE_CHECK", true, {expires: expDate});
		resetForm();
		$("#error-message").html("You must be 21 years of age or older");
		$(".sweep_table").hide();		
		return;
		//allValidFlag = false;
	} else {
		$("#ageLabel").css("color","#6a6a6a");
	}
	*/

	if(allValidFlag)	{
		// submit form
		$("#error-message").html("")
		submitForm();
	} else {
		$("#error-message").html("Please fill in the required fields...")
	}
}

function resetForm()	{
	$('input#first-name').val('');
	$('input#last-name').val('');
	$('input#phone').val('');
	$('input#email-address').val('');
	$('input#city').val('');
	$('input#zip').val('');
	//$('input#age-verification').checked = false;
	document.getElementById('state').selectedIndex = 0;
	$("#fNameLabel").css("color","#6a6a6a");
	$("#lNameLabel").css("color","#6a6a6a");
	$("#emailLabel").css("color","#6a6a6a");
	$("#phoneLabel").css("color","#6a6a6a");
	$("#cityLabel").css("color","#6a6a6a");
	$("#zipLabel").css("color","#6a6a6a");
	$("#stateLabel").css("color","#6a6a6a");
	//$("#ageLabel").css("color","#6a6a6a");
	$("#error-message").html("")
}

function submitForm()	{
	var firstName = $('input#first-name').val();
	var lastName = $('input#last-name').val();
	var phone = $('input#phone').val();
	var emailAddress = $('input#email-address').val();
	var city = $('input#city').val();
	var zip = $('input#zip').val();
	var stateObj = document.getElementById('state');
	var stateIndex = stateObj.selectedIndex;
	var state = stateObj.options[stateIndex].value;
	//var ageChecked = document.getElementById('age-verification').checked;
	/* if (!ageChecked)	{
		// set cookie
		$.cookie("PB_AGE_CHECK", true, {expires: expDate});
		resetForm();
		$(".sweep_table").hide();
		$("#error-message").html("You must be 21 years of age or older");
		return;
	}
	*/
	var dataString = 'action=enterSweepstakes&fname='+ firstName + '&lname='+ lastName + '&email=' + emailAddress + '&phone=' + phone + '&city=' + city + '&zip=' + zip + '&state=' + state;
	$.ajax({
		type: "POST",
		url: SWEEP_POST_URL,
		dataType: "html",
		data: dataString,
		success: function(returnValue) {
			$("#sweepstakes2").hide();
			resetForm();
			openSweepstakes3();
		},
		error: function() {
				//alert("ERROR");
				$("#sweepstakes2").hide();
				resetForm();
				openSweepstakes3();
		}
	});
  return false;
}

function printRecipe()	{
    pWindow = window.open('print-recipe.aspx', 'printPopUp', 'width=800,scrollbars=1,status=0,toolbar=1,menubar=1');
    _gaq.push(['_trackEvent', 'Print', 'Click', 'Print Recipe']);
}
function getRecipeHTML()	{
	printHTML = $("#recipe-details div.scrollable").html();
	//alert(printHTML);
	return printHTML;
}

function shareRecipe(socialLocation)	{
	if(socialLocation == "fb")	{
        // Google event tracking
        _gaq.push(['_trackEvent', 'Facebook', 'Click', 'Share Recipe Facebook']);
		fb_Window = window.open('http://www.facebook.com/share.php?u=http://www.progressobroth.com/' + homePageName +'?load-recipe=' + curRecipe,'socialPopUp','scrollbars=1,status=1,toolbar=1,menubar=1');
	} else if (socialLocation == "tw") {
        // Google event tracking
        _gaq.push(['_trackEvent', 'Twitter', 'Click', 'Share Recipe Twitter']);
		rName = recipeShortDescriptions[curRecipe - 1];
		if (rName.length > 40) rName = recipeShortDescriptions[curRecipe - 1].substr(0,37) + "...";
		tw_Window = window.open('http://twitter.com/home?status=Try ' + rName + ' at http://www.progressobroth.com/' + homePageName +'?load-recipe=' + curRecipe,'socialPopUp','scrollbars=1,status=1,toolbar=1,menubar=1');
	}
}

function shareSweep(socialLocation)	{
	if(socialLocation == "fb")	{
		fb_Window = window.open('http://www.facebook.com/share.php?u=http://www.progressobroth.com/' + homePageName +'?load-recipe=' + curRecipe,'socialPopUp','scrollbars=1,status=1,toolbar=1,menubar=1');
	} else if (socialLocation == "tw") {
		rName = recipeShortDescriptions[curRecipe - 1];
		if (rName.length > 40) rName = recipeShortDescriptions[curRecipe - 1].substr(0,37) + "...";
		tw_Window = window.open('http://twitter.com/home?status=Progresso Broth wants to fly you to Napa to party with Chef Michael Chiarello! Visit','socialPopUp','scrollbars=1,status=1,toolbar=1,menubar=1');
	}
}

// Read URL parameters if any
// Used to redirect to disease card 
$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

// For deep linking
var loadRecipeID = $.getUrlVar('load-recipe');   // Getting URL var by its name if any to redirect to that disease page

// When page loaded, let's get the ratings and counts
getRatings();

