// image preload
var loadingImg = new Image();
loadingImg.src = "/img/loading.gif";

var showSigninBox = function(){

	if ($("#signin-form").css("display") == "none") {
		
		if($("#signin-bar a#webmailSignin").length > 0) {
			$("#webmailSignin-form")[0].reset();
			$("#webmailSignin-form").hide();
			$("#signin-bar a.webmailSignin").find("span").html("&#x25bc;");
		}
		
		var $signinBlock = $("#signin-bar a");
		var offset = $signinBlock.offset();
		var $form = $("#signin-form");
		
		$("#signin-bar a#signin").find("span").html("&#x25b2;");
		
		$form[0].reset();
		
		if ($("#signin-bar a#webmailSignin").length > 0) {
			$form.css({
				'top': offset.top + 60,
				'left': offset.left + 120
			}).show();
		} else {
			$form.css({
				'top': offset.top + 60,
				'left': offset.left
			}).show();
		}
		
		$("#signin-form #username").focus();
		
	}
	else if ($("#signin-form").css("display") == "block") {
		
		$("#signin-form").hide();
		$("#signin-bar a#signin").find("span").html("&#x25bc;");
			
	}
}

var showWebmailSigninBox = function(){
	if ($("#webmailSignin-form").css("display") == "none") {
		
		if($("#signin-bar a#signin").length > 0) {
			$("#signin-form")[0].reset();
			$("#signin-form").hide();
			$("#signin-bar a#signin").find("span").html("&#x25bc;");
		}
		
		var $signinBlock = $("#signin-bar a");
		var offset = $signinBlock.offset();
		var $form = $("#webmailSignin-form");

		$("#signin-bar a.webmailSignin").find("span").html("&#x25b2;");
		
		$form[0].reset();
		
		$form.css({
				'top': offset.top + 60,
				'left': offset.left -50
		}).show();
			
		$("#webmailSignin-form #emailAddress").focus();
		
	}
	else if ($("#webmailSignin-form").css("display") == "block") {
		
		$("#webmailSignin-form").hide();
		$("#signin-bar a.webmailSignin").find("span").html("&#x25bc;");
			
	}		
}

var googleAnalyticsTrackEvent = function(category,action,label) {
	if(typeof _gaq != 'undefined' )
		_gaq.push(['_trackEvent', category, action, label]);
}
	
$(function(){


	$("#site-menu li").hover(
		function(){
			if (!$(this).hasClass("current")) {
				if ($("#site-menu li.current")[0]) {
					$(this).removeClass("hover-rest");
					$(this).addClass("hover");
				}
				else {
					$(this).addClass("hover active");
					$("#site-menu li:not('.active')").addClass("hover-rest");
				}
			}
		},
		function(){
			if (!$(this).hasClass("current")) {
				if ($("#site-menu li.current")[0]) {
					$(this).removeClass("hover");
					$(this).addClass("hover-rest");
				}
				else {
					$("#site-menu li:not('.active')").removeClass("hover-rest");
					$(this).removeClass("hover active");
				}
			}
		}
	);
	
	
	var signinValidator = $("#signin-form").validate({
		rules: {
			username: {
				required: true
			},
			password: {
				required: true
			},
			signinKey: {
				required: true
			}
		},
		messages: {
			username: {
				required: 'Username is required'			
			},
			password: {
				required: 'Password is required'	
			},
			signinKey: {
				required: 'Key is required'	
			}			
		},
		errorPlacement: function(error, element){
			error.css({'color':'#a00', 'font-size':'10px'});
			error.insertAfter(element);
		},
		submitHandler: function (form) {
			
			var currentHost = window.location.host;
			
			$(form).ajaxSubmit({
				url: "https://" + currentHost + "/index.cfm?event=remote.general.processSignin",
				beforeSubmit: function (formData, jqForm, options) {
					
					$('#signin-dialog div.content').html('<div class="signinMsg"><img src="/img/loading.gif" /> Signing in...please wait...</div>');
					$.blockUI({
						forceIframe: true,
						message: $('#signin-dialog'),
						css: {
							border:  "0px",
							background: "none",
							padding: "0",
							width: "100%",
							left: "0px"
						},
						fadeIn: 0
					});
				    return true; 
				},
				success: function (response, status) {
					if (response.status == true)
					{
						window.location = "https://" + currentHost + response.redirectionurl;
					}
					else
					{	
						$("#signin-dialog div.content").html('<br/><div>'+response.message+'</div>'
							+ '<a href="#" class="close" onclick="$.unblockUI();$(\'#signin-form #username\').focus();">Close</a>');
							
						$('div.blockUIDialog a.close').focus();

						if(response.failedlogintries > 5) {
							$.ajax({ url: "/?event=remote.general.regenerateCaptcha"
								, type: "GET"
								, data: "type=signin"
								, async: false
								, cache: false
								, dataType: "json"
								, success: function (result) {
										var captchaImg = result +"?"+Math.floor(Math.random()*999);
										var captchaHTML = 
											'<label>Enter the following key: </label>'+
											'<div id="signinKeyBlock">'+
											'<a href="#" id="reloadSigninKey" title="Click to reload image"><img src="'+ captchaImg +'" id="signinKeyImg" width="190" height="50" border="0"></a>' +
											'<input type="text" class="textbox" name="signinKey" id="signinKey" value="" maxlength="6" autocomplete="off" />'
											'<div id="signupKeyError"></div></div>';
										$("div#signin-wrapper ul li.captcha").html(captchaHTML);
										$("div#signin-wrapper ul li.captcha").show();
								}
							});
						}
					}
				},
				dataType: "json"
			});
		}
	});
	
	
	$("#signin-bar a#signin").click(function(){
		if ($("#signin-form").css("display") == "none") {
			if (window.location.protocol != "https:") {
				window.location = "https://" + window.location.host + window.location.pathname + "#signin";
			} else {
				showSigninBox();
			}
		} else {
			showSigninBox();
		}
	});
	
	$("#signin-bar a.webmailSignin").click(function(){
		if ($("#webmailSignin-form").css("display") == "none") {
			if (window.location.protocol != "https:") {
				window.location = "https://" + window.location.host + window.location.pathname + "#webmailSignin";
			} else {
				showWebmailSigninBox();
			}
		} else {
			showWebmailSigninBox();
		}		
	});
	
	var webmailSigninValidator = $("#webmailSignin-form").validate({
		rules: {
			emailAddress: {
				required: true
			},
			password: {
				required: true
			}
		},
		messages: {
			emailAddress: {
				required: 'Email is required'			
			},
			password: {
				required: 'Password is required'	
			}		
		},
		errorPlacement: function(error, element){
			error.css({'color':'#a00', 'font-size':'10px'});
			error.insertAfter(element);
		},
		submitHandler: function (form) {
			
			$('#signin-dialog div.content').html('<div class="signinMsg"><img src="/img/loading.gif" /> Signing in...please wait...</div>');
			$.blockUI({
						forceIframe: true,
						message: $('#signin-dialog'),
						css: {
							border:  "0px",
							background: "none",
							padding: "0",
							width: "100%",
							left: "0px"
						},
						fadeIn: 0
			});
			form.submit();
					
		}
	});
	
	
	$("#signin-submit,#webmailSignin-submit").hover(
		function(){
			$(this).attr("src", "/img/signin_over.png");	
		},
		function(){
			$(this).attr("src", "/img/signin.png");	
		}
	);
	
	$("#signin-submit2,#webmailSignin-submit2").hover(
		function(){
			$(this).css({
				backgroundImage: "url('/img/blue_btn_over.png')",
				paddingBottom: "10px"
			});	
		},
		function(){
			$(this).css({
				backgroundImage: "url('/img/blue_btn.png')",
				paddingBottom: "8px"
			});	
		}
	);
	
	$("#signin-form").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $('#signin-form').submit();
            return false;
        } else {
            return true;
        }
    });
	
	$("#webmailSignin-form").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $('#webmailSignin-form').submit();
            return false;
        } else {
            return true;
        }
    });
	
	
	$("a#reloadSigninKey").live("click", function() {
      	$.ajax({ url: "/?event=remote.general.regenerateCaptcha"
			, type: "GET"
			, data: "type=signin"
			, async: false
			, cache: false
			, dataType: "json"
			, success: function (result) {
					$("#signinKeyImg").attr("src",result+"?"+Math.floor(Math.random()*999));
			}
		});
    });	
	
	var goToByScroll = function(id){
		$('html,body').animate({
            scrollTop: $("#"+id).offset().top},
            'slow');
    }
	
});

$(window).load(function(){
	var windowHash = window.location.hash;
	
	if(windowHash == "#signin") {
		showSigninBox();
	} else if (windowHash == "#webmailSignin") {
		showWebmailSigninBox();
	}
})

function sessionExpires(){
	if(self!=top){
		top.location = "https://" + window.location.host + "/sign-in";
	}
}

