var overlay_list = new Array("blog", "print", "printInfo", "printInfoWithoutNutrition", "share", "submit", "nutrition");
var file_overlayList = {"blog": "../overlay/overlay_blog.html", "print": "none", "printInfo": "../overlay/overlay_print.html", "printInfoWithoutNutrition": "../overlay/overlay_printNoNutrition.html", "share": "../overlay/sharewithafriend.aspx", "submit": "../overlay/submitrecipe.aspx", "nutrition": "../overlay/nutrition.aspx"};
var form_overlayList = {"blog": "none", "print": "none", "printInfo": "none", "printInfoWithoutNutrition": "none", "share": "shareForm", "submit": "submitForm", "nutrition": "none"};
var messageList = {"blog": "none", "print": "none", "printInfo": "none", "printInfoWithoutNutrition": "none", "share": "Your message has been sent.", "submit": "Your recipe has been sent.", "nutrition": "none"};
var overlay_element_class = "div.overlayBox";
var overlay_wrapper_id = "overlayWrap";
var overlay_close_btn = "closeOverlay";
var count_friends = 2;
var print_list = new Array("letterPrint", "size46Print", "size35Print");
var recipe_card_list = {"letterPrint": "../overlay/recipe85x11.aspx", "size46Print": "../overlay/recipe4x6.aspx", "size35Print": "../overlay/recipe3x5.aspx"};
var lastOverlay = "";
var currentPage = location.href;

jQuery.noConflict();

jQuery(document).ready(function(){
  //searchTermDisplay();
	create_overlay_wrapper();
	for (i=0;i<=overlay_list.length;i++){
		jQuery("."+overlay_list[i]).click(function(){
			show_overlay(this);
			return false;
		});
	}
	/*jQuery(".popupLink").click(function(){
		window.open(this.href,'popupWindow','location=1,status=1,scrollbars=1,width=550,height=630');
		return false;
	});*/
});

function create_overlay_wrapper(){
	jQuery("body").append('<div id="'+overlay_wrapper_id+'"></div>');
}

function show_overlay(this_elem){

	var cur_elem = this_elem.className;
	lastOverlay = cur_elem;
	if (cur_elem.indexOf("offState") == -1 ){
		var overlay_filename = file_overlayList[cur_elem];
		if (overlay_filename != "none"){
		    if ( cur_elem == "nutrition" )
		        overlay_filename += location.href.substring(location.href.indexOf("?"));
		    else
		        overlay_filename += "?" + new Date().getTime();
		                
			var overlay_filename = overlay_filename + " " + overlay_element_class;	
			jQuery("#"+overlay_wrapper_id).load(overlay_filename, function(){
				jQuery("#"+overlay_wrapper_id).append('<iframe class="bleedThroughPrevent"></iframe>');
				// close button
				jQuery("#"+overlay_close_btn).click(function(){
					hide_overlay();
				});
				//form Validation
				var cur_form = form_overlayList[cur_elem];
				var cur_message = messageList[cur_elem];
				var privacy_policy_checkbox = document.getElementById("privacy_policy");
				
				if (cur_form != "none"){
					jQuery.validator.setDefaults({
						submitHandler: function() { 
							if ((privacy_policy_checkbox) && (check_privacy_value = jQuery("#privacy_policy:checked").length == 0)){ 
								return false;
							}else{
							    
							    if ( lastOverlay == "submit" )
							    {
							        // submit a recipe idea post
                                    jQuery.post("../overlay/submitrecipe.aspx", 
                                        {
                                            action : "submit",
                                            requestKey : jQuery("#requestkey").val(), 
                                            name: jQuery("#yourname").val(), 
                                            email: jQuery("#youremail").val(),
                                            suggestion: jQuery("#suggestion").val(),
                                            ideaType: jQuery("#ideaType").val(),
                                            flavorList: jQuery("#flavorList").val(),
                                            sendInfo : jQuery("#sendinfo:checked").length
                                        },
                                        function(result){
                                            
                                            // submit successfully
                                            if ( result == "OK" )
                                            {
								                jQuery("#"+cur_form).hide();
								                jQuery(".introBox").html("<p>"+cur_message+"</p>");
								            }
								            else if ( result == "ERROR" )
								            {
								                jQuery("#"+cur_form).hide();
								                jQuery(".introBox").html("<p>ERROR submitting, please try again later.</p>");
								            }
								            else
								            {
								                jQuery("#"+cur_form).hide();
								                jQuery(".introBox").html(result);
								            }
                                        });
                                }
                                else if ( lastOverlay == "share" )
                                {
                                   // jQuery("#share_message").append("\r\n\r\n"+currentPage);
                                    // share the recipe
                                    jQuery.post("../overlay/sharewithafriend.aspx", 
                                        {
                                            action : "share",
                                            requestKey : jQuery("#share_requestkey").val(), 
                                            yourname: jQuery("#share_yourname").val(), 
                                            youremail: jQuery("#share_youremail").val(),
                                            message: jQuery("#share_message").val(),
                                            friendname: jQuery("#share_friendname").val(),
                                            friendemail: jQuery("#share_friendemail").val(),
                                            sendcopy : jQuery("#share_sendcopy:checked").length
                                        },
                                        function(result){
                                            
                                            // submit successfully
                                            if ( result == "OK" )
                                            {
								                jQuery("#"+cur_form).hide();
								                jQuery(".introBox").html("<p>"+cur_message+"</p>");
								            }
								            else if ( result == "ERROR" )
								            {
								                jQuery("#"+cur_form).hide();
								                jQuery(".introBox").html("<p>ERROR sending, please try again later.</p>");
								            }
								            else
								            {
								                jQuery("#"+cur_form).hide();
								                jQuery(".introBox").html(result);
								            }								        
                                        });
                                }
                                    
							}
						}
					});
			
					jQuery("#"+cur_form).validate();
					
					jQuery("#"+cur_form).submit(function(){
						if (check_privacy_value = jQuery("#privacy_policy:checked").length == 0){ 
							//the privacy policy checkbox needs to be checked
							jQuery("#privacyError").show();
							return false;
						}
					});	
					  
					// Add more friends
					jQuery("#moreFriends").click(function(){					 
						add_more_friends();
					});
					// add friend's name and sender's name to preview area
					jQuery("#yourname").keyup(function(){ add_preview_text("sender") });
					jQuery("#youremail").focus(function(){ add_preview_text("sender") });
					jQuery("#friendname1").keyup(function(){ add_preview_text("recipient") });
					jQuery("#friendemail1").focus(function(){ add_preview_text("recipient") });
					
					// keyup event handler to preview message
					jQuery("#message").keyup(function(){
						var t_message = jQuery(this).val();
						jQuery("#sharePreview").text(t_message);
					});
				}
				
				
				
				
				
				//print functionality
				if (this_elem.className.indexOf("printInfo") != -1){
					setup_print_overlay();
					for(j=0;j<=print_list.length;j++){
						
						//selecting a card size click loads appropriate print
						jQuery("#"+print_list[j]).click(function(){
						    //deselect previous
						  for(k=0;k<=print_list.length;k++){
						        jQuery("#"+print_list[k]).removeClass("selected");
						    }						  
						  jQuery(this).addClass("selected");
						  					  
							var rcpcard_filename = recipe_card_list[this.id];
							var pageURL = window.location.search;
							
							if (pageURL.indexOf("?") != -1) {
                                var queryStrings = pageURL.substring(1);
                                var stringPairs = queryStrings.split("&");
                                
                                for (var i=0;i<stringPairs.length;i++) {
                                  var keyAndValue = stringPairs[i].split("=");
                                  if (keyAndValue[0] == "recipeId") {
                                    //alert('url with ID and nutritionals'+rcpcard_filename+''+pageURL+'&printN=1');
                                    if (jQuery("#nutrition:checked").length == 1) {
						                window.open(''+rcpcard_filename+'?'+keyAndValue[0]+'='+keyAndValue[1]+'&printN=1','recipeKitchen');
						            }
    				                else {
    				                  window.open(''+rcpcard_filename+'?'+keyAndValue[0]+'='+keyAndValue[1],'recipeKitchen');
    				                }
                    
                                  }
                                }
							}
						});
					}
				}
				
				//nutrition overlay
				if (this_elem.className.indexOf("nutrition") != -1){
					var source_hdr = "#recipeTitle";
					var target_hdr = "#nutritionTitle";
					add_sIFR_hdr(source_hdr, target_hdr);
				}
				
				//share overlay, pre populate message field
				if (this_elem.className.indexOf("share") != -1){
				    if(currentPage.indexOf("recipeId") != -1){
					    jQuery("#share_message").append("Check out this delicious recipe I found in the Dannon Kitchen.\r\n\r\n"+currentPage+"\r\n");
				    }else{
					    jQuery("#share_message").append("Check out this page I found in the Dannon Kitchen.\r\n\r\n"+currentPage+"\r\n");
				    }
				}
				
			}).fadeIn("slow");
		}else{
			// this case, it is for print functionality on non-recipe info pages
			window.print();
		}
	}else{
		return false;	
	}
}

function hide_overlay(){
	jQuery("#"+overlay_wrapper_id).fadeOut("slow");	
}

function add_more_friends(){
	var friend_name_field = "friendname" + count_friends;
	var friend_email_field = "friendemail" + count_friends;
	
	add_friends_ele = "<label for='"+ friend_name_field +"'>Friend "+ count_friends +"'s name:</label><input type='text' id='"+ friend_name_field +"' name='"+ friend_name_field +"' /><label for='"+ friend_email_field +"'>Friend "+ count_friends +"'s email:</label><input type='text' id='"+ friend_email_field +"' name='"+ friend_email_field +"' class='email' />";
	
	jQuery("#moreFields").append(add_friends_ele);
	count_friends++;
	return false
}

function add_preview_text(name_type){
	if (name_type == "sender"){
		var sender_name = jQuery("#yourname").val();
		jQuery("#senderPreview").html("Enjoy,<br />" + sender_name);
	}else{
		var recipient_name = jQuery("#friendname1").val();
		jQuery("#recipientPreview").html("Hi " + recipient_name + ",");
	}
}

function setup_print_overlay(){
	var recipe_title = jQuery("#recipeTitle").children("span.sIFR-alternate").text();
	var recipe_ingre = jQuery("#ingreList").html();
	var recipe_instuc = jQuery("#instrucList").html();
	var recipe_note = jQuery("#noteArea").html();
	jQuery("#printRecipeTitle").text(recipe_title);
	jQuery("#printRecipeIngre").html(recipe_ingre);
	jQuery("#printRecipeInst").html(recipe_instuc);
	jQuery("#printNoteArea").html(recipe_note);
}

function setup_recipe_card(){
	var recipe_title = jQuery("#recipeTitle").children("span.sIFR-alternate").text();
	var recipe_ingre = jQuery("#ingreList").html();
	var recipe_instuc = jQuery("#instrucList").html();
	var recipe_note = jQuery("#noteArea").html();
	var recipe_img = jQuery("#recipeImg").attr("src");
	var rcpcard_img = document.getElementById("rcpCardImg");
	jQuery("#rcpCardTitle").text(recipe_title);
	jQuery("#rcpCardTitle2").text(recipe_title);
	jQuery("#rcpCardIngre").html(recipe_ingre);
	jQuery("#rcpCardInstu").html(recipe_instuc);
	jQuery("#rcpCardNote").html(recipe_note);
	rcpcard_img.src = recipe_img;
	rcpcard_img.alt = recipe_title;
}

function add_printArea(){
	jQuery("body").append('<div id="printArea"></div>');
}

function remove_printArea(){
	jQuery("body div#printArea").remove();	
}

function add_rcpNutrition(){
	jQuery("#printArea").append('<div id="rcpNutrition"></div>');
	jQuery("#rcpNutrition").load('../overlay/nutrition.aspx .container');
	jQuery(".container").css('height','100%');
}

function add_sIFR_hdr(s_hdr, t_hdr){	
	var rcp_hdr = jQuery(s_hdr).html();
	jQuery(t_hdr).html(rcp_hdr);
}


/* Blog This scripts */
function GetThis(T, C, U, L)
{
var targetUrl = 'http://www.myspace.com/Modules/PostTo/Pages/?' + 't=' + encodeURIComponent(T)
+ '&c=' + encodeURIComponent(C) + '&u=' + encodeURIComponent(U) + '&l=' + L;
window.open(targetUrl);
}


/* search term in search results title */
function searchTermDisplay() {
  var searchTermId, searchTermEndLoc;
  var searchTermLoc = location.href.indexOf('sw=');

  if (searchTermLoc >= 0) {
    searchTermId = location.href.substring(searchTermLoc + 3);
    searchTermEndLoc = searchTermId.indexOf('&');
      
    if (searchTermEndLoc >= 0) {
        searchTermId = searchTermId.substring(0, searchTermEndLoc);
    }
  }
  jQuery(".searchResultsPage h2.rcpTitle span").append(' for "'+searchTermId+'"');
}