var $j = jQuery.noConflict();
$j(document).ready(function($) {
	init();
	if ($j(".outreach-application-wrapper").size() > 0) {
		addValidMethods();
		initApplication();
		checkLogon();
		handleFormEvents();
	}
});
function checkLogon() {
	$u = $j.cookie("outreachAppLogin");
	$a = $j.cookie("outreachAppID");
	if ($u) {
		$j(".logonLink").parent().html("Logged on as <a href='#' class='logoffLink'>" + $u + "</a>").addClass("loggedOn");
		$j("#contactemail,#contactpin").attr("readonly", "readonly");
		$j.getJSON('ajax/uinfo.php', {
			uid : $u
		}, function(data) {
			$j.each(data["data"], function(index, value) {
				$j("#contact" + index).val(value);
			});
		});
	} else {
		$j("#contactemail,#contactpin").removeAttr("readonly");
		$j(".logoffLink").parent().html("Already started an application? <a href='#' class='logonLink'>Login now!</a>").removeClass("loggedOn");
		$j("#tabContainer").tabs("select", 0);
	}
	if ($a) {
		$j.getJSON('ajax/ainfo.php', function(data) {
			$j.each(data["data"]["org"], function(index, value) {
				$j("#org" + index).val(value);
				$j("input[value=" + value + "][name=org" + index + "]").attr("checked", "checked").change();
				if (index == "type") {
					if (value != "unspc" && value != "intlnpc" && value != "fpo" && value != null) {
						$j("#orgotherbox").val(value);
						$j("#orgother").attr("checked", "checked").change();
					}
				}
				if (index == "exist" && value != 0 && value != "NULL" && value != "null" && value != null) {
					$j("#orgrelnamebox").val(value);
					$j("#yesexist").attr("checked", "checked").change();
				}
			});
			$j.each(data["data"]["lead"], function(index, value) {
				$j("#leader" + index).val(value);
			});
			if ($j("#orgleadercount").val() > 0) {
				$j("#orgleaderteam").attr("checked", "checked").change();
			} else {
				$j("#orgnoleaderteam").attr("checked", "checked").change();
			}
		});

	}
}
function updateAppProgress(loc) {
	$j("#tabContainer").tabs("select", $j("#tabContainer").tabs("option", "selected") + loc);
	$j("#appProgressBar").progressbar("value", (($j("#tabContainer").tabs("option", "selected")) / $j("#tabContainer form").size()) * 100);

}
function init() {
	var cat = $j(".iteminfo:first");
	$j("#nav-bar li").each(function() {
		if (cat.text().toLowerCase().match($j(this).text().toLowerCase())) {
			var color = $j(this).css("backgroundColor");
			$j(".color-spacer").css("backgroundColor", color);
		}
	});
	$j(".problems").live("click",function(e){showProblemForm(e)});
}
function initApplication() {
	$j("#tabContainer").tabs({
		fx : {
			opacity : 'toggle'
		}
	});
	$j("#appProgressBar").progressbar({
		value : 0
	});
	updateAppProgress();
	$j.address.change(function(event) {
		if (window.location.hash == "") {
			$j("#tabContainer").tabs("select", 0);
		}else {
			$j("#tabContainer").tabs("select", window.location.hash);
		}
	});

	$j("#tabContainer").bind("tabsshow", function(event, ui) {
		window.location.hash = ui.tab.hash;
	});
	$j(".logoffLink").live("click", function(e) {
		e.preventDefault();
		$j("<p>Are you sure you want to logoff?</p>").dialog({
			draggable : false,
			modal : true,
			position : [ "center", "center" ],
			width : 450,
			minHeight : 50,
			resizable : false,
			title : "Logoff?",
			buttons : [ {
				text : "Yes",
				click : function() {
					logoff(this);
				}
			}, {
				text : "No",
				click : function() {
					$j(this).dialog("destroy").remove();
				}
			} ]
		});
		return false;
	});
	$j(".logonLink").live("click", function(e) {
		e.preventDefault();
		$j("<div class='dialogRoot'><form action='ajax/login.php' method='post' id='loginForm'><ul><li><label for='logemail'>Email:</label><input type='text' name='logemail' id='logemail' /></li><li><label for='logpass'>PIN:</label><input type='password' name='logpass' id='logpass' size='4' maxlength='4'/></li><li class='button-holder'><input type='submit' value='Login'/><input type='button' class='closeDialog' value='Cancel'/></li></ul></form></div>").dialog({
			draggable : false,
			modal : true,
			position : [ "center", "center" ],
			width : 325,
			minHeight : 50,
			resizable : false,
			title : "Login"
		});
		$j("#loginForm").validate({
			rules : {
				logemail : {
					required : true,
					email : true
				},
				logpass : {
					required : true,
					range : [ 0000, 9999 ],
					minlength : 4
				}
			},
			messages : {
				logemail : {
					required : "*",
					email : "*"
				},
				logpass : {
					required : "*",
					range : "*",
					minlength : "*"
				}
			},
			errorElement : "span"
		});
		$j("#loginForm").live("submit", function(form) {
			if ($j("#loginForm").valid()) {
				$j("#loginForm").ajaxSubmit({
					beforeSubmit : showProgress,
					success : showLoginResponse
				});
			} else {
				showFormError();
			}
			return false;
		});
		$j(".newApp").live("click", function() {
			$j("table.apps").dialog("destroy").remove();
			$j.cookie("outreachAppID", null);
		});
		$j(".appLink").live("click", function(e) {
			e.preventDefault();
			$j("table.apps").dialog("destroy").remove();
			$j.cookie("outreachAppID", $j(e.target).attr("href"));
			checkLogon();
			$j("#tabContainer").tabs("select", 2);

		});
		$j("input:submit,input:button").button();
		return false;
	});
	$j("input:submit,input:button").button();
	$j(".closeDialog").live("click", function() {
		$j(this).parents(".dialogRoot").dialog("destroy").remove();
	});
}
function handleFormEvents() {
	var sel = "Please choose an option";
	$j("input[name=orgleaderteam]").change(function() {
		var checked = $j('input[name=orgleaderteam]:checked').attr("id");
		if (checked == "orgnoleaderteam" || checked == null) {
			$j("#orgleadercount").parent().hide().prev().hide();
		} else {
			$j("#orgleadercount").parent().show().prev().show();
		}
	});
	$j("input[name=orgtype]").change(function() {
		var checked = $j('input[name=orgtype]:checked').attr("id");
		if (checked != "orgother") {
			$j("#orgotherbox").parent().hide();
		} else {
			$j("#orgotherbox").parent().show();
		}
	});
	$j("input[name=orgexist]").change(function() {
		var checked = $j('input[name=orgexist]:checked').attr("id");
		if (checked != "yesexist") {
			$j("#orgrelnamebox").parent().hide();
		} else {
			$j("#orgrelnamebox").parent().show();
		}
	});
	$j("#tab2.outreach-application").validate({
		rules : {
			contactfirstname : "required",
			contactlastname : "required",
			contactemail : {
				required : true,
				email : true
			},
			contactphone : {
				required : true,
				minlength : 10
			},
			contactpin : {
				required : true,
				range : [ 0000, 9999 ],
				minlength : 4
			}
		},
		messages : {
			contactfirstname : "Please specify",
			contactlastname : "Please specify",
			contactemail : {
				required : "We need your email address to contact you",
				email : "Must be in the format of name@domain.com"
			},
			contactphone : {
				required : "We need your phone number to contact you",
				minlength : "Please enter a valid phone number"
			},
			contactpin : {
				required : "Please enter a PIN so you can return!",
				range : "Please enter a 4 digit PIN",
				minlength : "Please enter a 4 digit PIN"
			}
		},
		errorElement : "span",
		errorPlacement : errPlac
	});
	$j("#tab3.outreach-application").validate({
		rules : {
			orgname : "required",
			orgstreet : "required",
			orgcity : "required",
			orgst : "required",
			leaderfirstname : "required",
			leaderlastname : "required",
			leaderphone : "required",
			leaderemail : {
				required : true,
				email : true
			},
			orgleadercount : {
				required : {
					depends : function(element) {
						if ($j("#orgleaderteam:checked").size() > 0) {
							return true;
						} else {
							return false;
						}
					}
				}
			},
			orgleaderteam : "required",
			orgage : {
				required : true,
				range : [ 0000, 9999 ]
			}
		},
		messages : {
			orgname : "Please specify",
			orgstreet : "Please specify",
			orgcity : "Please specify",
			orgst : "Please specify",
			leaderfirstname : "Please specify",
			leaderlastname : "Please specify",
			leaderphone : "Please profive a phone number for a leader",
			leaderemail : {
				required : "Please provide an email for a leader",
				email : "Must be in the format of name@domain.com"
			},
			orgleadercount : "Please specify a valid number",
			orgleaderteam : sel,
			orgage : "Please specify a valid number"
		},
		errorElement : "span",
		errorPlacement : errPlac
	});
	$j("#tab4.outreach-application").validate({
		rules : {
			orgotherbox : {
				required : {
					depends : function(element) {
						if ($j("#orgother:checked").size() > 0) {
							return true;
						} else {
							return false;
						}
					}
				}
			},
			orgtype : "required",
			orgloc : "required",
			orgreligion : "required",
			orginsttype : "required"
		},
		messages : {
			orgotherbox : "Please specify",
			orgtype : sel,
			orgloc : sel,
			orgreligion : sel,
			orginsttype : sel
		},
		errorElement : "span",
		errorPlacement : errPlac
	});
	$j("#tab5.outreach-application").validate({
		rules : {
			orgrelnamebox : {
				required : {
					depends : function(element) {
						if ($j("#yesexist:checked").size() > 0) {
							return true;
						} else {
							return false;
						}
					}
				}
			},
			orgexist : "required",
			orgpast : "required"
		},
		messages : {
			orgotherbox : "Please specify"
		},
		errorElement : "span",
		errorPlacement : errPlac
	});
	$j(".outreach-application").submit(function(form) {
		if ($j(form.target).valid()) {
			$j(form.target).ajaxSubmit({
				data : {
					method : this.id
				},
				beforeSubmit : showProgress,
				success : showResponse
			});
		} else {
			showFormError();
		}
		return false;
	});
	$j(".prevBut").live("click", function() {
		scrollFormTop();
		updateAppProgress(-1);
	});
	$j("input[type=radio]").change();
}
function errPlac(error, element) {
	if (element.attr("type") == "radio") {
		el = $j("<li class='err'></li>").html(error);
		element.parent().prev().after(el);
	} else {
		element.after(error);
	}
}
function showProgress(title) {
	$j("<div class='progressBar'><p class='loading'></p></div>").dialog({
		draggable : false,
		modal : true,
		minHeight : 40,
		width : 240,
		title : "Loading",
		position : [ "center", "center" ],
		closeOnEscape : false
	})
}
function closeProgress() {
 $j(".progressBar").dialog("destroy").remove();

}
function showResponse(responseText, statusText, xhr, $form) {
	closeProgress();
	var resp = $j.parseJSON(responseText);
	if (resp.success == "false") {

		$j("<p>" + resp.reason + "</p>").dialog({
			draggable : false,
			modal : true,
			position : [ "center", "center" ],
			width : 450,
			minHeight : 50,
			resizable : false,
			title : "Submission Response:",
			buttons : [ {
				text : "Okay",
				click : function() {
					$j(this).dialog("destroy").remove();
				}
			} ]
		});
	} else {
		switch (resp.type) {
		case 'tab2':
			$j.cookie("outreachAppLogin", $j("#contactemail").val());
			break;
		case 'tab3':
			$j.cookie("outreachAppID", resp.id);
			break;
		case 'tab5':
			$j.cookie("outreachAppID", null);
			break;
		}

		scrollFormTop();
		checkLogon();
		updateAppProgress(1);
	}
}
function scrollFormTop() {
	var top = $j("#appNavProg").offset().top;
	$j('body').animate({
		scrollTop : top
	}, "fast");
}
function showLoginResponse(responseText, statusText, xhr, $form) {
	closeProgress();
	var resp = $j.parseJSON(responseText);
	if (resp.success == "false") {

		$j("<p>" + resp.reason + "</p>").dialog({
			draggable : false,
			modal : true,
			position : [ "center", "center" ],
			width : 450,
			minHeight : 50,
			resizable : false,
			title : "Login failure",
			buttons : [ {
				text : "Okay",
				click : function() {
					$j(this).dialog("destroy").remove();
				}
			} ]
		});
	} else {
		$j.cookie("outreachAppLogin", $j("#logemail").val());
		$j("#loginForm").parent().dialog("destroy").remove();
		checkLogon();
		var html = "<table class='apps'><tr><th>Name</th><th>Status</th></tr>";
		if (resp.apps == false) {
			html += "<tr><td class='newAppRow' colspan='2'>No applications found. Create a <a href='#' class='newApp'>new application?</a></td><td></td></tr></table>";
		} else {
			for (app in resp.apps) {
				if (resp.apps[app].status == 0) {
					var respo = "<a href='" + resp.apps[app].id + "' class='appLink'>In Progress</a>";
				} else {
					var respo = "Completed";
				}
				html += "<tr><td>" + resp.apps[app].title + "</td><td>" + respo + "</td></tr>";
			}
			html += "<tr><td class='newAppRow' colspan='2'>Or, create a <a href='#' class='newApp'>new application</a></td><td></td></tr></table>";
		}
		$j(html).dialog({
			draggable : false,
			modal : true,
			position : [ "center", "center" ],
			width : 450,
			minHeight : 50,
			resizable : false,
			title : 'Select an Application',
			buttons : [ {
				text : "Cancel",
				click : function() {
					logoff();
					$j("table.apps").dialog("destroy").remove();
				}
			} ]
		});
	}
}
function logoff(form) {
	$j(form).dialog("destroy").remove();
	$j.cookie("outreachAppLogin", "", -1);
	$j.cookie("outreachAppID", "", -1);
	$j("input").not("input[type=submit],input[type=button],input[type=radio]").val("");
	$j("input:radio").removeAttr("selected");
	checkLogon();
	updateAppProgress(-$j("#tabContainer").tabs("option", "selected"));
}
function showFormError() {
	$j("<p>Please correct invalid entries before submission!</p>").dialog({
		draggable : false,
		modal : true,
		position : [ "center", "center" ],
		width : 450,
		minHeight : 50,
		resizable : false,
		title : "Error on form!",
		buttons : [ {
			text : "Okay",
			click : function() {
				$j(this).dialog("destroy").remove();
			}
		} ]
	});
}
function showProblemForm(e){
	e.preventDefault();
	var html = '<form action="ajax/problems.php" method="post" id="probform"><ul><li><label for="probemail">Email:</label> <input id="probemail" name="probemail" type="text" /></li>';
	html += '<li><label for="probname">Name:</label> <input id="probname" name="probname" type="text" /></li>';
	html += '<li><label for="probprob">Problem:</label> <textarea cols="7" rows="3" id="probprob" name="probprob"/></li></ul></form>';
	$j(html).dialog({
		draggable : false,
		modal : true,
		position : [ "center", "center" ],
		width : 450,
		minHeight : 50,
		resizable : false,
		title : 'Problems?',
		buttons : [ {
			text : "Cancel",
			click : function() {
				$j("#probform").dialog("destroy").remove();
			}
		}, {
			text : "Submit",
			click : function() {
				var o = { 
					target:'#probform'
				}
				$j("#probform").ajaxSubmit(o);
				$j(".ui-button-text:contains('Cancel')").text("Close");
				$j(".ui-button-text:contains('Submit')").parent().remove();
				return false;
			}
		} ]	
	});
}
function addValidMethods() {
	jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
		phone_number = phone_number.replace(/\s+/g, "");
		return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
	}, "Please specify a valid phone number");
	jQuery.validator.addMethod("noSpecial", function(id, element) {
		return this.optional(element) || id.match(/[^\w\d]/);
	}, "Can only contain letters and numbers");
	jQuery.cookie = function(name, value, options) {
		if (typeof value != 'undefined') {
			options = options || {};
			if (value === null) {
				value = '';
				options.expires = -1;
			}
			var expires = '';
			if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
				var date;
				if (typeof options.expires == 'number') {
					date = new Date();
					date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
				} else {
					date = options.expires;
				}
				expires = '; expires=' + date.toUTCString();
			}
			var path = options.path ? '; path=' + (options.path) : '';
			var domain = options.domain ? '; domain=' + (options.domain) : '';
			var secure = options.secure ? '; secure' : '';
			document.cookie = [ name, '=', encodeURIComponent(value), expires, path, domain, secure ].join('');
		} else {
			var cookieValue = null;
			if (document.cookie && document.cookie != '') {
				var cookies = document.cookie.split(';');
				for ( var i = 0; i < cookies.length; i++) {
					var cookie = jQuery.trim(cookies[i]);
					if (cookie.substring(0, name.length + 1) == (name + '=')) {
						cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
						break;
					}
				}
			}
			return cookieValue;
		}
	};
}



