﻿var CSS_ERROR   = "error";
var CSS_SUCCESS = "success";

var modal_options = {
    overlay: 80,
    opacity: 70,
    persist: true,
    overlayCss: { backgroundColor: "#000" },
    focus: false,
    close: true, closeHTML: '<a class="modalCloseImg" title="Close"></a>', closeClass: 'simplemodal-close',
    onOpen: function(dialog) {
        dialog.overlay.fadeIn('fast', function() {
            dialog.data.hide();
            dialog.container.fadeIn('slow', function() {
                dialog.data.slideDown('slow');
            });
        });
    },
    onClose: function(dialog) {
        dialog.data.slideUp('slow', function() {
            dialog.container.hide('slow', function() {
                dialog.overlay.fadeOut('fast', function() {
                    $.modal.close();
                });
            });
        });
    }
}

//################################################################################################

// STARTING POINT
$(function() {

    $('a.form_popup').click(function(event) {
        event.preventDefault();
        var $popup = $("#popup_content");

        // Subscribing
        if ($(this).attr("title") == "subscription_form") {
            subscriptionForm($popup)
        }
        // Dear Santa
        else if ($(this).attr("title") == "dear_santa_form") {
            DearSantaPopup();
        }
        // Print Recipes
        else if ($(this).attr("title") == "recipe-view") {
            printRecipe($popup, $(this).attr("RecipeId"));
        }
        // Dear Santa Learn More
        else if ($(this).attr("title") == "learn_dear_santa") {
            learnDearSanta($popup);
        }
        // Share via email
        else if ($(this).attr("title") == "share_via_email") {
            shareEmail($popup);
        }

    });
});


function subscriptionForm($content) {
    // Get the necessary form in the jQuery Object
    $content.load('/Holidays/Subscribers/Email #email_subscription_popup', function() {
        $content.hide();
        // ---------------------------------------------------
        // Once the information is loaded, do the following...
        var $subscription_form = $("#subscription_form");
        var $email_form = $("#email_subscription_form");
        var $mobile_form = $("#mobile_subscription_form");

        $("#sub_form").unbind("submit").bind("submit", function(event) {
            // Take control of what happens after "submit" button is clicked
            event.preventDefault();

            // Functionality of the given forms
            if (addEmailSubscription($email_form) ||
                addMobileSubscription($mobile_form))
                showSubsciptionSuccess($content);
        });

        // ---------------------------------------------------

        // Everything is good and properly hooked up, show the popup
        $.modal($content, modal_options);
    });        // End of Popup load
}

function DearSantaPopup() {
    var $popup = $("#popup_content");
    var $parent = $(this).parent();
    if ($parent.attr("id") == "dealsFoot") {
        $parent = $parent.parent();
    }
    
    var $deals_name = $("h3", $parent).text();
    var $deals_price = $("p.price", $parent).text();
    
    if (!$deals_price) {
        $deals_price = $("#deal_price").text();
    }
    var $deals_desc = $("p.description", $parent).text();
    if (!$deals_desc) {
        $deals_desc = $("#dealofday_desc").text();
    }
    var $deals_img = $("img", $parent.parent()).attr("src");
    var $deals_uri = $("a", $parent.parent()).attr("href");
    var $ProductUrl = $("input.hidden_product", $(this).closest("div .product")).val();
    dearSantaForm($popup, $deals_name, $deals_desc, $deals_price, $deals_img, $ProductUrl)
}

// Removes the form and displays instructions for how to build the wishlist
function clear_santa_form($santa_form) {
    var $wishlist_help = "<h4>Wishlist</h4>" +
                                 "<p>You can send a list of products you want for the Holidays, but first you have to build that list.  Next to the products in the Gifts Galore section, there is an 'Add to Wishlist' button.  When you click that, you can view your wishlist and fill out a form to send to friends, family or perhaps even...your boss." +
                                 "</p>";

    if($santa_form != "")    
        $santa_form.html($wishlist_help);    
}


function dearSantaForm($content, $name, $desc, $price, $img, $uri) {
    // Get the necessary form in the jQuery Object
    $content.load('/Holidays/Gifts/DearSanta #dear_santa_popup', function() {
        $content.hide();
        // ---------------------------------------------------
        // Once the information is loaded, do the following...
        var $santa_form = $("#dear_santa_form");

        var $message = "<textarea name='Message' cols='40' rows='5'>A special someone has sent you their personal holiday wishlist:\n";
        var $wish_message = "";
        var $safe_product;
        if ($.cookie("SamsHolidayWishList")) {
            var sets = $.cookie("SamsHolidayWishList").split('&');
            var i;
            var $status = false;
            for (i = 0; i < sets.length; i++) {

                $type = sets[i].split("=|")[0];
                $test = $type.substr(0, 7);
                if ($test == "Product") {
                    $product = sets[i].split("=|")[1];

                    if ($product != "Removed" && $product != "") {
                        $safe_product = $product.replace(/[^a-zA-Z 0-9]+/g, '');
                        $status = true;

                    }
                }
                else {
                    $producturl = sets[i].split("=|")[1];

                    if ($producturl != "Removed" && $producturl != "") {
                        $safe_url = $producturl;
                        while ($safe_url.indexOf("@") > -1)
                            $safe_url = $safe_url.replace("@", "&");                        
                        $wish_message += "<a href='" + $safe_url + "'>" + $safe_product + "</a><br />";
                    }
                }
            }
            if ($status == false)
                clear_santa_form($santa_form);
        }
        else {
            clear_santa_form($santa_form);
        }
        $message += "</textarea>";

        $("#taMessage").html($message);
        $("#Gift_Wishlist").html($wish_message);
        $("#dear_santa_desc").html($desc);
        $("#dear_santa_img").attr("src", $img);
        $santa_form.find("h5").html($name);
        $santa_form.find(".price").html($price);

        // Clear button
        hookup_ClearWishlist($santa_form);

        // Submit button
        $("#test_form").unbind("submit").submit(function(event) {
            event.preventDefault();
            sendDearSanta($(this), $product, $price);
        });
        // ---------------------------------------------------

        // Everything is good and properly hooked up, show the popup
        $.modal($content, modal_options);
    });                 // End of Popup load

}

// Stored here, instead of wishlist.js, because there's a clear function
// in the popup itself (and popup.js appears on everypage, wishlist.js does not)
function hookup_ClearWishlist($santa_form) {

    $(".clear_wishlist").click(function(event) {
        event.preventDefault();
        ClearWishlist($santa_form);
    });
}

function ClearWishlist($santa_form) {
    // This controllor method removes the cookie itself
    $.ajax({
        url: "/holidays/gifts/clear_wishlist",
        type: "GET",
        dataType: "text"
    });
    $("div.btnClearList").hide();

    var $Options = $("div.wishlist_options");

    $wishlist_options = "<a href='#' class='addToWishlist'>Add to wishlist</a> ";

    // Graphics!
    $Options.fadeOut('fast', function() {
        $Options.html($wishlist_options);
        $Options.fadeIn('fast');

        // Hookup original options
        hookupAll_AddToWishList();
    });

    clear_santa_form($santa_form);
 
}

function printRecipe($content, $RecipeId) {
    $content.load('/holidays/food-and-entertainment/recipes/details/' + $RecipeId + ' #recipe_popup', function() {
        $content.hide();

        // Hide unnecessary divs in the content
        $("#voting.false", $content).hide();
        $("#not-voting.true", $content).hide();

        // Make sure the link uses the printing functionality of the printElement plugin
        $('a.print_popup').click(function(event) {
            event.preventDefault();
            $('#recipe_popup').printElement();
        });

        $('a.vote_up').click(function(event) {
            event.preventDefault();
            addVote($RecipeId, 1, 0);
        });

        $('a.vote_down').click(function(event) {
            event.preventDefault();
            addVote($RecipeId, 0, 1);
        });

        // Everything is good and properly hooked up, show the popup
        $.modal($content, modal_options);
    });
}

function learnDearSanta($content) {
    // Get the necessary form in the jQuery Object\

    $content.load('/Holidays/Gifts/LearnDearSanta #learn_dear_santa_popup', function() {
        //$content.load('/Holidays/Gifts/DearSanta #dear_santa_popup', function() {
        $content.hide();

        // Everything is good and properly hooked up, show the popup
        $.modal($content, modal_options);
    });  // End of Popup load

}

function shareEmail($content) {
    // Get the necessary form in the jQuery Object\

    $content.load('/Holidays/Home/ShareEmail #share_email_popup', function() {
    //$content.load('/Holidays/Gifts/DearSanta #dear_santa_popup', function() {
        $content.hide();
        $("#test_form").unbind("submit").submit(function(event) {
            // Take control of what happens after "submit" button is clicked
            event.preventDefault();
            // Functionality of the given form
            sendShareWithaFriend($(this));
        });
        
        // Everything is good and properly hooked up, show the popup        
        $.modal($content, modal_options);
    });  // End of Popup load

}

function addVote($RecipeId, $Up, $Down) {
    // Create an object to send to the controller with the data from the form
    var vote_data = { Id: $RecipeId, VoteCountUp: $Up, VoteCountDown: $Down, AuthorEmail: "test", AuthorName: "test2" };
    
    // Start the ajax, allowing the controller to decide what happens next
    $.ajax({
        url: "/holidays/recipes/vote",
        type: "POST",
        data: vote_data,
        dataType: "text",
        success: function(response) {
            showAddVote();
        },
        error: function(response) {
            showAddVoteError(response);
        }

    });
}

function addMobileSubscription($emailForm) {
    // Hookup the fields of the form
    var phone = $.trim($("input:text[name='PhoneNumber']", $emailForm).val());
    
    
    // Create an object to send to the controller with the data from the form
    var phone_data = { PhoneNumber: phone };
    var $status = false;

    // Start the ajax, allowing the controller to decide what happens next
    $.ajax({
        url: "/holidays/subscribers/phone",
        type: "POST",
        data: phone_data,
        dataType: "text",
        async: false,
        success: function(response) {
            //showAddMobileSubscriptionSuccess(response);
            $status = true;
        },
        error: function(response) {
            showAddMobileSubscriptionError(response);
            $status = false;
        }

    });
    return $status;
}

function sendDearSanta($santaForm, $product, $price) {
    var sender = $.trim($("input:text[name='Sender']", $santaForm).val());
    var sender_email = $.trim($("input:text[name='Sender_Email']", $santaForm).val());
    var recipient = $.trim($("input:text[name='Recipient']", $santaForm).val());
    var recipient_email = $.trim($("input:text[name='Recipient_Email']", $santaForm).val());
    var subject = $.trim($("input:text[name='Subject']", $santaForm).val());
    var message = "<b>From " + sender + ":</b><br /><br />" + $.trim($("textarea").val()) + "<br />" + $("#Gift_Wishlist").html() ;
    message.replace("\n", "<br>");    
    
    // Create an object to send to the controller with the data from the form
    var dearsanta_data = { Sender: sender,
                           Sender_Email: sender_email,
                           Recipient: recipient,
                           Recipient_Email: recipient_email,
                           Subject: subject,
                           Message: message };


    // Start the ajax, allowing the controller to decide what happens next
       var html = $.ajax({
           url: "/holidays/gifts/dearsanta",
           type: "POST",
           data: dearsanta_data,
           dataType: "text",
           success: function(response) {
               // Delete the cookie (i.e. The Wishlist)
               //$.cookie("SamsHolidayWishList", null);
               ClearWishlist($santaForm);
               showSendDearSantaSuccess(response);
               hideForm($santaForm);
           },
           error: function(response) {
               showSendDearSantaError(response);

           }

       });
}

function sendShareWithaFriend($santaForm) {
    var sender = $.trim($("input:text[name='Sender']", $santaForm).val());
    var sender_email = $.trim($("input:text[name='Sender_Email']", $santaForm).val());
    var recipient = $.trim($("input:text[name='Recipient']", $santaForm).val());
    var recipient_email = $.trim($("input:text[name='Recipient_Email']", $santaForm).val());
    var subject = $.trim($("input:text[name='Subject']", $santaForm).val());
    var message = $.trim($("textarea").val());

    // Create an object to send to the controller with the data from the form
    var shareemail_data = { Sender: sender,
        Sender_Email: sender_email,
        Recipient: recipient,
        Recipient_Email: recipient_email,
        Subject: subject,
        Message: message
    };

    // Start the ajax, allowing the controller to decide what happens next
    var html = $.ajax({
        url: "/holidays/home/shareemail",
        type: "POST",
        data: shareemail_data,
        dataType: "text",
        success: function(response) {
            showShareWithFriendSuccess(response);            
        },
        error: function(response) {
            showShareWithFriendError(response);
        }
    });
}

function addEmailSubscription($emailForm) {
    // Hookup the fields of the form
    var email = $.trim($("input:text[name='Email']", $emailForm).val());
    var accepts = $("input:checkbox:checked", $emailForm).val() ? true : false;
    
    // Create an object to send to the controller with the data from the form
    var email_data = { Email: email, DidOptIn: accepts };
    var $status = false;

    // Start the ajax, allowing the controller to decide what happens next
    var html = $.ajax({
        url: "/holidays/subscribers/email",
        type: "POST",
        data: email_data,
        dataType: "text",
        async: false,
        success: function(response) {
            $status = true;
        },
        error: function(response) {
            showAddEmailSubscriptionError(response);
            $status = false;
        }
    });   

    return $status;
}

function displayFeedback($target, feedback, cssClass) {
	if (cssClass) {
		$target.removeClass();
		$target.addClass(cssClass);
	}

	$target.hide();
	$target.html(feedback);
	$target.fadeIn('slow');
}

function showAddVote() {
    var feedback = "<p>Vote added!</p>";
    $("#voting").hide();
    displayFeedback($("#vote-feedback"), feedback, CSS_SUCCESS);

}

function showAddVoteError(res) {
    if (res.responseText.indexOf("HttpRequestValidationException") > 0) {
        displayFeedback($("#vote-feedback"), "Your input is invalid.<br/>Please avoid any markup and/or scripting.", CSS_ERROR);

    }
    else {
        try {
            var errors = JSON.parse(res.responseText);
            var feedback = errors ? buildErrorList(errors) : buildGenericError("An error has occurred.");
            displayFeedback($("#vote-feedback"), feedback, CSS_ERROR);
        }
        catch (ex) {
            displayFeedback($("#vote-feedback"), "An error occurred.<br/>Please avoid any markup and/or scripting.", CSS_ERROR);
        }
    }
}


function showAddMobileSubscriptionSuccess(res) {
    var feedback = "<p>Subscription successful</p>";
    displayFeedback($("#subscription-feedback2"), feedback, CSS_SUCCESS);

}

function showSendDearSantaSuccess(res) {
    var feedback = "<p>Wishlist successfully sent!</p>";
    displayFeedback($("#dearsanta-feedback"), feedback, CSS_SUCCESS);
}

function showShareWithFriendSuccess(res) {
    var feedback = "<div id='share_email_popup' class='popup'><a class='modalCloseImg simplemodal-close' href=''>Close</a>" + 
                    "<div class='popupTitle'><h2>Holidays Made Simple</h2>" +
                    "<p>Your e-mail has been sent successfully!</p>" +
                    "<p>Thank you for spreading the holiday cheer to everyone you know!</p>" +
                    "<p>Come back and visit us again for more holiday specials and useful tips on making your holidays simple, fun and memorable.</p></div><div class='clearfix'>&nbsp;</div>    </div>";
    displayFeedback($("#share_email_popup"), feedback, CSS_SUCCESS);    
}

function showAddEmailSubscriptionSuccess(res) {    
    var feedback = "<p>Subscription successful</p>";
    displayFeedback($("#subscription-feedback"), feedback, CSS_SUCCESS);

}

function showSubsciptionSuccess($content) {
    $content.load('/Holidays/Subscribers/Success #success_content', function() {
        
    });

}

function showShareWithFriendError(res) {
    if (res.responseText.indexOf("HttpRequestValidationException") > 0) {
        displayFeedback($("#dearsanta-feedback"), "Your input is invalid.<br/>Please avoid any markup and/or scripting.", CSS_ERROR);

    }
    else {
        try {
            var errors = JSON.parse(res.responseText);
            var feedback = errors ? buildErrorList(errors) : buildGenericError("An error has occurred.");
            displayFeedback($("#dearsanta-feedback"), feedback, CSS_ERROR);
        }
        catch (ex) {
            displayFeedback($("#dearsanta-feedback"), "An error occurred. Please avoid any markup and/or scripting.", CSS_ERROR);
        }
    }
}

function showSendDearSantaError(res) {
    if (res.responseText.indexOf("HttpRequestValidationException") > 0) {
        displayFeedback($("#dearsanta-feedback"), "Your input is invalid.<br/>Please avoid any markup and/or scripting.", CSS_ERROR);

    }
    else {
        try {
            var errors = JSON.parse(res.responseText);
            var feedback = errors ? buildErrorList(errors) : buildGenericError("An error has occurred.");
            displayFeedback($("#dearsanta-feedback"), feedback, CSS_ERROR);
        }
        catch (ex) {
            displayFeedback($("#dearsanta-feedback"), "An error occurred. Please avoid any markup and/or scripting.", CSS_ERROR);
        }
    }
}



function showAddEmailSubscriptionError(res) {
    if (res.responseText.indexOf("HttpRequestValidationException") > 0) {
        displayFeedback($("#subscription-feedback"), "Your input is invalid.<br/>Please avoid any markup and/or scripting.", CSS_ERROR);

    }
    else {
        try {
            var errors = JSON.parse(res.responseText);
            var feedback = errors ? buildErrorList(errors) : buildGenericError("An error has occurred.");
            displayFeedback($("#subscription-feedback"), feedback, CSS_ERROR);
        }
        catch (er) {
            displayFeedback($("#subscription-feedback"), "An error occurred. Please avoid any markup and/or scripting.", CSS_ERROR);
        }
    }
}

function showAddMobileSubscriptionError(res) {
    if (res.responseText.indexOf("HttpRequestValidationException") > 0) {
        displayFeedback($("#subscription-feedback2"), "Your input is invalid.<br/>Please avoid any markup and/or scripting.", CSS_ERROR);

    }
    else {
        try {
            var errors = JSON.parse(res.responseText);
            var feedback = errors ? buildErrorList(errors) : buildGenericError("An error has occurred.");
            displayFeedback($("#subscription-feedback2"), feedback, CSS_ERROR);
        }
        catch(er) {
            displayFeedback($("#subscription-feedback2"), "An error occurred. Please avoid any markup and/or scripting.", CSS_ERROR);
        }
    }
}



function buildErrorList(errors) {
    var list = "<ul class='errors'>";
    for(var i = 0; i < errors.length; i++) {
        list += "<li>" + errors[i] + "</li>";
    }
    list += "</ul>";
    
    return list;
}

function buildGenericError(msg) {
	return "Sorry! " + msg + "<br/>Please try again later.";
}


function hideForm($form) {
    $form.hide();
    $($form, "form").reset();  

}

$.fn.reset = function() {
     return this.each(function() {
         // Check against forms, and for the reset method
         if (this.tagName.toLowerCase() === "form" && this.reset) {
             this.reset();
         }
     });

 }
