/* ------------
	The main AJAX building blocks
------------ */

	var xmlhttp = false;
	
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {
			xmlhttp = false;
		}
	}
	
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		xmlhttp = new XMLHttpRequest();
	} else {
		/*alert("Please use one of the following web browsers:\n\n- Firefox 2+ (recommended)\n- Internet Explorer 6+\n- Safari 2+\n- Opera 9+");*/
	}
	
/* ------------
	Requests / Submissions
------------ */
	
	/* The general GET request */
	function getRequest(serverPage, objID) {
		var obj = document.getElementById(objID);
		xmlhttp.open("GET", serverPage, true);
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
				obj.innerHTML = xmlhttp.responseText;
			}
		}
		xmlhttp.send(null);
	}
	

/* ------------
	Subcategory fill-in
------------ */

function handleOnChange(company_id, form) {
	var thisForm = document.getElementById(form);
	var companyId = thisForm.company_id.value;
	var url = "./ajax_employee_list.php?company_id="+companyId;
	getRequest(url, 'employees');
}


$(document).ready(function() {

	/* Clearfix */
	$("#content, #footer, .splits").addClass("clearfix");
	
	/* Add classes to form items */
	$(":text").addClass("text");
	$(":radio").addClass("radio");
	
	/* Modal window */
	$("body.modal").append('<div id="overlay"></div><div id="modal"><div id="window"><h1>Welcome to StratConn!</h1><p>Getting set up for the upcoming StratConn event is simple. Use the Control Panel as navigation to complete each the following:</p><ol><li>Read and electronically <strong>sign the contract</strong>.</li><li><strong>Set attendees</strong> &mdash; assign who will be representing your company at StratConn and edit their information if necessary.</li><li><strong>Complete the company profile</strong> to provide the companies you are meeting with a description of your business. Completeness is key and helps us create your schedule.</li></ol><p>When we complete the meeting schedule for your company, you can view it and download it on this site as well. You will receive an e-mail when it&rsquo;s ready.</p><p><a href="./contact.php">Contact us</a> if you have any problems or questions. <a href="#">Get started!</a></p></div></div>');
	$("#modal a:last").click(function(){
		$("#overlay, #modal").hide();
		return false;
	});
	
	/* External links */
	$('a[rel="external"], area').click(function(){
		window.open($(this).attr('href'));
		return false;
	});
	
	/* Shorter textareas */
	$("textarea").addClass("shorter").focus(function() {
		if (this.value.length > 400) {
			if ($(this).hasClass("shorter")) { $(this).removeClass("shorter"); }
		} else {
			if (!$(this).hasClass("shorter")) { $(this).addClass("shorter"); }
		}
		$(this).keyup(function() {
			if (this.value.length > 400) {
				if ($(this).hasClass("shorter")) { $(this).removeClass("shorter"); }
			} else {
				if (!$(this).hasClass("shorter")) { $(this).addClass("shorter"); }
			}
		});
	});
	
	/* Disabled text box */
	$(":disabled").addClass("disabled");

	/* Login box submission */
	$("#login_form :submit").click(function(){
		if ($("input[name='email']").val() == '' || $("input[name='password']").val() == '') {
			alert('Please enter an e-mail address and a password to log in. Thank you.');
			return false;
		} else {
			return true;
		}
	});
	
	/* Table row striping */
	$("tbody tr:odd").addClass("table-bg");
	
	/* Strat event switcher */
	$(".admin h2 small a.slide").click(function(){
		$("#sidebar form").slideDown("fast");
		/*$(this).parent().parent().parent().removeClass("first");*/
		return false;
	});
   $("#strat_switch select").change(function(){
   	var event = $(this).val();
   	$(this).parent().attr("action","./admin.php?sc_event_id="+event).submit();
   });
   
   /* Schedule view switcher */
   $("#view_switch select").change(function(){
   	var oneoff = $(this).val();
   	var page = $("input[name='page']").val();
   	var view = $(":selected").parents("optgroup").attr("label");
   	var display = view.toLowerCase();
   	if (isNaN(oneoff)) {
 			$(this).parent().attr("action",page+"?view="+display).submit();
 		} else {
 			$(this).parent().attr("action",page+"?view="+display+"&oneoff="+oneoff).submit();
 		}
   });
   
   /* Compare profiles switcher */
   $("#compare-profiles select").change(function(){
   	var guest = $("select[name='guest_id']").val();
   	var host = $("select[name='host_id']").val();
   	if (guest != '' && host != '') {
   		$("#compare_form").attr("action","./compare_profile.php?host_id="+host+"&guest_id="+guest).submit();
   	}
   });
   
   /* Turn the schedule on */
   $("#live-schedule a").click(function(){
		var url = "./ajax_live_schedule.php";
		getRequest(url, 'live-schedule');
		alert("You just made the schedule for this StratConn event visible to all hosts and guests.");
		return false;
	});
	
	 /* Turn the profiles on */
   $("#live-profile a").click(function(){
		var url = "./ajax_live_profile.php";
		getRequest(url, 'live-profile');
		alert("You just made the profiles for this StratConn event visible to all hosts and guests.");
		return false;
	});
	
	/* Set up the batch e-mail editor */
	$("select[name='sc_event_id'], select[name='letter_id']").change(function(){
		var event = $("select[name='sc_event_id']").val();
		var letter = $("select[name='letter_id']").val();
		var e_text = $("select[name='sc_event_id'] :selected").text();
		var l_text = $("select[name='letter_id'] :selected").text();
		if (event != '' && letter != '') {
			$("#batch-email-editor").empty();
			$("blockquote").remove();
			if ($("h1").text() == 'Send Solo E-mails') {
				var url = "./ajax_oneoff_email_editor.php?sc_event_id="+event+"&letter_id="+letter;
				var start_over = '<small><a href="./oneoff_email.php">Start over</a></small>';
			} else {
				var url = "./ajax_batch_email_editor.php?sc_event_id="+event+"&letter_id="+letter;
				var start_over = '<small><a href="./batch_email.php">Start over</a></small>';
			}
			getRequest(url, 'batch-email-editor');
			$("select[name='sc_event_id']").replaceWith('<p>'+e_text+'</p>');
			$("select[name='letter_id']").replaceWith('<p>'+l_text+' '+start_over+'</p>');
		}
	});
   
   /* Attendee changer */
   $("table.attendees :radio").click(function(){
   	$("table.attendees tr").each(function(){
   		if ($(this).find(":checked").length < 1) {
   			$(this).removeClass("highlighted").find(".hidden").slideUp("fast");
   		} else {
   			if ($(this).find(":radio:checked").length > 1) {
   				$(this).find(":radio:checked").attr("checked",false);
   			}
   			$(this).addClass("highlighted").find(".hidden").slideDown("fast");
   		}
   	});
   	$(this).attr("checked","checked");
   });
   
   $("table.attendees tr.highlighted").find(".hidden").show();
   
   $("table.attendees :checkbox").click(function(){
   	$("table.attendees tr").each(function(){
   		if ($(this).find(":checked").length < 1) {
   			$(this).removeClass("highlighted").find(".hidden").slideUp("fast");
   		} else {
   			$(this).addClass("highlighted").find(".hidden").slideDown("fast");
   		}
   	});
   });
   
   /* Company highlight */
   $("#assign_companies_form :radio").click(function(){
   	$(this).parent().parent().addClass("highlighted");
   });
   
   /* Guests will include... no padding */
   $("p").each(function(){
   	if ($(this).html() == 'Guests will include:') {
   		$(this).addClass("no-pad").addClass("strong");
   	}
   });
   
   /* Use the YFT if called for */
   if ($("body").hasClass("yft")) {
   	$(".svar_box").effect("highlight", {}, 2000);
   	$("body").removeClass("yft");
	}
	
	/* Make it so that the room changes for every drop down on the set schedule page */
	$("#schedule_form select:odd").change(function(){
		var new_value = $(this).val();
		$("#schedule_form select:odd").val(new_value);
	});
	
	/* Lockdown = no form editing */
	if ($("body").hasClass("lockdown")) {
		$(":input").each(function(){
			$(this).attr("disabled","disabled");
		});
	} else {
		$(function() {
			$("#sortable1, #sortable2, #rankable1, #rankable2").sortable({
				placeholder: 'ui-state-highlight',
				connectWith: '.connectedSortable'
			}).disableSelection();
		});
	}
	
	/* Make sure they pick someone when sending a one-off e-mail */
	$("#oneoff_submit").click(function(){
		return false;
		alert(yes);
	});
	
/* ------------
	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})+$/;

/* ------------
	Curly quote remover
------------ */

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;
}

/* ------------
	jQuery Form Validation
------------ */
   
   
   /* Profile form (percentages) */
   $("#profile_form :submit").click(function(){

		/* Initialize variables */
   	var total = 0; var error_list = ''; var errors = '';
   	
   	if ($("input[name='address1']").val() == "") {
   		error_list = error_list + '<li><strong>Address 1</strong> is required.</li>';
   	}
   	if ($("input[name='city']").val() == "") {
   		error_list = error_list + '<li><strong>City</strong> is required.</li>';
   	}
   	if ($("select[name='state_id']").val() == "") {
   		error_list = error_list + '<li><strong>State / Province</strong> is required.</li>';
   	}
   	if ($("input[name='zip']").val() == "") {
   		error_list = error_list + '<li><strong>Zip / Postal Code</strong> is required.</li>';
   	}
   	if ($("select[name='country_id']").val() == "") {
   		error_list = error_list + '<li><strong>Country</strong> is required.</li>';
   	}
   	if ($("input[name='url']").val() == "") {
   		error_list = error_list + '<li><strong>URL</strong> is required.</li>';
   	} else {
			/*if (!url_filter.test($("input[name='url']").val())) {
   			error_list = error_list + '<li>The address you provided for <strong>Website</strong> is not valid. (ex. www.ebay.com)</li>';
   		}*/
   	}
   
   	$(".percent-check").each(function(){
   	
   		if ($(this).val() == "") {
   			$(this).val() = 0;
   		} else {
   			if (isNaN($(this).val())) {
   				error_list = '<li>One or more of your percentages is not numeric.</li>';
   			} else {
   				total = total + Math.round($(this).val());
   			}
   		}
   	
   	});
   	
   	if (total > 100 && error_list == '') {
   		error_list = '<li>The total value of your percentages is greater than 100. (currently '+total+')</li>';
   	}
   	
   	/* get rid of curly quotes on each textarea */
   	$("#profile_form textarea").each(function(){
   		$(this).val(removeMSWordChars(this.value));
   	});
   	
   	if (error_list != '') {
   		errors = '<ul>' + error_list + '</ul>';
   		$("#errors, blockquote.success").remove();
   		$("#profile_form").before("<blockquote id=\"errors\"><h3>There are errors in your form.</h3>" + errors + "</blockquote>");
   		$("#errors").slideDown("fast");
   		window.location = "#errors";
   		return false;
   	} else {
   		$(this).val("Submitting...");
			$(this).parent().submit();   
   	}
   
   });
   
   /* I agree (Contract form) */
   $("#contract_form :submit").click(function() {
   
   	if ($("input[name='agree']").attr("checked")) {
   		$(this).val("Submitting...");
			$(this).parent().submit();   		
   	} else {
   		errors = '<ul><li>Please check the box below to continue.</li></ul>';
   		$("#errors, blockquote.success").remove();
   		$("#contract_form").before("<blockquote id=\"errors\">" + errors + "</blockquote>");
   		$("#errors").slideDown("fast");
   		window.location = "#errors";
   		return false;
   	}
   
   });
   
   /* check curly quote script */
   
   $("#event_form textarea").blur(function(){
   	$(this).val(removeMSWordChars(this.value));
   	return false;
   });
   
   /* Add event */
   $("#event_form :submit").click(function() {
   
   	/* Initialize variables */
   	var error_list = ''; var errors = '';
   	
   	/* Error checking */
   	if ($("select[name='sc_event_type_id']").val() == "") {
   		error_list = error_list + '<li><strong>Event Type</strong> is required.</li>';
   	}
   	
   	if ($("select[name='sc_venue_id']").val() == "") {
   		error_list = error_list + '<li><strong>Venue</strong> is required.</li>';
   	}
   	
   	if ($("input[name='start_date']").val() != "") {
   		var date_value = $("input[name='start_date']").val();
   		var split_date = date_value.split("-");
   		var year1 = split_date[0];
   		var month1 = split_date[1];
   		var day1 = split_date[2];
   		if (!yyyy_filter.test(year1) || (!mmdd_filter.test(month1) || month1 > "12" || month1 == "00") || (!mmdd_filter.test(day1) || day1 > "31" || day1 == "00")) {
   			error_list = error_list + '<li>The date you provided for the <strong>Start Date</strong> is not a valid date.</li>';
   		} else {   			
				if (month1 == "02" || month1 == "04" || month1 == "06" || month1 == "09" || month1 == "11") {
					if (month1 == "02") {
						if (year1 % 4 == 0) {
							if (day1 > "29") {
								error_list = error_list + '<li>The date you provided for the <strong>Start Date</strong> is not a real date.</li>';
							}
						} else {
							if (day1 > "28") {
								error_list = error_list + '<li>The date you provided for the <strong>Start Date</strong> is not a real date.</li>';
							}
						}
					} else {
						if (day1 > "30") {
							error_list = error_list + '<li>The date you provided for the <strong>Start Date</strong> is not a real date.</li>';
						}
					}
				}
			}
   	} else {
   		error_list = error_list + '<li><strong>Start Date</strong> is required.</li>';
   	}
   	
   	if ($("input[name='stop_date']").val() != "") {
   		var date_value = $("input[name='stop_date']").val();
   		var split_date = date_value.split("-");
   		var year2 = split_date[0];
   		var month2 = split_date[1];
   		var day2 = split_date[2];
   		if (!yyyy_filter.test(year2) || (!mmdd_filter.test(month2) || month2 > "12" || month2 == "00") || (!mmdd_filter.test(day2) || day2 > "31" || day2 == "00")) {
   			error_list = error_list + '<li>The date you provided for the <strong>End Date</strong> is not a valid date.</li>';
   		} else {   			
				if (year1 <= year2 && ((month1 == month2 && day1 <= day2) || (month1 < month2))) {
					if (month2 == "02" || month2 == "04" || month2 == "06" || month2 == "09" || month2 == "11") {
						if (month2 == "02") {
							if (year2 % 4 == 0) {
								if (day2 > "29") {
									error_list = error_list + '<li>The date you provided for the <strong>End Date</strong> is not a real date.</li>';
								}
							} else {
								if (day2 > "28") {
									error_list = error_list + '<li>The date you provided for the <strong>End Date</strong> is not a real date.</li>';
								}
							}
						} else {
							if (day2 > "30") {
								error_list = error_list + '<li>The date you provided for the <strong>End Date</strong> is not a real date.</li>';
							}
						}
					}
				} else {
					if ($("input[name='start_date']").val() != "") {
						error_list = error_list + '<li>The date you provided for the <strong>End Date</strong> comes before the <strong>Start Date</strong>!</li>';
					}
				}
			}
   	} else {
   		error_list = error_list + '<li><strong>End Date</strong> is required.</li>';
   	}
   	
   	if ($("input[name='profile_cutoff']").val() != "") {
   		var date_value = $("input[name='profile_cutoff']").val();
   		var split_date = date_value.split("-");
   		var year3 = split_date[0];
   		var month3 = split_date[1];
   		var day3 = split_date[2];
   		if (!yyyy_filter.test(year3) || (!mmdd_filter.test(month3) || month3 > "12" || month3 == "00") || (!mmdd_filter.test(day3) || day3 > "31" || day3 == "00")) {
   			error_list = error_list + '<li>The date you provided for the <strong>Profile Cutoff Date</strong> is not a valid date.</li>';
   		} else {   			
				if (month3 == "02" || month3 == "04" || month3 == "06" || month3 == "09" || month3 == "11") {
					if (month3 == "02") {
						if (year3 % 4 == 0) {
							if (day3 > "29") {
								error_list = error_list + '<li>The date you provided for the <strong>Profile Cutoff Date</strong> is not a real date.</li>';
							}
						} else {
							if (day3 > "28") {
								error_list = error_list + '<li>The date you provided for the <strong>Profile Cutoff Date</strong> is not a real date.</li>';
							}
						}
					} else {
						if (day3 > "30") {
							error_list = error_list + '<li>The date you provided for the <strong>Profile Cutoff Date</strong> is not a real date.</li>';
						}
					}
				}
			}
   	} else {
   		error_list = error_list + '<li><strong>Profile Cutoff Date</strong> is required.</li>';
   	}
   	
   	if ($("textarea[name='description']").val() == "") {
   		error_list = error_list + '<li><strong>Description</strong> is required. Use <a target="_blank" href="http://daringfireball.net/projects/markdown/dingus">Markdown</a> for syntax.</li>';
   	}
   	
   	/* Display errors if any, or submit */
   	if (error_list != '') {
   		errors = '<ul>' + error_list + '</ul>';
   		$("#errors, blockquote.success").remove();
   		$("#event_form").before("<blockquote id=\"errors\"><h3>There are errors in your form.</h3>" + errors + "</blockquote>");
   		$("#errors").slideDown("fast");
   		window.location = "#errors";
   		return false;
   	} else {
   		/* Throw up a warning alert if they choose Delete */
			if ($("select[name='active']").val() == "999") {
				var holdon = confirm("Are you 100% sure that you want to delete this event? Doing so will delete any and all data associated with this event. Choose [CANCEL] if you made a mistake.");
				if (holdon) {
					alert("You have chosen to delete everything! Quit your browser immediately if this is a mistake.");
					$(this).parent().submit();
				} else {
					alert("Whew! Crisis averted!");
					return false;
				}
			} else {
				$(this).val("Submitting...")/*.attr("disabled","disabled")*/;
				$(this).parent().submit();
			}
   	}
   	
   });
   
 /* Contact Form Validation */
   $("#contact_form :submit").click(function() {
   
   	var error_list = ''; var errors = '';
   	if ($("input[name='first_name']").val() == "") {
   		error_list = error_list + '<li><strong>Your First Name</strong> is required.</li>';
   	}
		if ($("input[name='last_name']").val() == "") {
   		error_list = error_list + '<li><strong>Your Last Name</strong> is required.</li>';
   	}
   	if ($("input[name='title']").val() == "") {
   		error_list = error_list + '<li><strong>Title</strong> is required.</li>';
   	}
   	if ($("input[name='company']").val() == "") {
   		error_list = error_list + '<li><strong>Company</strong> is required.</li>';
   	}
   	if ($("input[name='address1']").val() == "") {
   		error_list = error_list + '<li><strong>Address 1</strong> is required.</li>';
   	}
   	if ($("input[name='city']").val() == "") {
   		error_list = error_list + '<li><strong>City</strong> is required.</li>';
   	}
   	if ($("select[name='state_id']").val() == "") {
   		error_list = error_list + '<li><strong>State / Province</strong> is required.</li>';
   	}
   	if ($("input[name='zip']").val() == "") {
   		error_list = error_list + '<li><strong>Zip / Postal Code</strong> is required.</li>';
   	}
   	if ($("select[name='country_id']").val() == "") {
   		error_list = error_list + '<li><strong>Country</strong> is required.</li>';
   	}
   	if ($("input[name='phone']").val() == "") {
   		error_list = error_list + '<li><strong>Phone</strong> is required.</li>';
   	} else {
   		if (!phone_filter.test($("input[name='phone']").val())) {
   			error_list = error_list + '<li>The value you provided for <strong>Phone</strong> is not valid.</li>';
   		}
   	}
   	if ($("input[name='email_wtf']").val() == "") {
   		error_list = error_list + '<li><strong>E-mail</strong> is required.</li>';
   	} else {
			if (!email_filter.test($("input[name='email_wtf']").val())) {
				error_list = error_list + '<li>The e-mail address you provided for <strong>E-mail</strong> is not valid.</li>';
			}
		}
		if ($("input[name='site_url']").val() == "") {
   		error_list = error_list + '<li><strong>Website</strong> is required.</li>';
   	} else {
			if (!url_filter.test($("input[name='site_url']").val())) {
   			error_list = error_list + '<li>The address you provided for <strong>Website</strong> is not valid. (ex. www.ebay.com)</li>';
   		}
   	}
   	if ($("select[name='category_id']").val() == "") {
   		error_list = error_list + '<li><strong>Business Type</strong> is required.</li>';
   	}
   	if ($("select[name='iwant']").val() == "") {
   		error_list = error_list + '<li><strong>I am interested in...</strong> is required.</li>';
   	}
   	if ($("input[name='spam']").val() == "" || $("input[name='spam']").val() != 9) {
   		error_list = error_list + '<li>Please answer the simple math problem at the end of the form.</li>';
   	}
	
   	if (error_list != '') {
   		errors = '<ul>' + error_list + '</ul>';
   		$("#errors, blockquote.success").remove();
   		$("#contact_form").before("<blockquote id=\"errors\">" + errors + "</blockquote>");
   		$("#errors").slideDown("fast");
   		window.location = "#errors";
   		return false;
   	} else {
   		$(this).val("Submitting...");
			$(this).parent().submit();   
   	}
   });
      
});