/************************************************************************ 
 * Copyright 16th Street Ventures, LLC
 * ============================================= 
 *  Last edited by: $$Author: mqumhieh $$ 
 *              on: $$Date: 2012-02-09 14:00:34 $$ 
 *        Filename: $$RCSfile: venueHeader.js,v $$ 
 *        Revision: $$Revision: 1.42 $$ 
 * 
 */

$(function(){
	/* Check availability validation
	----------------------------------------------------------------------------------------------------------------- */
	$("#find-table").submit(function(){
	    if($(this.d).val() != ""){
	    	// get the current date and validate it with the given date, where the given date should be less than current 
	    	// date about 30 minutes 
	    	var today = new Date();
	    	var givenDate = new Date();
	    	// get time
		    var time = getTimeObj($("#find-table .ca-time").val());
	        $(this.h).val(time.hour);
	        $(this.m).val(time.minute);
	    	givenDate.setFullYear($(this.d).val().substr(6), $(this.d).val().substr(3, 2) - 1, $(this.d).val().substr(0, 2));
	    	givenDate.setHours($(this.h).val(), $(this.m).val() - 30, 0, 0);
	    	if(givenDate < today){
	    		alert("You can only make reservations at least 30 minutes in advance through ihjez.com");
	    		return false;
	    	}
	    }
	}); 
	
	/* Signup && Login container events && quick search
	----------------------------------------------------------------------------------------------------------------- */
	// Remove invalid box class for inputs if it exists
	$("#sign-up-container .invalid-box, #login-container .invalid-box").live('focus', function(){
		$(this).removeClass("invalid-box");
	});

	// animation for hidden-tittle and animate-title
	$(".animate-title").live('click', function(){
		if (!$(this).next("input[type=text]").is(":disabled")){
			$(this).stop(true, true).fadeOut(300);
			$(this).next("input").addClass("active-box").focus();
		}
	});
	// animate title events (input clicked)
	$("#activate-code-container input[type=text], #login-container input[name=e], #login-container input[name=pass]," +
			"#quick-search-container input[type=text], #find-table input[type=text], .animate-target").live('focus', function(){
		if(!$(this).hasClass("active-box")){
			$(this).prev(".animate-title").stop(true, true).fadeOut(300);
			$(this).addClass("active-box");
		}	
	});
	// animate title events (input blur)
	$("#activate-code-container input[type=text], #login-container input[name=e], #login-container input[name=pass]," +
			"#quick-search-container input[type=text], #find-table input[type=text], .animate-target").live('blur', function(){
		if($.trim($(this).val()).length == 0){
			$(this).prev(".animate-title").fadeIn(300);
		}
		$(this).removeClass("active-box");
	});
	
	/* quick search bar
	----------------------------------------------------------------------------------------------------------------- */
	// Show datepicker
	$("#find-table input[name=d], #availability-container input[name=d]").datepicker({ 
		showAnim: 'fadeIn',
		dateFormat: 'dd/mm/yy',
		minDate: 'dd/mm/yy',
		maxDate: '+6m',
		onSelect: function(dateText, inst) {
			$(this).prev(".animate-title").hide();
		}
		});
	
	$("#search-criteria").change(function(){
		$(this).siblings("input[type=hidden]").val("all");
	});
	
	/* Signup contianer
	----------------------------------------------------------------------------------------------------------------- */
	// Show signup container
	$('#show-sign-up').click(function(){
		$("#loading-div").fadeIn(500 ,function(){
			$("#sign-up-wrapper").show();
		});
	});
	// close signup container
	$('#close-sign-up-container, #close-confirm-sign-up').click(function(){
		closeSignup();
	});
	
	function closeSignup(){
		$("#sign-up-wrapper").hide();
		$("#loading-div").fadeOut(500);
		$("#sign-up-body").css({
			left:"0px",
			width: "554px"
				});
		$("#header-2, #header-3").hide();
		$("#header-1").show();
		$("#create-account-container").hide();
		$("#activate-account-container").hide();
		$("#confirmation-container").hide();
		$("#sign-up-body .error").hide();
		// clearing forms
		$("#sign-up-body .invalid-box").removeClass("invalid-box");
		$("#sign-up-body input[type=text]").val("");
		$("#sign-up-body input[type=password]").val("");
		$("#sign-up-body .animate-title").show();
		$("#invalid-sign-up").hide();
	}
	
	// continue to login
	$("#continue-to-login").click(function(){
		$.ajax({ url:  contextPath +  "/auth/login",
		     dataType: 'json',
		     data: {email:  $("#validate-account input[name=e]").val(), password: $("#validate-account input[name=pass]").val(),
					rememberMe: false},
			 success: function(){
					window.location.reload();
			}
		});
	});
	
	// validate email in signup process
	$("#validate-account").submit(function(){
		//clear invalid boxes
		$("#validate-account .invalid-box").removeClass("invalid-box");
		// get parameters
		var email = $(this.e).val(),
			name= $(this.n).val(),
			password = $(this.pass).val(),
			confPassword = $(this.confPass).val(),
			validate = false;
		// validate if there is empty text
		$("#validate-account input[type=text], #validate-account input[type=password]").each(function(){
			if($.trim($(this).val()) == ""){
				$(this).addClass("invalid-box");
				$("#validate-account-container .error").html("<div>- Fill all required information</div>").slideDown(500);
				validate = true;
			}
		});
		if(validate){
			return false;
		}
		// validate email address
		if(!isValidEmailAddress(email)){
			$("#validate-account input[name=e]").addClass("invalid-box");
			$("#validate-account-container .error").html("<div>- Invalid email address</div>").slideDown(500);
			return false;
		}
		// validate password
		if(password.length < 6){
			$("#validate-account input[name=p]").addClass("invalid-box");
			$("#validate-account-container .error").html("<div>- password must be more than 6 charachteres</div>").slideDown(500);
			return false;
		}
		// validate password confirmation
		if(password != confPassword){
			$("#validate-account input[name=pass]").addClass("invalid-box");
			$("#validate-account input[name=confPass]").addClass("invalid-box");
			$("#validate-account-container .error").html("<div>- password and password confirmation not matches</div>").slideDown(500);
			return false;
		}
		
		// show loading image
		$("#ihjez-loading-validate").css('display','inline');
		// send request
		$.ajax({ 
			url: contextPath + "/user/user_exists_for_email",
		    dataType: 'json',
		    data: {e: email},
		    success: function(data){
				// check the return data
		    	if (data.success) {
					if (data.result == 0) { 
						// email valid for signup
						$("#validate-account-container .error").hide();
						$("#sign-up-body").css("width","1108px");
						$("#create-account-container").show();
						$("#sign-up-body").animate({
							left : "-=554px"
						});
					} else if (data.result == 1){
						$("#validate-account-container .error").html("<div>- email address is already used</div>").slideDown(500);
						$("#validate-account input[name=e]").addClass("invalid-box");
					} else if (data.result == 2) {
						$("#validate-account-container .error").html("<div>- email address is alreay used, but inactive! ! <a id=\"resend-activation-link\"><input type=\"hidden\" name=\"email\" value=\""+email+"\" />resend activation link</a></div>").slideDown(500);
						$("#validate-account input[name=e]").addClass("invalid-box");
					} else {
						$("#validate-account-container .error").html("<div>- its seems this email has been used as guest " +
								"user, to get full account for this email please check the email that sent to you after first" +
								" guest registration! <a id=\"resend-registration\"><input type=\"hidden\" name=\"email\" value=\""+email+"\" />resend registration email</a></div>").slideDown(500);
						$("#validate-account input[name=e]").addClass("invalid-box");
					}
				} else {
					$("#validate-account-container .error").html("<div>- " + data.result + "</div>").slideDown(500);
				}
		    	// hide loading image
		    	$("#ihjez-loading-validate").hide();
			}
		});
		return false;
	});
	
	// back to validate container
	$("#back-to-validate-button").click(function(){
		$("#create-account-container .error").hide();
		$("#validate-account-container").show();
		$("#sign-up-body").animate({
			left : "+=554px"
		}, function(){
			$("#create-account-container").hide();
			$("#sign-up-body").css("width","554px");
		});
		return false;
	});
	
	// create account
	$("#create-account").submit(function(){
		// reset account creation form
		$("#create-account .invalid-box").removeClass("invalid-box");
		// initialize variables
		var day= $(this.d).val(),
			month = $(this.m).val(),
			year = $(this.y).val(),
			phone = $(this.p).val(),
			gender = $("#create-account input[name=g]:checked").val(),
			name = $("#validate-account input[name=n]").val(),
			email = $("#validate-account input[name=e]").val(),
			password = $("#validate-account input[name=pass]").val(),
			errorList = "";
		// validate date of birth
		if (day == 0 || month == 0 || year == 0){
			errorList = "<div>- Select your date of birth</div>";
		}
		// validate gender
		if (gender == null || gender == "") {
			errorList = "<div>- Select your gender</div>";
		}
		// validate phone number if it entered
		if (!isValidPhoneNumber(phone) || phone.length < 6) {
			$("#create-account input[name=p]").addClass("invalid-box");
			errorList += "<div>- invalid phone number</div>";
		}
		if (errorList.length > 0){
			$("#create-account-container .error").html(errorList).slideDown(500);
			return false;
		}
		var data = {n: name, c: 'JOR', ci: 'AMMAN', e: email, pc: "JOR", p: phone, s: true, y: year, m: month, d: day,
				g: gender, pass: password};
		// show loading image
		$("#ihjez-loading-create").css('display','inline');
		$.ajax({ 
			url: contextPath + "/user/add",
		    dataType: 'json',
		    data: data,
		    success: function(data){
					// check the return data
			    	if (data.success == true && data.result == true) {
							// user successfully added
							$("#activate-code-container .send-to").html(email);
							$("#create-account-container .error").hide();
							$("#sign-up-body").css("width","1662px");
							$("#header-1").hide();
							$("#header-2").show();
							$("#activate-account-container").show();
							$("#sign-up-body").animate({
								left : "-=554px"
							});
							
					} else if (data.error_code == 1){
						$("#create-account-container .error").html("<div>- email address is already used</div>").slideDown(500);
					} else if (data.error_code == 6){
						$("#create-account-container .error").html("<div>- invalid phone number</div>").slideDown(500);
						$("#create-account input[name=p]").addClass("invalid-box");
					} else if (data.error_code != null){
						$("#create-account-container .error").html("<div>- " + data.message + "</div>").slideDown(500);
					} else {
						$("#create-account-container .error").html("<div>- invalid operation</div>").slideDown(500);
					}
			    	// hide loading image
			    	$("#ihjez-loading-create").hide();
			}
		});
		return false;
		
	});
	
	// activate ihjez account
	$("#activate-account").submit(function(){
		var code = $(this.c).val();
			email = $("#validate-account input[name=e]").val();
		// reset activation code box
		$(this.c).removeClass("invalid-box");
		$(this.c).blur();
		// validate activation code
		if(code == "" || code.length != 10 || !isValidEmailAddress(email)){
			$(this.c).addClass("invalid-box");
			return false;
		}
		// view loading img
		$("#ihjez-loading-confirme-code").css('display','inline');
		// prepare request data
		$.ajax({ url: contextPath + "/user/confirmemail_call",
		     dataType: 'json',
		     data: {e: email, c: code},
		     success: function(data){
		    	 if (data.success && data.result) {
	    		 	 // if valid move to account creation container
	    			 $("#header-2").hide();
	    			 $("#header-3").show();
	    			 $("#sign-up-body").css("width","2216px");
	    			 $("#confirmation-container").show();
	    			 $("#sign-up-body").animate({
	    				 left : "-=554px"
	    			 });
	    			 // if not valid code
		    	 } else {
		    		 $("#activate-account input[name=c]").addClass("invalid-box");
		    	 }
				$("#ihjez-loading-confirme-code").hide();
				return false;
			}
		});
		return false;
	});
	
	$("#resend-registration").live("click", function(){
		var email = $(this).children("input[name=email]").val();
		if(!isValidEmailAddress(email)){
			alert("Try again please");
			return false;
		}
		$("#ihjez-loading-validate").css('display','inline');
		$.ajax({ url: contextPath + "/relay/send_mail",
		     dataType: 'json',
		     data: {e: email, ut: "GUEST_USER"},
		     success: function(data){
		    	 $("#ihjez-loading-validate").hide();
		    	 if (data.success && data.result) {
		    		 alert("an email sent to " + email + " containes the link to make full registration");
		    		 closeSignup();
		    	 } else {
		    		 alert("Invalid operation");
		    	 }
			}
		});
		return false;
	});
	
	$("#resend-activation-link").live("click", function(){
		var email = $(this).children("input[name=email]").val();
		if(!isValidEmailAddress(email)){
			alert("Try again please");
			return false;
		}
		$("#ihjez-loading-validate").css('display','inline');
		$.ajax({ url: contextPath + "/relay/send_mail",
		     dataType: 'json',
		     data: {e: email, ut: "NOT_ACTIVE_USER"},
		     success: function(data){
		    	 $("#ihjez-loading-validate").hide();
		    	 if (data.success && data.result) {
		    		 alert("an email sent to " + email + " containes the activation link");
		    		 closeSignup();
		    	 } else {
		    		 alert("Invalid operation");
		    	 }
			}
		});
		return false;
	});
	
	
	
	/* Login && forgot password contianer
	----------------------------------------------------------------------------------------------------------------- */
	// Show login container
	$('#show-login').click(function(){
		$("#loading-div").fadeIn(500 ,function(){
			//Login events, show / hide email, and password text
			if($.trim($("#login input[name=e]").val()).length == 0){
				$("#login input[name=e]").prev(".animate-title").show();
			}else{
				$("#login input[name=e]").addClass("active-box");
			}
			if($.trim($("#login input[name=pass]").val()).length == 0){
				$("#login input[name=pass]").prev(".animate-title").show();
			}else{
				$("#login input[name=pass]").addClass("active-box");
			}
			$("#login-wrapper").show();
		});
	});
	// close login container
	$("#close-login-container").click(function(){
		$("#login-wrapper").hide();
		$("#loading-div").fadeOut(500);
		// reset login container layout
		// check if the layout for forgot password
		if($("#login-container .body-slider").css("left") != "0px"){
			$("#forgot-password-title").hide()
			$("#login-title").show()
			$("#back-to-login").hide();
			$("#show-forgot-password").show();
			$("#forgot-password").hide();
			$("#login-container .body-slider").css({
				left: "0px",
				width: "316px"});
		}
		$("#login-container input.active-box").removeClass("active-box");
		$("#login-container .error").hide();
		$("#login-container .success").hide();
	});
	
	//show forgot password body
	$("#show-forgot-password").click(function(){
		if($("#login-container .body-slider").css("left") != "0px"){
			return;
		}
		// set the new layout for the forgot password
		$(this).hide();
		$("#back-to-login").show();
		$("#login-title").hide();
		$("#forgot-password-title").show();
		$("#login-container .body-slider").css("width","632px");
		$("#forgot-password").show();
		$("#login-container .body-slider").animate({
			left: "-316px"
		});
	});
	// back to login
	$("#back-to-login").click(function(){
		// set the new layout for the forgot password
		$(this).hide();
		$("#show-forgot-password").show();
		$("#forgot-password-title").hide();
		$("#login-title").show();
		$("#login-container .body-slider").animate({
			left: "0px"
		}, function(){
			$("#forgot-password").hide();
			$(this).css("width","316px");
		});
	});
	// not ihjez memebr
	$("#not-ihjez-member").click(function(){
		$("#login-wrapper").hide();
		$("#sign-up-wrapper").show();
	});
	
	// logout process
	$("#logout, #change-user").click(function(){
		$.ajax({ url:  contextPath + "/auth/logout",
		     dataType: 'json',
		     success: function(data){
				window.location =  contextPath + "/";
			}
		});
	});
	
	// login process
	$("#login, #validate-guest-login").submit(function(){
		// get parameters
		var emailAddress = $.trim($(this.e).val()),
		    password = $.trim($(this.pass).val()),
			rememberMe = $(this.rm).is(":checked"),
			parentId = $(this).attr("id");
		// validate parameters
		if(!isValidEmailAddress(emailAddress) || password.length < 6) {
			$("#" + parentId + " .error").html("invalid email address / password").slideDown(500);
			$(this.p).val("");
			return false;
		}
		// view loading img
		$("#" + parentId + " .ihjez-loading").css('display','inline');
		// prepare request data
		var requestData = "email=" + emailAddress + "&password=" + password + "&remember=" + rememberMe;
		$.ajax({ url:  contextPath +  "/auth/login",
		     dataType: 'json',
		     data: requestData,
		     success: function(data){
			    $("#" + parentId + " .ihjez-loading").hide();
				if(data.error_code == null) {
					window.location.reload();
				} else if (data.error_code == 2) {
					$("#" + parentId + " .error").html("your ihjez account is inactive ! <a href=\""+ contextPath +"/user/confirm_email?e"+ emailAddress +"\">activate now</a>").slideDown(500);
					$("#" + parentId + " input[name=pass]").val("");
					return false;
				} else {
					$("#" + parentId + " .error").html("invalid email address / password").slideDown(500);
					$("#" + parentId + " input[name=pass]").val("");
					return false;
				}  
			}
		});
		return false;
	});
	
	// forgot process
	$("#forgot-password").submit(function(){
		// get parameters
		var emailAddress = $.trim($(this.e).val());
		// validate parameters
		if(!isValidEmailAddress(emailAddress)) {
			$("#invalid-forgot-password").slideDown(500);
			return false;
		}
		// view loading img
		$("#ihjez-loading-forgot-password").css('display','inline');
		$.ajax({ url: contextPath + "/auth/reset_request",
		     dataType: 'json',
		     data: {e : emailAddress},
		     success: function(data){
			    $("#ihjez-loading-forgot-password").hide();
			    if(data.success == true && data.result == true) {
			    	$("#forgot-password input[name=e]").val("");
			    	$("#invalid-forgot-password").hide();
					$("#forgot-password .success").slideDown(500);
				} else {
					$("#forgot-password .success").hide();
					$("#invalid-forgot-password").slideDown(500);
				}
			}
		});
		return false;
	});
	
	/* account info dropdown events
	----------------------------------------------------------------------------------------------------------------- */
	$(document).click(function(e){
		// show ul info
		if($(e.target).hasClass("show-account-info") && $(e.target).parents("#header-right").length != 0   
				&& $("#header-tabs .nav-tabs-logged").is(":hidden")){
			$("#header-tabs .user-name").removeClass("user-name").addClass("user-name-selected");
			$("#header-tabs .nav-tabs-logged").show();
		} else if($("#header-tabs .nav-tabs-logged").is(":visible") && $(e.target).parents("ul.nav-tabs-logged").length == 0){
					// hide ul info
					$("#header-tabs .user-name-selected").removeClass("user-name-selected").addClass("user-name");
					$("#header-tabs .nav-tabs-logged").hide();
				}
	});
	
	/* Change location
	----------------------------------------------------------------------------------------------------------------- */
	$(document).click(function(e){
		// show location ul info
		if($(e.target).hasClass("show-location-info") && $(e.target).parents("#header-left").length != 0   
				&& $("#header-tabs .change-location").is(":hidden")){
			$("#header-tabs .location-info").removeClass("location-info").addClass("location-info-selected");
			$("#header-tabs .change-location").show();
		} else if($("#header-tabs .change-location").is(":visible") && $(e.target).parents("ul.change-location").length == 0){
					// hide location ul info
					$("#header-tabs .location-info-selected").removeClass("location-info-selected").addClass("location-info");
					$("#header-tabs .change-location").hide();
				}
	});
	
    // select location
	$("#header-tabs .change-location a").live("click", function(){
		$("#header-tabs .location-info-selected").removeClass("location-info-selected").addClass("location-info");
		$("#header-tabs .change-location").hide();
	});
	
});

