var jQueryScope = {};
(function($){
	var carouselIntervalTime = 10000;
	var carouselIntervalID;
	
	jQueryScope.showForgotPasswordLayer = showForgotPasswordLayer;
	jQueryScope.toggleMapFullScreen = toggleMapFullScreen;
	
	$(document).ready(function(){
		initUtilityNav();
		initMainNav();
		initFooter();
		initSignIn();
		checkForResetPassScreen();
		
		initHome();
		//initSideNav();
		initAccordion();
		initTrailBuilders();
		initTabs();
		initCreateAccount();

                $('#ChangePasswordForm_ChangePasswordForm').submit(function() {
                    $('.error').remove();
                    if ($('#ChangePasswordForm_ChangePasswordForm_NewPassword1').val().length<3) {
                        if ($('input[name=lang]').val()=='en_US') {
                            $('#NewPassword1').before('<span class="error" id="pass_char_error" style="display: inline; ">Your password must be at least 3 characters long</span>');
                        } else {
                            $('#NewPassword1').before('<span class="error" id="pass_char_error" style="display: inline; ">Votre mot de passe doit contenir au moins trois caractères.</span>');
                        }
                        return false;
                    }

                    if ($('#ChangePasswordForm_ChangePasswordForm_NewPassword1').val()!=$('#ChangePasswordForm_ChangePasswordForm_NewPassword2').val()) {
                        if ($('input[name=lang]').val()=='en_US') {
                            $('#NewPassword1').before('<p class="error" style="display:block;">Passwords don’t match. Please try again.</p>');
                        } else {
                            $('#NewPassword1').before('<p class="error" style="display:block;">Les mots de passe ne sont pas les mêmes. Veuillez essayer de nouveau.</p>');
                        }
                        return false;
                    }

                });
		
		$(".input_labelinside").each(function(){
			$(this).focus(function(){
				if($(this).val() == $(this).attr("title")){
					$(this).val("");
				}
			}).blur(function(){
				if($(this).val() == ""){
					$(this).val($(this).attr("title"));
				}
			}).val($(this).attr("title"));
		});
		
		$(".terms_lb").each(function(){
			$("#"+$(this).attr("id")).attr("href", getHash($("#"+$(this).attr("id")).attr("href")));
			$("#"+$(this).attr("id")).fancybox({
				titleShow: false,
				scrolling: false,
				padding: 0,
				showCloseButton: false,
				onStart: function(){
					$("#enter_forgot_pass").show();
					$("#forgot_pass_sent").hide();
				},
				onClosed: function(){
					$(".lightbox input").val("");
					$(".lightbox .error").hide();
				}
			});
		});
		
		$(".video_iframe").each(function(){
			$("#"+$(this).attr("id")).attr("href", getHash($("#"+$(this).attr("id")).attr("href")));
			var videoURL = $(this).attr("rev");
			$("#"+$(this).attr("id")).fancybox({
				titleShow: false,
				scrolling: true,
				padding: 0,
				showCloseButton: true,
				autoDimensions: false,
				width: 480,
				height: 360,
				onStart: function(){
					$("#video_lb > iframe").attr("src", videoURL+"?wmode=opaque");
				},
				onClosed: function(){
					$(".lightbox input").val("");
				}
			});
		});
		
		$("#account_thanks_hidden_btn").attr("href", getHash($("#account_thanks_hidden_btn").attr("href")));
		$("#account_thanks_hidden_btn").fancybox({
			titleShow: false,
			scrolling: false,
			padding: 0,
			showCloseButton: false,
			onClosed: function(){
				$(".lightbox input").val("");
				$(".lightbox .error").hide();
			}
		});
		var hashLink = getHash(window.location.href);
		if(hashLink == "#thanks"){
			$("#account_thanks_hidden_btn").click();
			$(".lb_cancel").click(function(){
				$.fancybox.close();
				return false;
			});
			if(typeof _gaq !== "undefined") _gaq.push(['_trackEvent', 'Account', 'Created']);
		}
		
		$(".imageRoll").each(function(){
			$(this).imageRollOver("_roll");
		});
		
		$("h3.blue a").mouseover(function(){
			$(this).parent().css({backgroundPosition: "0px -17px"});
		}).mouseleave(function(){
			$(this).parent().css({backgroundPosition: "-9px 0px"});
		});
		
		$(".middleContent").each(function(){
			var containerHeight = $(this).outerHeight();
			var contentHeight = $("h3", this).outerHeight(true) + $("p", this).outerHeight(true);
			$("h3", this).css({
				paddingTop: (containerHeight-contentHeight)/2
			});
		});
		
		if(ismobilesafari()){
			$(".content_frame").addClass("mobile_safari");
			$("#newsletter_fields input[type='text']").width(178);
		}
		
	});
	
	function toggleMapFullScreen(on){
		if($("#map_iframe").length){
			if(on){
				$("#content_shell").addClass("fullscreen_map");
			} else {
				$("#content_shell").removeClass("fullscreen_map");
			}
		}
	}
	
	function initUtilityNav(){
		$("#search_fields > input[type=text]").focus(function(){
			if($(this).val() == $("#search_fields > input[type=submit]").val()){
				$(this).val("");
			}
		}).blur(function(){
			if($(this).val() == ""){
				$(this).val($("#search_fields > input[type=submit]").val());
			}
		})
		$("#search_fields > input[type=text]").each(function(){
			if(!$(this).hasClass("prepopulate")){
				$(this).val($("#search_fields > input[type=submit]").val());
			}
		});
		$(".search_form").each(function(){
			$(this).submit(function(){
				if(!$("input[type=text]", this).brValidate(["required"])[0]){
					return false;
				}
				if($("input[type=text]", this).val() == $("input[type=submit]", this).val()){
					return false;
				}
			});
			return true;
		});
	}
	
	function initMainNav(){
		$("#main_nav > li").mouseover(function(){
			$("ul", this).show();
		}).mouseleave(function(){
			$("ul", this).hide();
		});
		
		$("#main_nav li").click(function(e){
			if(!$("a", this).length) return false;
			var urlPath = $("a", this).attr("href");
			if($("a", this).attr("target") != "_blank"){
				window.location = urlPath;
			} else {
				window.open(urlPath);
			}
			e.stopPropagation();
		}).css("cursor", "pointer");
		
		/*Used JS to add a li element at the beginning of the drop down in the main nav, 
		used to display the drop shadow because IE7 wasn't playing nice with the z-index-ing */
		$("#main_nav > li > ul").append("<li class='sub_nav_shadow'></li>");
		
		/*Add non-breaking spaces to text in the main nav, issues with IE7...again.*/
		$("#main_nav > li > a").each(function(){
			var val = $(this).html().split(" ").join("&nbsp;");
			$(this).html(val);
		});
	}
	
	function initFooter(){
		$("#footer_newsletter input[type=text]").bind("validate", function(){
			var result = $(this).brValidate(["required", "email"]);
			if(result[0] && result[1]){
				//valid
				$("#footer_newsletter_error").hide();
			} else {
				//empty or invalid
				$("#footer_newsletter_error").show();
			}
		});
		
		$("#footer_newsletter").submit(function(){
			var valid = true;
			$("#footer_newsletter input[type=text]").validate();
			if($("#footer_newsletter_error").css("display") != "none"){
				valid = false;
			}
			
			return valid;
		});
	}
	
	function initHome(){
		if($("#carousel_contents").length){
			$("#carousel_contents > div").hide();
			$("#carousel_contents").attr("rel", -1);
			jQueryScope.showCarouselContent = showCarouselContent;
			showCarouselContent();
			carouselIntervalID = setInterval("jQueryScope.showCarouselContent()", carouselIntervalTime);
			
			$("#carousel_contents").after($("#carousel_nav"));
			$("#carousel_nav > li > a > span").each(function(){
				var val = $(this).html().split(" ").join("&nbsp;");
				$(this).html(val);
				$(this).css({
					position: "absolute",
					left: "50%",
					marginLeft: -($(this).outerWidth()/2),
					visibility: "hidden"
				});
				$(this).parent().append("<span class='carousel_pointer'></span>");
			});
			
			$("#carousel_nav > li > a").mouseover(function(){
				$("span", this).css("visibility", "visible");
				$(".carousel_pointer", this).css("visibility", "visible");
				//$(this).css("backgroundPosition", "center");
				$(this).addClass("rollover");
			}).mouseleave(function(){
				$("span", this).css("visibility", "hidden");
				$(".carousel_pointer", this).css("visibility", "hidden");
				$(this).removeClass("rollover");
			}).click(function(){
				if(carouselIntervalTime){
					clearInterval(carouselIntervalID);
					carouselIntervalTime = 0;
				}
				showCarouselContent($(this).parent().index());
				return false;
			});
		}
		if($("#home_donate_button").length){
			$("select[name=home_donation_dropdown]").change(function(){
				$("#home_donate_button").attr("href", $("select[name=home_donation_dropdown]").val());
			}).change();
		}
	}
	
	function showCarouselContent(newIndex){
		var index = parseInt($("#carousel_contents").attr("rel"));
		$("#carousel_contents > div").each(function(slideIndex){
			$(this).fadeOut();
			$("a", $($("#carousel_nav > li")[slideIndex])).css("backgroundPosition", "right");
		});
		index++;
		if($("#carousel_contents > div").length <= index){
			index = 0;
		}
		if(newIndex != undefined){
			index = newIndex;
		}
		$("a", $("#carousel_nav > li")[index]).css("backgroundPosition", "left");
		$($("#carousel_contents > div")[index]).fadeIn();
		$("#carousel_contents").attr("rel", index);
	}
	
	function initSideNav(){
		if($("#side_nav").length){
			$("#side_nav > li > ul > li > a").click(function(){
				if($(".toggle", $(this).parent()).length){
					$(".toggle", $(this).parent()).toggle();
					return false;
				}
			});
			$(".toggle_show").show().removeClass("toggle_show");
		}
	}
	
	function initAccordion(){
		if($(".accordion").length){
			$(".accordion > li > div").hide();
			$(".accordion > li > h4").click(function(){
				var information = $(this).parent();
				$("div", information).toggle();
				if($("div", information).css("display") != "none"){
					$(this).css("backgroundPosition", "1px -17px");	
				} else {
					$(this).css("backgroundPosition", "-17px 0px");	
				}
			}).css("cursor", "pointer");
		}
	}
	
	function initTrailBuilders(){
		if($("#builder_list").length){
			$("#builders > div").hide();
			$("#builder_list").change(function(){
				$("#builders > div").hide();
				$("#"+$(this).val()).show();
			});
			$("#builder_list").change();
		}
	}
	
	function initTabs(){
		if($(".tabs").length){
			$(".tabs > li > a").click(function(e){
				var tabUL = $(this).parent().parent();
				$("li", tabUL).removeClass("active");
				$($(this).parent()).addClass("active");
				$("div[rel="+$(tabUL).attr("id")+"]").hide();
				$($(this).attr("rel")).show();
				e.stopPropagation();
				return false;	
			});
			$(".tabs > li").click(function(){
				$("a", this).click();	
			}).css("cursor", "pointer");
			$(".tabs > li:first-child").click();
		}
	}
	
	function initSignIn(){
		$("#sign_in_form").submit(loginUser);
		$("#sign_in_form2").submit(loginUser);
		
		$("#forgot_pass_link").attr("href", getHash($("#forgot_pass_link").attr("href")));
		$("#forgot_pass_link").fancybox({
			titleShow: false,
			scrolling: false,
			padding: 0,
			showCloseButton: false,
			onStart: function(){
				$("#enter_forgot_pass").show();
				$("#forgot_pass_sent").hide();
			},
			onClosed: function(){
				$(".lightbox input").val("");
				$(".lightbox .error").hide();
			}
		});
		
		$("#forgot_pass_form").submit(sendPassword);
		
		replaceFormSubmitBtn($("#sign_in_form"));
		replaceFormSubmitBtn($("#sign_in_form2"));
		replaceFormSubmitBtn($("#forgot_pass_form"));
		$(".close_btn").click(function(){
			$.fancybox.close();
		});
		$(".inpage_lb").each(function(){
			$("#"+$(this).attr("id")).attr("href", getHash($("#"+$(this).attr("id")).attr("href")));
			$("#"+$(this).attr("id")).fancybox({
				titleShow: false,
				scrolling: false,
				padding: 0,
				showCloseButton: false,
				onClosed: function(){
					$(".lightbox input").val("");
					$(".lightbox .error").hide();
				}
			});
		});
	}
	
	function showForgotPasswordLayer(){
		$("#forgot_pass_link").click();
	}
	
	function initCreateAccount(){
		if($("#createAccount").length){
			replaceFormSubmitBtn($("#createAccount"));
			$("#createAccount input[name=displayname]").bind("validate", function(){
				if($(this).brValidate(["required"])[0]){
					$("#displayname_error").hide();
				} else {
					$("#displayname_error").show();
				}
			}).blur($("#createAccount input[name=displayname]").validate);
			
			if($("#createAccount input[name=username]").length){ //doesn't exist in edit account form, so check for it
				$("#createAccount input[name=username]").bind("validate", function(){
					var results = $(this).brValidate(["required", {minCharCount: 3}]);
					if(results[0]){ //field is not empty, check if it's long enough
						$("#username_empty_error").hide();
						if(results[1]){ //long enough, check if it exists
							if(usernameExists($(this).val())){
								$("#username_error").show();
							} else {
								$("#username_error").hide();
							}
							$("#username_short_error").hide();
						} else {
							$("#username_short_error").show();
							$("#username_error").hide();
						}
					} else {
						$("#username_empty_error").show();
						$("#username_error").hide();
						$("#username_short_error").hide();
					}
				}).blur($("#createAccount input[name=username]").validate);
				
				$('input[name=username]').change(
	                function () {
						//IE7 doesn't support Array.indexOf, only String.indexOf
	                    a=$(this).val().split("");
	                    //var allowed=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','À','à','Â','â','Æ','æ','Ç','ç','È','è','É','é','Ê','ê','Ë','ë','Î','î','Ï','ï','Ô','ô','Œ','œ','Ù','ù','Û','û','Ü','ü'];
	                    var allowed=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
	                    allowed = allowed.join(""); //Converted to string, fixes the indexOf issue in IE
						n=""; 
						for (i in a) { //IE couldn't loop through a string, had to convert it to Array above
							if (allowed.indexOf(a[i].toLowerCase())>-1) n+=a[i];
						}
	                    $(this).val(n);
	                }
	            );
			}
			
			$("#createAccount input[name=email]").bind("validate", function(){
				$(this).val($(this).val().toLowerCase());
				var result = $(this).brValidate(["required", "email"]);
				if(!result[0] || !result[1]){
					$("#email_error").show();
				} else {
					$("#email_error").hide();
					if(emailExists($(this).val())){
						$("#email_format_error").show();
					} else {
						$("#email_format_error").hide();
					}
				}
			}).blur($("#createAccount input[name=email]").validate);
			
			$("#createAccount input[name=conf_email]").bind("validate", function(){
				$(this).val($(this).val().toLowerCase());
				if($(this).brValidate([{matches: [$("#createAccount input[name=email]").val(), "false"]}])[0]){
					$("#conf_email_error").hide();
				} else {
					$("#conf_email_error").show();
				}
			}).blur($("#createAccount input[name=conf_email]").validate);
			
			$("#createAccount input[name=password]").bind("validate", function(){
				var result = $(this).brValidate(["required", {minCharCount: 3}]);
				if(result[0]){
					$("#pass_error").hide();
					if(result[1]){
						$("#pass_char_error").hide();
					} else {
						$("#pass_char_error").show();
					}
				} else {
					$("#pass_error").show();
					$("#pass_char_error").hide();
				}
			}).blur($("#createAccount input[name=password]").validate);
			
			$("#createAccount input[name=conf_password]").bind("validate", function(){
				if($(this).brValidate([{matches: [$("#createAccount input[name=password]").val(), "false"]}])[0]){
					$("#pass_match_error").hide();
				} else {
					$("#pass_match_error").show();
				}
			}).blur($("#createAccount input[name=conf_password]").validate);
			

			$("#createAccount input[name=city]").bind("validate", function(){
				var results = $(this).brValidate(["required"]);
				if(results[0]){
					$("#city_error").hide();
				} else {
					$("#city_error").show();
				}
			}).blur($("#createAccount input[name=city]").validate);



			$("#createAccount input[name=phone]").bind("validate", function(){
				var results = $(this).brValidate(["required"]);
				if(results[0]){
					$("#phone_error").hide();
				} else {
					$("#phone_error").show();
				}
			}).blur($("#createAccount input[name=phone]").validate);

			
			$("#createAccount select[name=province]").bind("validate", function(){
				if($(this).brValidate(["required"])[0]){
					$("#province_error").hide();
				} else {
					$("#province_error").show();
				}
			}).change($("#createAccount select[name=province]").validate);

			$("#createAccount input[name=terms]").bind("validate", function(){
				if($(this).brValidate(["required"])[0]){
					$("#terms_error").hide();
				} else {
					$("#terms_error").show();
				}
			}).change($("#createAccount input[name=terms]").validate);
			
			$("#createAccount").submit(function(){
				var valid = true;
				
				$("#createAccount input[name=displayname]").validate();
				if($("#createAccount input[name=username]").length) $("#createAccount input[name=username]").validate();
				$("#createAccount input[name=password]").validate();
				$("#createAccount input[name=conf_password]").validate();
				$("#createAccount input[name=phone]").validate();
				$("#createAccount input[name=email]").validate();
				$("#createAccount input[name=conf_email]").validate();
				$("#createAccount input[name=city]").validate();
				$("#createAccount select[name=province]").validate();
				$("#createAccount input[name=terms]").validate();
				
				$("#createAccount .error").each(function(){
					if($(this).css("display") != "none"){
						valid = false;
					}
				});
				
				if(valid){
					var emailValue = $("#createAccount input[name=email]").val();
					$("#createAccount input[name=email]").val(emailValue.toLowerCase());
				}
				return valid;
			});
		}
	}
	
	function loginUser(){
		if(jQueryScope.tempLogin) return false;
		var data;
		var action="/Security/loginform";
		var loginError;
		jQueryScope.tempLogin = true;
		if($(this).attr("id") == "sign_in_form"){
			data={ 
				username: $('#sign_in_form #user').val(),
				password: $('#sign_in_form input[type=password]').val(),
				ajax: true
			};
			action = $("#sign_in_form").attr("action");
			loginError = $("#login_error");
		} else {
			data={ 
				username: $('#sign_in_form2 #user2').val(),
				password: $('#sign_in_form2 input[type=password]').val(), 
				ajax: true
			};
			action = $("#sign_in_form2").attr("action");
			loginError = $("#login_error2");
		}
		
		$.ajax({ 
			url: action,
			dataType: 'json',
			type: 'POST',
			data: data,
			success: function(r){
				if(r.error) {//Login failed
					$(loginError).show();
					jQueryScope.tempLogin = false;
				} else {
					//Login success
					$(loginError).hide();
					jQueryScope.tempLogin = false;
					window.location = window.location.href;
				} 
			}
		});
		
		
		return false;
	}
	
	function sendPassword(){
		if(jQueryScope.tempPasswordSent) return false;
		if(!$("#phone_email").brValidate(["email"])[0]){
			$("#forgotpass_emailerror").show();
			return false;
		} else{
			$("#forgotpass_emailerror").hide();
		}
		var data={ 
			Email: ($('#forgot_pass_form #phone_email').val()).toLowerCase(),
			lang: $('input[name=lang]').val(),
			ajax: true
		};
		jQueryScope.tempPasswordSent = true;
		$.ajax({ 
			url: $('#forgot_pass_form').attr('action'),
			dataType: 'json',
			type: 'POST',
			data: data,
			success: function(r){
				if(r.error) {//Login failed
					//alert("raspberry");
					$("#forgotpass_error").show();
					jQueryScope.tempPasswordSent = false;
				} else {
					//Login success
					//alert('success');
					$("#forgotpass_error").hide();
					$("#enter_forgot_pass").hide();
					$("#forgot_pass_sent").fadeIn();
					jQueryScope.tempPasswordSent = false;
				} 
			}
		});
		
		return false;
	}
	
	function getHash(url){
		var segments = url.split("#");
		return "#"+segments[1];
	}
	
	function replaceFormSubmitBtn(form){
		var buttonHTML = $('<a href="" class="rounded_btn" onclick="return false;"><span>'+$("input[type=submit]", form).val()+'</span></a>');
		$("input[type=submit]", form).after(buttonHTML).css({
			position: "absolute",
			left: -5000 //PLACE THE REAL FORM BUTTON OFFSCREEN
		})
		
		$(buttonHTML).click(function(e){
			$(form).submit();
			return false;
		});
	}
	
	function checkForResetPassScreen(){
		//reset_pass
		$("#reset_pass_hidden_btn").attr("href", getHash($("#reset_pass_hidden_btn").attr("href")));
		replaceFormSubmitBtn($("#reset_password_form"));
		$("#reset_pass_hidden_btn").fancybox({
			titleShow: false,
			scrolling: false,
			padding: 0,
			showCloseButton: false,
			onClosed: function(){
				$(".lightbox input").val("");
				$(".lightbox .error").hide();
			}
		});
		
		//validation
		$("#reset_password_form #pass").bind("validate", function(){
			var results = $(this).brValidate(["required", {minCharCount: 3}]);
			if(results[0]){
				if(results[1]){
					//good to go
					$("#resetPass_short").hide();
				} else {
					//not long enough
					$("#resetPass_short").show();
				}
				$("#resetPass_passempty").hide();
			} else {
				//empty
				$("#resetPass_passempty").show();
			}
		}).blur($("#reset_password_form #pass").validate);
		
		$("#reset_password_form #conf_pass").bind("validate", function(){
			var results = $(this).brValidate([{matches: [$("#reset_password_form #pass").val(), "false"]}]);
			if(results[0]){
				//good to go
				$("#resetPass_matcherror").hide();
			} else {
				//doesn't match
				$("#resetPass_matcherror").show();
			}
		}).blur($("#reset_password_form #conf_pass").validate);
		
		$("#reset_password_form").submit(function(){
			if(jQueryScope.tempResetPass) return false;
			jQueryScope.tempResetPass = true;
			var valid = true;
			$("#reset_password_form #pass").validate();
			$("#reset_password_form #conf_pass").validate();
			$(".error", this).each(function(){
				if($(this).css("display") != "none"){
					valid = false;
					jQueryScope.tempResetPass = false;
				}
			});
			
			return valid;
		});
		
		var hashLink = getHash(window.location.href);
		if(hashLink == "#resetPassword"){
			$("#reset_pass_hidden_btn").click();
			$(".lb_cancel").click(function(){
				$.fancybox.close();
				return false;
			});
		}
	}
	
	function emailExists(email) {
		try {
			testExists=jQuery.parseJSON($.ajax({type: 'post', url:"/ProfileSecurity/checkEmailExists",data:{ email: email },async:false}).responseText);
		} catch (e) {
			//Server request failure
		}
		return testExists.email_exists;
	}

	function usernameExists(username) {
		try {
			testExists=jQuery.parseJSON($.ajax({type: 'post', url:"/ProfileSecurity/checkUsernameExists",data:{ username: username},async:false}).responseText);
		} catch (e) {
			//Server request failure
		}
		return testExists.user_exists;
	}
	
	function ismobilesafari(){
		return navigator.userAgent.match(/(iPod|iPhone|iPad)/);
	}
})(jQuery);

