var Form = function() {
    return {
        values: function(form) {
            var data = {};
            form.find(':input').each(function() {
                data[$(this).attr('name')] = $(this).attr('value');
            });
            return data;
        }
    }
}();

var Patterns = {
	email: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
};

var Classes = {
	formerror: 'form-error'
};

var validate_comments = function() {
	var add_error_class = function(what) {
		what.focus().siblings('small, label').addClass('form-error');
	};
	var remove_error_class = function(what) {
		what.siblings('small, label').removeClass('form-error');
	};

	// Validate the comment forms
	(function() {
		$('#commentform').submit(function() {
			var author = $('#author');
			var email = $('#email');
			var comment = $('#comment');
			var ok = true;

			if (ok && author.val().length < 1) {
				ok = false;
				add_error_class(author);
			} else {
				remove_error_class(author);
			}

			if (ok && !email.val().match(Patterns.email)) {
				ok = false;
				add_error_class(email);
			} else {
				remove_error_class(email);
			}

			if (ok && comment.val().length < 1) {
				ok = false;
				var small = comment.prev('p:first').find('small');
				var text = small.text();

				var chunks = text.split('.');
				var notice = chunks.shift();
				var span = $('<span>' + notice + '. </span>');
				small.text(chunks.join('. '));
				small.prepend(span);
				comment.focus().prev('p:first').find('span').addClass('form-error');
			} else {
				comment.prev('p:first').find('small .form-error').removeClass('form-error');
			}

			return ok;
		});
	})();


	// Validate the whitepaper request form
	(function() {
		$('#whitepaper-form form').submit(function() {
			var ok = true;
			var inputs = $(this).find('input:text');
			var textarea = $(this).find('textarea');

			// The first, second, and fourth fields are required. The third needs to match an email address.
			// The textarea also needs to be considered
			var reqs = [inputs[0], inputs[1], inputs[2], inputs[3], textarea];
			var focused = false;
			$.each(reqs, function(i) {

				var t = $(this);
				var siblings = $(this).siblings('.reqtxt, .emailreqtxt, label');
				if (t.val().length < 1) {
					if (!focused) {
						t.focus();
						focused = true;
					}
					siblings.addClass(Classes.formerror);
					ok = false;
				} else {
					siblings.removeClass(Classes.formerror);
				}
			});
			try {
				
				var email = $(inputs[3]);
				var siblings = email.siblings('.reqtxt, .emailreqtxt, label');
				if (!email.val().match(Patterns.email)) {
					siblings.addClass(Classes.formerror);
					ok = false;
				} else {
					siblings.removeClass(Classes.formerror);
				}
			} catch(ex) {
				//	alert(ex);
			}
			return ok;
		});
	})();
};


var add_style = function() {
	// Add the button style that cforms uses for submit buttons
	$('input:submit').addClass('sendbutton');


	// Adjust the font-size and padding for cforms to match the wpcontactform
	(function() {
		$('#whitepaper-form *').css({width: 'auto'});
		$('#whitepaper-form input:text').css({
			fontSize: '1.5em',
			padding: '5px',
			width: '300px',
			margin:'0'
		});
	})();

    // Check the URL for a pattern that matches one of the top major links
    (function() {
        var flattenName = function(node) {
           return $.trim(node.text()).toLowerCase().replace(/\s+/g, '-');
        };
        var updateHeader = function(index) {
            $('#callout_bar a:eq(' + index + ')').find('span').addClass('current-section').stop().css({opacity: 1});
        };

        // Don't run this if there are no .current links in the sidebar
        var current = $('#sidebarnav a.current');
        if (current.length < 1) {
            return false;
        }
        var names = [];
        $('#callout_bar a').each(function() {
            names.push($(this).attr('name'));
        });

        var text = flattenName(current);
        var index = $.inArray(text, names);
        if (index > -1) {
            updateHeader(index);
        } else {
            current = current.parents('ul:first').prev('a:first');
            text = flattenName(current);
            index = $.inArray(text, names);
            if (index > -1) {
                updateHeader(index);
            }
        }

        // Now reset the "callout bar" to the current section when leaving the area
        $('#callout_bar').bind("mouseleave", function() {
            $(this).find(".current-section").stop().fadeTo(500, 1);
        });
    })();


};

var IE = function() {
    var fix_map = function() {
        $('.maptrigger').click(function() {
            var element = document.documentElement;
            $('#map').css({
                top: Number($('#map').position().top) + element.scrollTop
            });
        });
    };
    var fix_blog = function() {
        $('textarea#comment').removeClass('span-13').addClass('span-12');
    };
    if ($.browser.msie && $.browser.version < 7) {
        $.each([fix_map, fix_blog], function() {
            this();
        });
    }
};

var salesforce = function() {
    $('form.salesforce').each(function() {
        $(this).find('#return-url').val([window.location.href, "#thank-you"].join(''));
        if (window.location.hash.match(/thank-you/)) {
            $(this).hide();
            $('#thank-you').show();
        } else {
            $('#thank-you').hide();
        }
    });
};

$(document).ready(function() {
	var functions = [
        salesforce,
        IE
	];
	$.each(functions, function(i) {
		this();
	});
});
