$(document).ready(function(){

	jQuery.fn.exists = function(){
   	return jQuery(this).length > 0;
  };

	/* Javascript filters */
	var email_filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var zip_filter = /^([a-zA-Z0-9\s\-])+$/;
	var phone_filter = /^([0-9\s\-])+$/;
	var url_filter = /^(www.)+([a-zA-Z0-9\-])+\.+([a-zA-Z\.\/])+$/;
	var yyyy_filter = /^([0-9]{4})+$/;
	var mmdd_filter = /^([0-9]{2})+$/;

	/* add clearfix */
	$(".container, ul.tabs, .bullpen").addClass("clearfix");
	
	/* send external links elsewhere */
	$("a[rel=external], area").attr("target","_blank");
	
	/* add classes to each input type */
	$(":text, :password").addClass("text");
	$(":radio, :checkbox").addClass("radio");
	$(":submit").addClass("submit")/*.wrap('<div class="submit-box"></div>')*/;
	
	/* add focus where appropriate
	$(":text:first").focus().addClass("focused"); */
	
	/* slideshow */
	$('#slideshow').cycle({ fx: 'fade', speed: 500, timeout: 5000, delay: -2000, pause: 1, prev: '.prevslide', next: '.nextslide' });
	
	/* add class when focused */
	$(":text, :password, textarea").focus(function(){
		$(this).addClass("focused");
	});
	$(":text, :password, textarea").blur(function(){
		$(this).removeClass("focused");
	});
	
	/* masthead nav check */
	$("#masthead li li, .admin .sidebar li").each(function(){
		if ($(this).hasClass("not-linked")) {
		
		} else {
			/* chop hashes off */
			var url_split1 = location.href.split("#");
			var new_location = url_split1[0];
			var link = $("a", this).attr("href");
			var link_split = link.split("/");
			var url_split = new_location.split("/");
			if (url_split[url_split.length - 2]+'/'+url_split[url_split.length - 1] === link_split[1]+'/'+link_split[2]) {
				$(this).addClass("active");
			}
		}
	});
	
	/* if the user clicks the div, send them to the index page */
	$("#masthead li div").click(function(){
		var goto = $(this).siblings("ul").children("li").children("a").attr("href");
		window.location = goto;
	});
	
	/* nav hovering and sticking */
	$("ul#nav > li").hover(function(){
		if ($("ul", this).css("display") == 'none') {
			$("ul#nav div").css("background-position","left top");
			$("ul#nav ul").hide();
			$("ul#nav ul ul").show();
			$("div", this).css("background-position","left -29px");
			$("ul", this).fadeIn(200);
		}
	}, function(){
		$("div", this).css("background-position","left top");
		$("ul", this).hide();
		$(".attendees ul#nav li.att-nav div, .exhibitors ul#nav li.exh-nav div, .dot ul#nav li.dot-nav div, .wish ul#nav li.wish-nav div").css("background-position","left -29px");
		$(".attendees ul#nav li.att-nav ul, .exhibitors ul#nav li.exh-nav ul, .dot ul#nav li.dot-nav ul, .wish ul#nav li.wish-nav ul").show();
		//$(".entry li ul").hide();
	});
	
	/* get rid of the bar during DOT entries */
	//$(".entry li ul").hide();
	
	/* this handles any scrolling activity */
	if ($(".stop-me").exists()) {
		//$("body").append('<div id="scroller"></div>');
		offset = $(".stop-me").offset();
		$(window).scroll(function(){
			scroller = $(window).scrollTop();
			if (scroller >= offset.top - 20) {
				$(".stop-me").css("position","fixed").css("top","20px");
			} else {
				$(".stop-me").css("position","relative").css("top","0px");
			}
			$("#scroller").text(scroller);
		});
	}
	
	/* enter form */
	$("#updateform :submit").click(function() {
  		var email_filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  		var pin_filter = /^([0-9]{4})+$/;
   	if (!email_filter.test($("input[name='email']").val())) {
			alert("Please enter a valid email address.");
   		$("input[name='email']").focus();
   		return false;
   	} else if (!pin_filter.test($("input[name='pin']").val()) || $("input[name='pin']").val() == '') {
   		alert("Please enter a valid PIN.");
   		$("input[name='pin']").focus();
   		return false;
   	} else {
   		$("#updateform :submit").val("Logging in...").attr("disabled","disabled");
   		$("#updateform").submit();
   	}
   });
   
   /* Email trick on the create profile page */
   $("input[name='email']").blur(function() {
   	$(".username-box").empty();
   	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (!filter.test($(this).val())) {
			$(".username-box").append("Enter a valid e-mail address above.");
		} else {
			$(".username-box").append($(this).val());
		}
	});
	
	/* Label fix for radio buttons */
	$("span.label-fix").click(function(){
		var $previous = $(this).prev(":radio");
		/*if ($previous.attr("name") == 'volt_110' && $(this).text() == 'Yes') {
			alert("Be aware that 110-volt electricity results in an additional $75 charge.");
		}*/
		$previous.attr("checked","checked");
	});
	
	/* Make session track required IF they choose regular session */
	$("#session_form #type").change(function(){
		if ($(this).val() == 1) {
			$("#track").prev("label").addClass("required");
		} else {
			$("#track").prev("label").removeClass("required");
		}
	});
	
	/* Turn the last paragraph in each session to an <h4> */
	$("#seminar_page .session, #symposium_page .session").each(function(){
		$("p:last", this).replaceWith("<h3>"+$("p:last", this).text()+"</h3>");
	});

	/* Bullpen flyout */
	$(".bullpen img").hover(function(){
		name = $(this).attr("alt");
		$(this).parent().prepend('<span>'+name+'</span>');
	}, function(){
		$(".bullpen span").remove();
	});
	
	/* Submit button box */
	$("input[name='formsubmit']").wrap('<div class="submit-box"></div>');
	
	/* MS Word paste fix */
	function removeMSWordChars(str) {
    var myReplacements = new Array();
    var myCode, intReplacement;
    myReplacements[8216] = 39;
    myReplacements[8217] = 39;
    myReplacements[8220] = 34;
    myReplacements[8221] = 34;
    myReplacements[8212] = 45;
    for(c=0; c<str.length; c++) {
        var myCode = str.charCodeAt(c);
        if(myReplacements[myCode] != undefined) {
            intReplacement = myReplacements[myCode];
            str = str.substr(0,c) + String.fromCharCode(intReplacement) + str.substr(c+1);
        }
    }
    return str;
	}
	
	/* =============
   THE VALIDATOR
   ============= */
   
  jQuery.fn.validator = function(){
  
  	var changer = '';
  
  	$("input, select, textarea").change(function(){
			changer = 1;
		});
		$("a").click(function(){
			if (changer == 1) {
				var wait = confirm('Are you sure you want to leave this page? The changes you have made to this form will be not saved until the click blue Save button at the bottom of the page.\r\n\r\nClick Cancel to remain on this page.\r\nClick OK to leave this page and go where you had intended.');
				if (wait == true) {
					return true;
				} else {
					return false;
				}
			}
		});
		
   	return this.submit(function(){
   	
   		/* Initialize the error list */
   		var $error_list = '';
   	
   		$(".form-item",this).each(function(){
   		
   			/* get rid of error labels */
   			$("label", this).removeClass("error");
   		
   			/* grab the value of each form-item's field */
   			var $newval = ''; var $vartype = '';
   			if ($("textarea", this).exists()) {
   				$newval = jQuery.trim(removeMSWordChars($("textarea", this).val()));
   				$vartype = 'textarea';
   			} else if ($("select", this).exists()) {
   				if ($("select[name$='month']", this).exists()) {
   					var month = $("select[name$='month']", this).val();
   					var day = $("select[name$='day']", this).val();
   					var year = $("select[name$='year']", this).val();
   					$vartype = 'date';
 					} else {
   					$newval = jQuery.trim($("select", this).val());
   					$vartype = 'select';
   				}
   			} else if ($("input", this).exists()) {
   				$newval = jQuery.trim($("input", this).val());
   				if ($(":file", this).exists()) {
   					$vartype = 'file';
   				} else if ($("input[name='agree']", this).exists()) {
   					$newval = $("input[name='agree']", this).attr("checked");
   					$vartype = 'agreement';
   				} else if ($("input[name^='email']", this).exists()) {
   					$vartype = 'email';
   				} else if ($("input[name^='phone']", this).exists()) {
   					$vartype = 'phone';
   				} else if ($("input[name^='url']", this).exists() || $("input[name^='website']", this).exists()) {
   					$vartype = 'url';
   				} else if ($("input[name^='zip']", this).exists()) {
   					$vartype = 'zip';
   				} else if ($("input[name^='trigger']", this).exists()) {
   					$vartype = 'trigger';
   				} else if ($("input[name^='height']", this).exists() || $("input[name^='weight']", this).exists() || $("input[name^='width']", this).exists() || $("input[name^='depth']", this).exists()) {
   					$vartype = 'whole_numbers';
   				} else {
   					$vartype = 'text';
   				}
   			}
   			
   			if ($("label",this).hasClass("required")) {
   			
   				/* Snag the label and name the parent */
   				var $fieldlabel = jQuery.trim($("label", this).html());
   				var $instructions = jQuery.trim($("label small", this).text());
   				
   				switch ($vartype) {
   					case "file":
   						if ($newval == '') {
   							$error_list += '<li>Please choose a file for <strong>'+$fieldlabel+'</strong>.</li>';
								$("label", this).addClass("error");
   						}
   						break;
   					case "agreement":
   						if (!$newval) {
								$error_list += '<li>Please check the <strong>Agreement</strong>.</li>';
								$("label", this).addClass("error");
							}
   						break;
   					case "textarea":
							if ($newval == '') {
								$error_list += '<li><strong>'+$fieldlabel+'</strong> is blank.</li>';
								$("label", this).addClass("error");
							} else {
								if ($(".wordCount", this).length > 0) {
									var numWords = $(".wordCount", this).children("strong:first").text();
									var maxWords = $(".wordCount", this).children("strong:last").text();
									if (parseInt(numWords) > parseInt(maxWords)) {
										$error_list += '<li>You have exceeded the word limit for <strong>'+$fieldlabel+'</strong>.</li>';
										$("label", this).addClass("error");
									}
								}
							}
						break;
						case "text":
							if ($newval == '') {
								$error_list += '<li><strong>'+$fieldlabel+'</strong> is blank.</li>';
								$("label", this).addClass("error");
							}
						break;
						case "select":
							if ($newval == '') {
								$error_list += '<li><strong>'+$fieldlabel+'</strong> needs a selection.</li>';
								$("label", this).addClass("error");
							}
						break;
						case "date":
							if (month == '' || day == '' || year == '') {
								$error_list += '<li><strong>'+$fieldlabel+'</strong> needs a complete date.</li>';
								$("label", this).addClass("error");
							} else {
								if (month == "02" || month == "04" || month == "06" || month == "09" || month == "11") {
									if (month == "02") {
										if (year == "2008") {
											if (day > "29") {
												$error_list += '<li>The date you gave for <strong>'+$fieldlabel+'</strong> is not a real date.</li>';
												$("label", this).addClass("error");
											}
										} else {
											if (day > "28") {
												$error_list += '<li>The date you gave for <strong>'+$fieldlabel+'</strong> is not a real date.</li>';
												("label", this).addClass("error");
											}
										}
									} else {
										if (day > "30") {
											$error_list += '<li>The date you gave for <strong>'+$fieldlabel+'</strong> is not a real date.</li>';
											$("label", this).addClass("error");
										}
									}								
								}
							}
						break;
						case "email":
							if ($newval != '') {
								if (!email_filter.test($newval)) {
									$error_list += '<li>What you entered for <strong>'+$fieldlabel+'</strong> is not a valid email address.</li>';
									$("label", this).addClass("error");
								}
							} else {
								$error_list += '<li><strong>'+$fieldlabel+'</strong> is blank.</li>';
								$("label", this).addClass("error");
							}
						break;
						case "phone":
							if ($newval != '') {
								if (!phone_filter.test($newval)) {
									$error_list += '<li>What you entered for <strong>'+$fieldlabel+'</strong> is not a valid number.</li>';
									$("label", this).addClass("error");
								}
							} else {
								$error_list += '<li><strong>'+$fieldlabel+'</strong> is blank.</li>';
								$("label", this).addClass("error");
							}
						break;
						case "url":
							if ($newval != '') {
								if (!url_filter.test($newval)) {
									$error_list += '<li>What you entered for <strong>'+$fieldlabel+'</strong> is not a valid URL. Enter it like this &mdash; www.domain.com</li>';
									$("label", this).addClass("error");
								}
							} else {
								$error_list += '<li><strong>'+$fieldlabel+'</strong> is blank.</li>';
								$("label", this).addClass("error");
							}
						break;
						case "whole_numbers":
							if ($newval != '') {
								if (isNaN($newval) || $newval.indexOf(".") != -1) {
									$error_list += '<li><strong>'+$fieldlabel+'</strong> needs to be a whole number.</li>';
									$("label", this).addClass("error");
								}
							} else {
								$error_list += '<li><strong>'+$fieldlabel+'</strong> is blank.</li>';
								$("label", this).addClass("error");
							}
						break;
						case "zip":
							if ($newval != '') {
								if (!zip_filter.test($newval)) {
									$error_list += '<li>What you entered for <strong>'+$fieldlabel+'</strong> is not a valid zip/postal code.</li>';
									$("label", this).addClass("error");
								}
							} else {
								$error_list += '<li><strong>'+$fieldlabel+'</strong> is blank.</li>';
								$("label", this).addClass("error");
							}
						break;
						case "trigger":
							if ($newval == 0) {
								$error_list += '<li>The requirements for <strong>'+$fieldlabel+'</strong> have not been met.</li>';
								$("label", this).addClass("error");
							}
						break;
					}
   				
   				
   				
   			}
   			
   		});
   		
   		if ($error_list != '') {
				$("#errors").remove();
				$(this).before("<fieldset id=\"errors\"><legend class=\"error\">There are errors in your form.</legend><ul>" + $error_list + "</ul></fieldset>");
				$("#errors").slideDown("fast");
				window.location = "#errors";
				return false;
			} else {
				$(":submit", this).replaceWith('<h2 class="center">Submitting...</h2>');
				return true;
			}
   		
   	});	
  };
  
  $("#contact_form #memo").counter({
  	type: 'char',
  	goal: 500,
  	count: 'down'
  });
  
  $("#nomination_form #title, #nomination_form #client_company").counter({
  	type: 'char',
  	goal: 40,
  	count: 'down'
  });
  
  $("#nomination_form #misc_setup").counter({
  	type: 'char',
  	goal: 100,
  	count: 'down'
  });
  
  $("#contest_declaration #essay_1, #contest_declaration #essay_2, #contest_declaration #essay_3, #contest_declaration #essay_4").counter({
  	type: 'char',
  	goal: 1100,
  	count: 'down'
  });
  	
   
  $("#contact_form, #nomination_form, #contest_declaration, #upload_photo, #addedit_profile, #featured_form").validator();
	
});