﻿
function isValidEmail(email) {
    var regex = /([\w\d\-_]+)(\.[\w\d\-_]+)*@([\w\d\-_]+\.)([\w\d\-_]+\.)*([\w]{2,3})/;
    if (regex.test(email))
        return true;
    else
        return false;
}
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
    chars = chars || '\\s';
    return str.replace(new RegExp('^[" + chars + "]+', 'g'), '');
}
function rtrim(str, chars) {
    chars = chars || '\\s';
    return str.replace(new RegExp('[" + chars + "]+$', 'g'), '');
}
function setupDefaultTextReset(obj, message) {
    obj.click(function() {
        if (obj.val() == message)
            obj.val('');
    });
    obj.blur(function() {
        if (obj.val() == '')
            obj.val(message);
    });
}
function PostBackOnReturn(event, postbackMethod) {
    if (event) {
        if (event.keyCode == 13) {
            __doPostBack(postbackMethod, '');
        }
    }
}
String.prototype.startsWith = function(str) { return (this.match("^" + str) == str); }
String.prototype.trim = function() { return trim(this); }

$(document).ready(function () {

    $("a.reply").click(blogReplyClicked);

    $(".btnCommentFormSend").live('click', function (e) {
        e.preventDefault();
    });
    $(".btnCommentFormCancel").live('click', function (e) {
        e.preventDefault();
        $(this).parent().parent().parent().html('');
    });

    $('a.jsTwitter').live('click', function () {
        var url = 'http://twitter.com/share?url=' + encodeURIComponent(window.location);
        if ($(this).attr('href') != '#')
            url = 'http://twitter.com/share?url=' + encodeURIComponent($(this).attr('href'));
        window.open(url, 'twitter', 'width=600,height=400');

        if (_gaq != null) {
            _gaq.push(['_trackPageview', '/share/twitter']);
        }

        return false;
    });
    $('a.jsFaceBook').live('click', function () {
        var url = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(window.location);
        if ($(this).attr('href') != '#')
            url = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent($(this).attr('href'));
        window.open(url, 'facebook', 'width=600,height=400');

        if (_gaq != null) {
            _gaq.push(['_trackPageview', '/share/facebook']);
        }

        return false;
    });
    $('a.jsLinkedIn').live('click', function () {
        var url = 'http://www.linkedin.com/shareArticle?mini=true&url=' + encodeURIComponent(window.location);
        if ($(this).attr('href') != '#')
            url = 'http://www.linkedin.com/shareArticle?mini=true&url=' + encodeURIComponent($(this).attr('href'));
        window.open(url, 'linkedin', 'width=600,height=400');

        if (_gaq != null) {
            _gaq.push(['_trackPageview', '/share/linked-in']);
        }

        return false;
    });
    $('a.jsPlusOne').live('click', function () {
        var url = 'https://www.google.com/accounts/ServiceLogin?service=oz&continue=https://plusone.google.com/u/0/%252B1/profile/?type%3Dpo%26source%3Dp%26parent%3Dhttps://plusone.google.com%26proxy%3DI1_1312175996309%26hl%3Den_US%26gpcaz%3D12f468d6&hl=en-US#11420385%26ru%3D' + encodeURIComponent(window.location);
        if ($(this).attr('href') != '#')
            url = 'https://www.google.com/accounts/ServiceLogin?service=oz&continue=https://plusone.google.com/u/0/%252B1/profile/?type%3Dpo%26source%3Dp%26parent%3Dhttps://plusone.google.com%26proxy%3DI1_1312175996309%26hl%3Den_US%26gpcaz%3D12f468d6&hl=en-US#11420385%26ru%3D' + encodeURIComponent($(this).attr('href'));
        window.open(url, 'Google_plus_one', 'width=800,height=400');

        if (_gaq != null) {
            _gaq.push(['_trackPageview', '/share/google-plus']);
        }

        return false;
    });


    $('a.jsForward').live('click', function () {
        $('div.blogforward').fadeIn(100, function () {
            var offset = ($(".blogforward").offset().top);
            $('html, body').animate({ scrollTop: offset }, 'slow');
        });

        if (_gaq != null) {
            _gaq.push(['_trackPageview', '/share/email-forward']);
        }

        return false;
    });
    $('.blogforward .buttonCancel').click(function () {
        $('div.blogforward').slideUp(500);
        return false;
    });
    $('div.blogforward a.buttonForward').click(function () {
        blogForward();
        return false;
    });
    $('div.commentFormContainer input#tbBFFriendEmail').keyup(function (event) {
        if (event.keyCode == '13') {
            blogForward();
            return false;
        }
    });
    setupDefaultTextReset($('div.blogforward input#tbBFName'), 'Your Name');
    setupDefaultTextReset($('div.blogforward input#tbBFEmail'), 'Your Email');
    setupDefaultTextReset($('div.blogforward input#tbBFFriendName'), "Your Friend's Name");
    setupDefaultTextReset($('div.blogforward input#tbBFFriendEmail'), "Your Friend's Email");
    function blogForward() {
        $('div.blueFullWidth').hide();
        var name = $('div.blogforward input#tbBFName').val();
        var email = $('div.blogforward input#tbBFEmail').val();
        var friendname = $('div.blogforward input#tbBFFriendName').val();
        var friendemail = $('div.blogforward input#tbBFFriendEmail').val();
        $('div.blogforward p.error').html('');
        $('div.blogforward p.error').hide();
        $('div.blogforward div.success').hide();

        $('div.blogforward input#tbBFName').removeClass('error');
        $('div.blogforward input#tbBFEmail').removeClass('error');
        $('div.blogforward input#tbBFFriendName').removeClass('error');
        $('div.blogforward input#tbBFFriendEmail').removeClass('error');

        var errorMessage = '';
        if (trim(name) == '' ||
            trim(name) == 'Your Name') {
            $('div.blogforward input#tbBFName').addClass('error');
            errorMessage += 'Please enter your name<br />';
        }
        if (trim(email) == '' ||
            trim(email) == 'Your Email') {
            $('div.blogforward input#tbBFEmail').addClass('error');
            errorMessage += 'Please enter your email address<br />';
        }
        else if (!isValidEmail(email)) {
            $('div.blogforward input#tbBFEmail').addClass('error');
            errorMessage += 'Please enter a valid email address<br />';
        }
        if (trim(friendname) == '' ||
            trim(friendname) == "Your Friend's Name") {
            $('div.blogforward input#tbBFFriendName').addClass('error');
            errorMessage += "Please enter your friend's name<br />";
        }
        if (trim(friendemail) == '' ||
            trim(friendemail) == "Your Friend's Email") {
            $('div.blogforward input#tbBFFriendEmail').addClass('error');
            errorMessage += "Please enter your friend's email address<br />";
        }
        else if (!isValidEmail(friendemail)) {
            $('div.blogforward input#tbBFFriendEmail').addClass('error');
            errorMessage += "Please enter your friend's valid email address<br />";
        }
        if (errorMessage != '') {
            $('div.blogforward p.error').html(errorMessage);
            $('div.blogforward p.error').fadeIn(500);
            $('div.blueFullWidth').show();
        }
        else {
            //send
            $('div.blogforward p.blogforwardwait').show();
            $.post("/handlers/BlogForwardHandler2.ashx", { blogid: $('#hfBlogId').val(), name: name, email: email, friendname: friendname, friendemail: friendemail }, function (data) {
                $('div.blogforward p.blogforwardwait').hide();

                if (data.indexOf('Error:') != -1) {
                    $('div.blogforward p.error').fadeIn(500);
                    $('div.blogforward p.error').html('An error had occured. Please try again later.');
                }
                else if (data.indexOf('Success') != -1) {
                    $('div.blogforward input#tbBFFriendName').val('');
                    $('div.blogforward input#tbBFFriendEmail').val('');
                    $('div.blogforward div.success').show();
                }
                $('div.blueFullWidth').show();
            });
        }
    }

    $(".btnForwardFormCancel").live('click', function (e) {
        e.preventDefault();
        $("#blogForward").fadeOut(100);
    });

    $("#forwardSend").live('click', function (e) {
        e.preventDefault();
    });

    if ($("#forwardSend").length > 0) {
        var forwardValidator = new validator();
        forwardValidator.applyFormValidation({
            validationMessages: $("#forwardErrors"),
            fieldErrorClass: "errorState",
            submitButton: $("#forwardSend"),
            doPostback: function () {
                var blogId = $("#blogId").val();
                var name = $("#forwardFromName").val();
                var email = $("#forwardFromEmail").val();
                var nameTo = $("#forwardToName").val();
                var emailTo = $("#forwardToEmail").val();
                var container = $(this).parent().parent();
                $("#blogForward .successText").hide();

                $.post('/handlers/BlogForwardHandler.ashx', { blogid: blogId, name: name, nameTo: nameTo, email: email, emailTo: emailTo }, function (data) {
                    if (data == "Success") {
                        if (!$("#blogForward h2").hasClass("sent")) {
                            $("#blogForward h2").hide().html("FORWARD THIS ARTICLE TO ANOTHER FRIEND").addClass("sent").fadeIn("fast");
                            $("#blogForward h2").after($("<p />").addClass("successText").text("This article has been fowarded to " + emailTo + ".").fadeIn("fast"));
                        } else {
                            $("#blogForward .successText").text("This article has been fowarded to " + emailTo + ".").fadeIn("fast");
                        }

                        $("#forwardToName").val('');
                        $("#forwardToEmail").val('');
                        $("#forwardToName").focus();
                    } else {
                        alert("There was an error processing your request. Please try again later.");
                    }
                });
            },
            fields: [
            { type: "required", control: $("#forwardFromName"), msg: "Please enter your name<br />", dt: "Your name" },
            { type: "regex", control: $("#forwardFromEmail"), msg: "Please enter a valid email address<br />", dt: "Your email", expression: /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/ },
            { type: "required", control: $("#forwardToName"), msg: "Please enter your friend's name<br />", dt: "Your friend's name" },
            { type: "regex", control: $("#forwardToEmail"), msg: "Please enter a valid email address for your friend<br />", dt: "Your friend's email", expression: /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/ }
        ]
        });
    }
});


function blogReplyClicked(e) {
    var commentId = $(this).attr("rel");
    var commentContainer = $("#divBlogReplyComment-" + commentId);
    var replyFormHTML = $("#commentReplyFormTemplate").html().toString();
    replyFormHTML = replyFormHTML.replace(/\-commentId/gi, "-" + commentId);

    commentContainer.html(replyFormHTML);
    var formPos = commentContainer.offset().top - (($(window).height() / 3.33));
    $('html, body').animate({ scrollTop: formPos }, 'slow');

    $("#send-" + commentId).attr("rel", commentId);

    var cvalid = new validator();
    cvalid.applyFormValidation({
        validationMessage: "Oops you missed these required fields...",
        validationMessages: $("#validationMessage-" + commentId),
        fieldErrorClass: "errorState",
        submitButton: $("#send-" + commentId),
        doPostback: function (e, z) {

            var commentID = $(e).attr("rel");

            var name = $("#name-" + commentID).val();
            var email = $("#email-" + commentID).val();
            var comment = $("#commentText-" + commentID).val();

            var commentContainer = $(e).parent().parent().parent();
            commentContainer.html('<p class="success">Submitting... Please Wait</p>');

            //this is for the devs to sort out, if needed
            //return; //remove this statement when going into development
            jQuery.post('/handlers/BlogCommentReply.ashx', { commentid: commentID, name: name, email: email, comment: comment }, function (data) {
                if (data.indexOf('Success') >= 0) {
                    var newComment = $("<div></div>").addClass("comment").addClass("reply").addClass("commentFor-" + commentID);

                    if (data.indexOf("Success:posted") >= 0) {
                        newComment.append($("<p></p>").html(comment));
                    }
                    else {
                        newComment.append($("<p></p>").html(comment + "<br /><em>Your comment has been posted and is awaiting approval.</em>"));
                    }

                    newComment.append($("<p></p>").addClass("commenterName").html(name));
                    if ($(".commentFor-" + commentID).length == 0) {
                        var pointerImg = $("<img></img>").addClass("point").attr("src", "/resources/images/ui/bgBlogReply.png");
                        newComment.addClass("first").prepend(pointerImg);
                    }

                    commentContainer.before(newComment);
                    commentContainer.html('');
                }
                else {
                    commentContainer.html('<p class="error">An error had occurred. Please try again later.</p>');
                }
                z.preventDefault();
                return false;
            });
            z.preventDefault();
            return false;
        },
        fields: [
            { type: "required", control: $("#name-" + commentId), msg: "Please enter your name<br />", dt: "Your name" },
            { type: "regex", control: $("#email-" + commentId), msg: "Please enter a valid email address<br />", dt: "Your email (not published)", expression: /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/ },
            { type: "required", control: $("#commentText-" + commentId), msg: "Please enter your comment<br />", dt: "Your message" }
    ]
    });
    e.preventDefault();
    return false;
}

function track(page) {
    if (_gaq != null) {
        _gaq.push(['_trackPageview', page]);
    }
}
