function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

/*
		CSS Browser Selector v0.4.0 (Nov 02, 2010)
		Rafael Lima (http://rafael.adm.br)
		http://rafael.adm.br/css_browser_selector
		License: http://creativecommons.org/licenses/by/2.5/
		Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
function css_browser_selector(u){var ua=u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1},g='gecko',w='webkit',s='safari',o='opera',m='mobile',h=document.documentElement,b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3.6')?g+' ff3 ff3_6':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('blackberry')?m+' blackberry':is('android')?m+' android':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?m+' j2me':is('iphone')?m+' iphone':is('ipod')?m+' ipod':is('ipad')?m+' ipad':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win'+(is('windows nt 6.0')?' vista':''):is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);
$(document).ready(function () {

    $('a.newsletterOpen').mouseenter(function () {
        $('fieldset.form').slideDown(300, function () {
            $('a.newsletterOpen').addClass('active');
        });
    });

    $(".matchHeight").each(function (idx) {
        var maxHeight = 0;
        $(this).children().each(function (idx) {
            var ht = $(this).height();
            if (ht > maxHeight)
                maxHeight = ht;
        });

        $(this).children().height(maxHeight);
    });

    $('#close_ie6upgrade').mousedown(function () {
        $('#ie6').slideUp();
        return false;
    })

    if ($(".spot").length > 0) {
        $(".spot").tipTip({ maxWidth: "auto", edgeOffset: 10, attribute: "alt", defaultPosition: "top" });
    }

    $('.spotObj img').mouseover(function () {
        var el = $(this);
        setTimeout(function () {
            $('#tiptip_holder').removeClass('customRed');
            $('#tiptip_holder').addClass(el.attr('class').replace('spot ', ''));
        }, 100);
    });

    $("a.reply").click(blogReplyClicked);
    $(".btnCommentFormSend").live('click', function (e) {
        e.preventDefault();
    });
    $(".btnCommentFormCancel").live('click', function (e) {
        e.preventDefault();
        $(this).parent().parent().parent().html('');
    });

    $('a.tweet').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=500,height=300');
        return false;

        if ($(this).hasClass("track") && _gaq != null) {
            var hash = location.hash;
            if (hash != '') {
                hash = hash.replace('#', '');
            } else {
                hash = 'home';
            }
        }
    });

    $('a.fb-share').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=500,height=300');
        return false;
    });

    $('a.shareEmail').click(function () {
        $('div.blogForward').fadeIn(100, function () {
            var offset = ($(".blogForward").offset().top);
            $('html, body').animate({ scrollTop: offset }, 'slow');
        });
        $('div.blueFullWidth').show();
        return false;
    });

    if ($("#newsletterSend").length > 0) {

        $("#newsletterSend").click(function (e) {
            e.preventDefault();
        });

        var newsletterValidator = new validator();
        newsletterValidator.applyFormValidation({
            validationMessages: $("#newsletterError"),
            fieldErrorClass: "errorState",
            submitButton: $("#newsletterSend"),
            doPostback: function () {
                var homeNodeId = $("#homeNodeId").val();
                var name = $("#newsletterName").val();
                var email = $("#newsletterEmail").val();
                var container = $(this).parent();

                $.post('/handlers/NewsletterSignup.ashx', { nodeId: homeNodeId, name: name, email: email }, function (data) {
                    if (data != "Fail") {
                        $("#newsletterName").hide();
                        $("#newsletterEmail").hide();
                        $("#newsletterSend").hide();
                        $("#newsletterSuccess").html(data).fadeIn("fast");
                    } else {
                        alert("There was an error processing your request. Please try again later.");
                    }
                });
            },
            fields: [
            { type: "required", control: $("#newsletterName"), msg: "Please enter your name<br />", dt: "Enter your name" },
            { type: "regex", control: $("#newsletterEmail"), msg: "Please enter a valid email address<br />", dt: "Enter your email address", expression: /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/ },
        ]
        });
    }
});

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); }

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;
}
