/***************************/
//@Author: Adrian "yEnS" Mato Gondelle
//@website: www.yensdesign.com
//@email: yensamg@gmail.com
//@license: Feel free to use it, but keep this credits please!					
/***************************/

var popupCache = [];

function ehoAction()
{
	$.get('/html/eho.html', {}, function(html) { 
		initPopup('eho', html);
	});
	return false;
}

function contactAction() {
	$.get('/html/contact.php', {}, function(html) { 
		initPopup('contact', html);
		
		var contactValidator = $("#contactForm").validate({ 
			rules: {
				keystring: {
					required: true,
 					remote: "/ajax/usercheck.php"
				}
			}, messages: {
				visitorname: "Enter your name.", 
				keystring: {
					required: "Please enter a verification code.",
					remote: "Please enter the correct code."
				}
			},
			submitHandler: function(form) {
				$(form).ajaxSubmit(function(data) {
					if (data == 'sent') {
						$("#pop-up-contact div.pop-up-content").html('<h3>Your comments have been sent to the manager.</h3>');
						setTimeout(function() {
							disablePopup('pop-up-contact');
						}, 3000);
					}
				});
			}
		});
		
		$("#contact-submit").click(function() {
			$("#contactForm").submit();
			return false;
		});
		$("#contactForm input[name=commid]").val(commInfo['commid']);
		$("#contactForm input[name=commtype]").val(commInfo['commtype']);
	});
	return false;
}

function couponAction(couponID) {
	
	var getID = (couponID) ? couponID : '';
	
	$.get('/html/coupon.php', {comm_id: commInfo['commid'], coupon_id: getID, comm_type: commInfo['commtype']}, function(html) { 
		initPopup('coupon', html);
		
		var couponValidator = $("#couponForm").validate({ 
			rules: {
				keystring: {
					required: true,
 					remote: "/ajax/usercheck.php"
				},
				visitorphone: {
					required: function(element) {
						return $("input[name=visitormail]").val() == "";	
					}
				},
				visitormail: {
					required: function(element) {
						return $("input[name=visitorphone]").val() == "";	
					}	
				}
			},
			messages: {
				keystring: {
					required: "Please enter a verification code.",
					remote: "Please enter the correct code."
				},
				visitorphone: {
					required: "Please enter your email address or phone number."
				},
				visitormail: {
					required: "Please enter your email address or phone number."
				}
			},
			submitHandler: function(form) {
				$(form).ajaxSubmit(function(data) {
					if (data == 'sent') {
						$("#pop-up-coupon div.pop-up-content").html('<h3>Your coupon has been sent to you.</h3>');	
					} else {
						alert('There was a problem sending your coupon. Please try again later.');	
					}
				});
			}
		});
		
		$("#coupon-submit").click(function() {
			$("#couponForm").submit();
			return false;
		});
		
		$("#couponForm input[name=commid]").val(commInfo['commid']);
		$("#couponForm input[name=couponid]").val(couponID);
		$("#couponForm input[name=commtype]").val(commInfo['commtype']);
	});
	return false;
}


function disclaimerAction()
{
	$.get('/html/disclaimer.html', {}, function(html) { 
		initPopup('disclaimer', html);
	});
	return false;
}

function registrationWizardAction()
{
	$.get('/html/wizard-wrapper.html', {}, function(html) { 
		$(document).find('#popupBox').append(html);
		centerPopup("pop-up-wizard");
		loadPopup("pop-up-wizard");
		
		$("#discClose").click(function() {
			disablePopup("pop-up-wizard");
		});
	});
	return false;
}

function aptstoreImageAction(image, alt_text)
{
	$.get('/html/aptstorepopup.php', {'image': image, 'alt_text': alt_text}, function(html) { 
		$(document).find('#popupBox').append(html);
		centerPopup("pop-up-disclaimer");
		loadPopup("pop-up-disclaimer");
		
		$("#discClose").click(function() {
			disablePopup("pop-up-disclaimer");
		});
	});
	return false;
}

function aptstorePopupAction(url, size)
{
	$.get('/html/aptstorepopup-wrapper.php', {'url': url, 'size': size}, function(html) { 
		$(document).find('#popupBox').append(html);
		centerPopup("pop-up-wrapper");
		loadPopup("pop-up-wrapper");
		
		$("#discClose").click(function() {
			disablePopup("pop-up-wrapper");
		});
	});
	return false;
}

function enlargeFloorplanAction(fpId) {
	$.get('/html/floorplanpopup.php', {id: fpId}, function(html) {
		initPopup('fp', html, false);
		
		$("li.flare-fp3d a").click(function() {
			hdPopup('fp3d', false);
			return false;
		});
	});
}

function intdecAction(fpId)
{
	$.get('/html/intdecpopup.php', {id: fpId}, function(html) {
		initPopup('fpintdec', html, false);
	});
}

function loginButtonAction() {
	$.get('/html/login.html', {}, function(html) {
		initPopup('login-form', html, false);
		
		$("#loginToRegister").click(function(){
			disablePopup("login-form", "backgroundPopup");
			registerButtonAction();
		});
		
		$('div.pass-forgot').hide();
		$('#forgot-username-password-toggle').click(function() {
			$('div.pass-forgot').slideToggle(400);
			return false;
		});

	    // validate signup form on keyup and submit 
    var validator = $("#loginform").validate({ 
        rules: { 
            email: { 
                required: true, 
                remote: "/ajax/loginemailcheck.php" 
            }, 
            pass: "cpass"
            
        },
        onkeyup: false,
        messages: { 
            email: { 
                required: "Enter your e-mail", 
                remote: jQuery.format("Email Address does not exist.") 
            }, 
            pass: { 
                required: "Enter your password.", 
                rangelength: jQuery.format("Enter at least {0} characters"),
				cpass: 'wrong password'
            },
            terms: " " 
        },
   		success: function(label) {
			// set &nbsp; as text for IE
			label.html("&nbsp;").addClass("checked");
		}

        });
        
    var forgotpassvalidator = $("#forgotpassform").validate({
    	rules: {
    		forgotpass_email: {
    			required: true,
    			remote: "/ajax/loginemailcheck.php"
    		},
    		keystring: {
    			required: true,
    			remote: "/ajax/loginemailcheck.php"
    		}
    	},
    	onkeyup: false,
    	messages: {
    		forgotpass_email: {
    			required: "Please enter your e-mail address.",
    			remote: jQuery.format("This e-mail address is not registered.")
    		},
            keystring: {
            	required: "Please enter a verification code.",
            	remote: jQuery.format("That is not the correct verification code.")
    		}
    	},
   	success: function(label) {
			// set &nbsp; as text for IE
			label.html("&nbsp;").addClass("checked");
	},
	submitHandler: function(form) {
		var email = $("#forgotpass_email").val();
		$.post('/ajax/aptcart/forgotpass.php', {forgotpass_email: email}, function(data) {
			if(data == 'true')
			{
				$("#forgotpass-row").children(".left").html("<h4>New Password Sent!</h4>");
				$("#forgotpass-row").children(".right").html("A new temporary password has been sent to your email address.");
			}
			else
			{
				alert("ERROR: Could not create a new password.");
			}
		});
	}
		});
	});
	return false;
}

function registerButtonAction() {
	$.get('/html/registration.html', {}, function(html) {
		initPopup('sign-up-form', html, false);
		
		$('#usernameLoading').hide();
		$('#emailLoading').hide();
		$("#registerToLogin").click(function(){
			disablePopup("sign-up-form", "registerBackgroundPopup")
			loginButtonAction();
		});

    // validate signup form on keyup and submit 
    var validator = $("#registerform").validate({ 
        rules: { 
            firstName: "required", 
            lastName: "required", 
            register_user: { 
                required: true, 
                minlength: 2, 
                remote: "/ajax/usercheck.php" 
            }, 
            register_pass: { 
                required: true, 
                minlength: 5 
            }, 
            register_passagain: { 
                required: true, 
                minlength: 5, 
                equalTo: "#register_pass" 
            }, 
            updatefreq: "required",
            email: { 
                //required: true, 
                email: true, 
                remote: "/ajax/usercheck.php" 
            }, 
            phone: {
            	//required: false,
            	minlength: 7
            },
            keystring: {
            	required: true,
            	remote: "/ajax/usercheck.php"
            },
            terms: "required" 
        }, 
        onkeyup: false,
        messages: { 
            firstName: "Enter your first name.", 
            lastName: "Enter your last name.", 
            register_user: { 
                required: "Enter a username", 
                minlength: jQuery.format("Enter at least {0} characters"), 
                remote: jQuery.format("Username is already in use") 
            }, 
            password: { 
                required: "Provide a password", 
                rangelength: jQuery.format("Enter at least {0} characters") 
            }, 
            phone: {
            	minlength: "Please enter a valid phone number."
            },
            keystring: {
            	required: "Please enter a verification code.",
            	remote: "Please enter the correct code."
            },
            register_passagain: { 
                required: "Repeat your password", 
                minlength: jQuery.format("Enter at least {0} characters"), 
                equalTo: "Enter the same password as above" 
            }, 
            updatefreq: "Please choose how often you want to receive email updates",
            email: { 
                required: "Please enter a valid email address", 
                minlength: "Please enter a valid email address", 
                remote: jQuery.format("Email Address is already in use") 
            }, 
            terms: " " 
        },
   		success: function(label) {
			// set &nbsp; as text for IE
			label.html("&nbsp;").addClass("checked");
		}

        });

		$("input").change(function() {
	        switch($("input[@name='prefcontact']:checked").val()) {
	        	case 'email':
					$("#email").addClass('required email');
	        		$("#phone").removeClass('required phone');
	        	break;
	        	case 'phone':
	        		$("#phone").addClass('required phone');
	        		$("#email").removeClass('required email');
	        	break;
	        	case 'both':
					$("#email").addClass('required email');
	        		$("#phone").addClass('required phone');
	        	break;
	        }
    
		});
	});
	return false;
}

function centerPopup(id, height)
{
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var popupWidth = $("#" + id).width();

	if (height == 'dynamic') {
		var windowHeight = document.documentElement.clientHeight;  
		var popupHeight = $("#popupBox").height();
		var top = scrollY()+windowHeight/2-popupHeight/2;
	} else {
		var windowHeight = document.documentElement.clientHeight;  
		var top = scrollY() + 20;
	}
		
	//centering
	$("#" + id).css({
		"position": "absolute",
		"top": top,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
}

function initPopup(name, html, dynamic) {
	var id = "pop-up-" + name;
	$(document).find('#popupBox').html(html);
	if (dynamic)
		centerPopup(id, "dynamic");
	else centerPopup(id);
	loadPopup(id);
	
	$(document).find('body').append('<div id="backgroundPopup"></div>');
	$("#backgroundPopup").show().animate({opacity: "0.7"}, 1000);
	
	$("#popupBox div.close-button,#backgroundPopup").click(function() {
		disablePopup(id);
		return false;
	});
}

function loadPopup() {
	if ($("div.pop-up:visible").length == 0) {
		$("#backgroundPopup").css('opacity', 0.7);	
		$("div.pop-up").fadeIn("slow", function() { });
	}
}

function disablePopup(id) {
	if ($("#" + id + ":visible").length == 1) {
		$("#backgroundPopup").fadeOut(500, function() { $(this).remove(); });
		$("#" + id).fadeOut(750, function() { $("#popupBox").empty(); });
	}
	return false;
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){
	$(".registrationWizard").click(registrationWizardAction);
	$("#loginButton").click(loginButtonAction);
	$("#contactButton").click(contactAction);
	$("#couponButton").click(function() {couponAction('')});
	$("#footerLogin").click(loginButtonAction);
	$("#registerButton").click(registerButtonAction);
	$("#inpageRegister").click(registerButtonAction);  //aptcart page, 'Sign Up Now!' near top of page
	$("#inpageRegButton").click(registerButtonAction); //aptcart page, 'Sign Me Up!' button on right side
	$("#footerRegister").click(registerButtonAction);
	$("#eho").click(ehoAction);
	$("#disclaimer").click(disclaimerAction);

	$("a.get_coupon_button").click(function() {
		var parts = this.id.split('_');
		couponAction(parts[1]);
	});

//	$("#promoButton").click(promoButtonAction);
	
	$.validator.addMethod("cpass", function(value, element) {
		var outerResult;
		$.ajax({type: "GET",
			url: "/ajax/loginemailcheck.php",
			async: false,
			data: {email: $('#loginform input[name=email]').val(), pass: value},
			success: function(result) {
				outerResult = result;	
			}
		});
		return (outerResult == "true");
	}, "valid");
});

