﻿//This file is a combination of commonly used functions on the website

function clearTextBoxesLabel(reference) {

    if ($(reference).val() != "") {
        $(reference).parents(".errorContainer").children("label").hide();
    }
    //Hide the password label if the user clicks on the password input
    $(reference).focus(
        function() {
            $(reference).parents(".errorContainer").children("label").hide();
        }
    );

    //If the User doesn't enter anything place anyting in the password field than show the password label again
    $(reference).blur(
        function() {
            if ($(reference).val() == "") {
                $(reference).parents(".errorContainer").children("label").show();
            }
        }
     );
}


//clearTextBoxes will allow you to set the default text for a input box so that the text will clear out when the user clicks on it and reappear if the user fails to enter any text
function clearTextBoxes(reference, textValue) {
    $(reference).focus(
                function() {
                    if ($(reference).val() == textValue) {
                        $(reference).val("");
                    }
                }
     );
    $(reference).blur(
                function() {
                    if ($(reference).val() == "") {
                        $(reference).val(textValue);
                    }
                }
    );
}

//The following function will be used to create overlays thoughout the site
//parameters: overlayID = used to determine the overlay to display, widthParam = width of overlay, buttonID = the identifier for button, overlayYPosition = optionaly only use if you want to specfically position the Y pos of the overlay
function createOverlay(overlayID, widthParam, buttonID, overlayYPosition) {
    
    $(overlayID).dialog({
        width: widthParam
    });

    if (overlayYPosition) {
        $(overlayID).dialog("option", "position", ['center', overlayYPosition]);
    }

    $(overlayID).hide();

    if (buttonID) {
        $(buttonID).click(function() {
            $(overlayID).show();
        });
    }

    $(overlayID + " .close").click(function() {
        $(overlayID).hide();
    });
}

//The following is the function for creating the dropdown functionality simply pass in the ID of the containing div
function createDropDown(dropdownID) {
    $(dropdownID).click(
        function() {
            $(dropdownID + " ul").show();
        }
    );

    $(dropdownID).mouseleave(
        function() {
            $(dropdownID + " ul").hide();
        }
    );

    $(dropdownID + " ul a").click(
            function() {
                var currentRecommendedFilterID = this.id;
                var currentRecommendedFilterText = ($("#" + currentRecommendedFilterID).text());
                $(dropdownID + " .currentlySelected").text(currentRecommendedFilterText);
            }
     );
}

// This creates an associative array from a culture-based resource string (in format 'text|value||text|value')
function buildLookupArray(valueString) {
    var assocArray = new Object();
    var valuesArray = valueString.split('||');
    
    for (var i=0; i < valuesArray.length; i++) {
        var keyValue = valuesArray[i].split('|');
        
        if (keyValue.length == 2) {
            assocArray[keyValue[1].toLowerCase()] = keyValue[0];
        }
    }
    
    return assocArray;
}

function buildSelectList(idName, valueString) {
    var values = valueString.split('||');
    
    // Remove any previous values
    $("#" + idName + ' >option').remove();
    
    for (var i=0; i < values.length; i++) {
        var keyValue = values[i].split('|');
        
        if (keyValue.length == 2) {
            $("#" + idName).append(
                $('<option></option>').val(keyValue[1].toLowerCase()).html(keyValue[0])
            );
        } else {
            $("#" + idName).append(
                $('<option></option>').val('').html(keyValue[0])
            );
        }
    } 
}

function displayForgotPassword() {
    var forgotPasswordEmail = "";
    $('html, body').animate({
    scrollTop: $("#HeaderMyBlackAndDecker").offset().top + 30
    }, 750);
    $("#forgotPasswordOverlayContainer").show();
    if ($("#txtEmail").val().length > 0) {
        forgotPasswordEmail = $("#txtEmail").val();
    } else if ($("#txtEmailFooter").val().length > 0) {
        forgotPasswordEmail = $("#txtEmailFooter").val();
    }
    $("#txtEmailForgot").val(forgotPasswordEmail);
    $("#hidden_forgot_email").val(forgotPasswordEmail);
}


/*Remove Comment Form*/
function clearComment() {
    $("#comment_form_display").html("");
    $("#comment_form_display").hide();
    $(".commentsBox .postCommentBtn").show();
}

/*Get a Querystring Parameter*/
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

/*Report Abuse*/
function reportAbuse(_contentTitle, _contentType, _contentID, handler) {
    $.ajax({
        type: "POST",
        url: "/WebServices/PluckContent.asmx/BuildReportAbuseForm",
        data: { ContentTitle: _contentTitle, ContentType: _contentType, ContentId: _contentID },
        dataType: "xml",
        success: function(xml) {
            var content = "";
            $(xml).find("Content").each(function() {
                content += $(this).find("Html").text();
            });
            $("#reportAbuseOverlay").html(content);
            $("#reportAbuseOverlay").show();
            //$("").css("top", "350px");
            $("#reportAbuseOverlay").dialog("option", "position", "center");
//            $('html, body').animate({
//                scrollTop: $("#reportAbuseOverlay").offset().top - 30
//            }, 750);
            validateOnFocus("#reportAbuseOverlay .formenv");
            $("#reportAbuseOverlay .btnSubmit").click(function() {
                if (validateOnSubmit("#reportAbuseOverlay") == 0) {
                    postReportAbuse("handlePluckReportAbuse");
                }
            });
        },
        error: function(response) {
            // TODO --> HIDE ENTIRE CONTROL
            alert("JSON Error Response:\r\n" + response.responseText);
        }
    });
}

function createWishlist(_catalogNumber, elementClicked) {
    //alert($(elementClicked).parent());
    // Example: createWishlist('VEC117BD');
    if (loggedIn) {
        _userId = $('.hidden_consumer_touchpointid').val();
        _emptyGuid = $('.hidden_empty_guid').val();

        //if (_userId != _emptyGuid) {
        $.ajax({
            url: "/webservices/ProductService.asmx/AddWishListProductByModelNumber",
            global: false,
            type: "POST",
            data: "modelNumber=" + _catalogNumber + "&consumerTouchpointId=" + _userId,
            dataType: "xml",
            success: function(xml) {
                var returnVal = $(xml).text();
                //alert(returnVal);
                if (typeof elementClicked == "string") {
                    $("#" + elementClicked).parent('.wishList').css('background', 'transparent');
                    $("#" + elementClicked).after("<strong>Item added to Wishlist</strong>");
                    $("#" + elementClicked).hide();
                } else {
                    $(elementClicked).after("<strong>Item added to Wishlist</strong>");
                    $(elementClicked).hide();
                }
//                var wishListSpan = $("#wishListSpan").html();
//                if (wishListSpan) {
//                    wishListSpan = wishListSpan.replace("(", "");
//                    wishListSpan = wishListSpan.replace(")", "");
//                    wishListSpan++;
//                    $("#wishListSpan").html("(" + wishListSpan + ")");
//                }
            } // end success function

        });
    } else {
        loginPrompt();
    }
}

function removeWishlist(_wishListId, _catalogNumber) {
    // Example: createWishlist('VEC117BD');
    _userId = $('.hidden_consumer_touchpointid').val();
    _emptyGuid = $('.hidden_empty_guid').val();

    //if (_userId != _emptyGuid) {
    $.ajax({
        url: "/webservices/ProductService.asmx/RemoveWishListProduct",
        global: false,
        type: "POST",
        data:  "consumerTouchpointId=" + _userId + "&wishListId=" + _wishListId + "&modelNumber=" + _catalogNumber,
        dataType: "xml",
        success: function(xml) {
            var returnVal = $(xml).text();
            //alert(returnVal);
            $("#ProductOverview .overviewRightSide .overviewRightSideBottom .buyWishList .addBox").after("<strong>Item added to Wishlist</strong>");
            $("#ProductOverview .overviewRightSide .overviewRightSideBottom .buyWishList .addBox").hide();

            var wishListSpan = $("#wishListSpan").html();
            if (wishListSpan) {
                wishListSpan = wishListSpan.replace("(", "");
                wishListSpan = wishListSpan.replace(")", "");
                wishListSpan--;
                $("#wishListSpan").html("(" + wishListSpan + ")");
            }
        } // end success function

    });
    //} else {
    //    alert('You need to be logged in for this feature');
    // }
}

function handlePluckReportAbuse(message) {
    alert(message);
    if (message == "ok") {
    } else {
    }
}

function loginPrompt() {
    setTimeout('$("#myBlackAndDeckerLoginForm").show();', 100);
    
    $('html, body').animate({
        scrollTop: $("#header").offset().top
    }, 750);
    
}

function recommendCommentPostHandler(message, commentKey) {
    if (message == "ok") {
        commentKey = commentKey.replace("CommentKey:", "");
        $("#recommendComment" + commentKey).before('<div class="reportedAbuse">You have recommended this post.</div>');
        $("#recommendComment" + commentKey).remove();
    } else {
    }
}

function recommendBlogPostHandler(message, blogPostKey) {
    if (message == "ok") {
        blogPostKey = blogPostKey.replace("Blog:", "");
        var fpostLocation = blogPostKey.indexOf("fPost:");
        blogPostKey = blogPostKey.substring(0, fpostLocation);
        $(".BlogPostRecommendationLink").before('<div class="reportedAbuse">You have recommended this post.</div>');
        $(".BlogPostRecommendationLink").remove();
    } else {
    }
}

function addLineBreaks(message) {
    message = message.replace(/(\r\n|[\r\n])/g, "<br />"); //Add Line Breaks
    message = message.replace(/(\r\n|\r|\n)/g, "<br />");
    return message;
}

function removeLineBreaks(message) {
    message = message.replace("<br />", "\r\n");
    return message;
}
