$(document).ready(function(){
	var modaldate;
    var _ignoreHashChange = false;
	
	$(window).resize(function(){
		if($("#register-dialog").dialog("isOpen") && ($(".ui-dialog").height() + 18) < $(window).height()){
			$("#register-dialog").dialog("option", "position", ["center", 18]);
		}
	});
	
	$("a[href*=verify\\.cgi]").click(function(event){
		if($(window).height() > 300 && $(window).width() > 300 && window.location.pathname.match(/verify\.cgi?state=sendpasswordreset/) == null){
			modaldate = new Date()
			$("body").append("<div id=\"passwordreset-dialog\"><p>Enter your email address or customer number to receive your lost credentials.</p><form method=\"get\" action=\"/cgi-bin/verify.cgi\"><div><label for=\"customerid\" class=\"block-label\">Account or email</label><br /><input type=\"text\" name=\"customerid\" title=\"Enter you account number or email address to reset your password\" /><br /><input type=\"hidden\" name=\"state\" value=\"sendpasswordreset\" /><input type=\"submit\" value=\"Reset password\" /></div></form></div>");
			$("#passwordreset-dialog").dialog({modal: true, dragable: false, resizable: false, width: 300, title: "Reset password", close: function(event, ui){
				$.ajax({url: "/cgi-bin/logger.cgi", async: false, cache: false, data: {"modal": $("#passwordreset-dialog").dialog("option", "title"), "time": (new Date().getTime() - modaldate.getTime())}});
				$("#passwordreset-dialog").remove();
			}});
			$(event.target).effect("transfer", {to: "#passwordreset-dialog", className: "ui-effects-transfer"}, 500);
			return false;
		}
	});

	$("a[href*=register\\.php]").click(function(event){
		if($(window).height() > 550 && $(window).width() > 550 && window.location.pathname.match(/register\.php/) == null && navigator.userAgent.match(/iPhone|iP(?:o|a)d|Android|MSIE\s*7.0/i) == null){
            		$.bbq.pushState({modal : true});
			$.ajax({data: "initialize=true&inewemail=" + $.trim($("#bnum").val()) + "&ipasswd=" + $.trim($("#bpwd").val()) +  $.trim($(this).attr("href").match(/\?.*/)).replace(/^\?/, "&"), success: function(data){
				modaldate = new Date();
				if(data != null && data.title && data.html){
					if($("#register-dialog").attr("id") == null){
						$("body").append("<div id=\"register-dialog\"></div>");
					}
					$("#register-dialog").html(data.html);
					$("#register-dialog").dialog({modal: true, draggable: false, resizable: false, width: 450, position: ["center", 18], title: data.title, beforeClose: function(event, ui){
                        if(event.keyCode == 27){
                            return confirm("If you proceed, you will lose any information you have entered on the current screen. Are you sure you want to close this screen?");
                        }
                    }, close: function(event, ui){
						$.ajax({url: "/cgi-bin/logger.cgi", async: false, cache: false, data: {"modal": $("#register-dialog").dialog("option", "title"), "time": (new Date().getTime() - modaldate.getTime())}});
						$("#register, #billing").validationEngine("hideAll");
						
						if($.trim($("#register-dialog").dialog("option", "title")).match(/enable\s*bid/i) != null){
							$.ajax({data: "status=true", success: function(data){
								modaldate = new Date();
								if(data != null && data.title && data.html){
									if($("#status-dialog").attr("id") == null){
										$("body").append("<div id=\"status-dialog\"></div>");
									}
									$("#status-dialog").html(data.html);
									$("#status-dialog").dialog({modal: true, resizable: false, width: 450, title: data.title, close: function(event, ui){
										$.ajax({url: "/cgi-bin/logger.cgi", async: false, cache: false, data: {"modal": $("#status-dialog").dialog("option", "title"), "time": (new Date().getTime() - modaldate.getTime())}});
										if($("#rform").is(":visible")){
											$("#rform").submit();
										}else{
											window.location = window.location.href.replace(/&hash=.+$/, "");
										}
									}});
								}else if($("#rform").is(":visible")){
									$("#rform").submit();
								}else{
									window.location = window.location.href.replace(/&hash=.+$/, "");
								}
							}});
						}else if($("#rform").is(":visible")){
							$("#rform").submit();
						}else{
							window.location = window.location.href.replace(/&hash=.+$/, "");
						}
					}
					});
					$(event.target).effect("transfer", {to: "#register-dialog", className: "ui-effects-transfer"}, 500);
					$(".ac-container").remove();
					$("#state").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "state"}});
					//$("#city").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "city"}});
					$("#country").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "country"}});
					$(".ac-container").css("position", "fixed");
					$("#register").validationEngine("hideAll");
					$("#passwd, #altpasswd, #passwd-toggle, label[for=passwd-toggle]").toggle();
					$("#passwd-toggle").change();
					$("#newemail").val((($.trim($("#bnum").val()).match(/^\d{2,5}|[\w!#$%&'*+\/=?^`{|}~-]+(?:\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i) != null) ? $.trim($("#bnum").val()) : $.trim($("#newemail").val())));
					$("#passwd").val((($.trim($("#bpwd").val()) != "" && $.trim($("#bpwd").val()).match(/password/i) == null) ? $.trim($("#bpwd").val()) : $.trim($("#passwd").val())));
					$("#passwd").keyup();
					$("#company, #title, #passwd").blur();
					$("#register #fname").focus();
					$(".parentFormregister, .parentFormbilling").css("postion", "fixed !important");
                    $(window).bind("hashchange", function(){
                        var state = $.bbq.getState("modal");
                        
                        if (state != "true" && _ignoreHashChange == false){
                            if (confirm("If you proceed, you will lose any information you have entered on the current screen.")){
                                $("#status-dialog").dialog("close");
                                $("#register-dialog").dialog("close");
                            }else{
                                $.bbq.pushState({modal : true});
                            }
                        }
                    });
				}
			}});
			return false;
		}else{
            window.location = $(this).attr("href");
        }
	});

	$("#register input[type=text], #register input[type=password]").live("blur", function(){
		if(($.trim($("#passwd").val()).match(/^[A-Za-z0-9]{5,50}$/i) != null || ($("#register-dialog").dialog("option", "title") == "Upgrade" && $.trim($("#passwd").val()).match(/^[A-Za-z0-9]{2,50}$/i) != null)) && $.trim($("#newemail").val()).match(/^[\w!#$%&'*+\/=?^`{|}~-]+(?:\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i) != null){
			$.ajax({data: $("#register input:visible, #register select:visible").serialize()});
		}
	});

	$("#billing input, #billing select").live("blur", function(){
		$.ajax({data:  $("#address, #city, #state, #country, #postalcode, #companycategory, #terms").serialize()});
	});

	$("input[name=use]").live("change", function(){
		$("#company, #title").blur();
	});

	$("#company, #title").live("focus", function(){
		if($("label[for=" + $("input[name=use]:checked").attr("id") + "]").text().match(/personal/i) != null && ($.trim($(this).val()) == "" || $.trim($(this).val()).match(/optional/i) != null)){
			$(this).css("color", "black");
			$(this).val("");
		}
	});

	$("#company, #title").live("blur", function(){
		if($("label[for=" + $("input[name=use]:checked").attr("id") + "]").text().match(/personal/i) != null && ($.trim($(this).val()) == "" || $.trim($(this).val()).match(/optional/i) != null)){
			$(this).removeClass("required");
			$(this).css("color", "gray");
			$(this).val("Optional");
		}else if($("label[for=" + $("input[name=use]:checked").attr("id") + "]").text().match(/personal/i) == null && $.trim($(this).val()).match(/optional/i) != null){
			$(this).css("color", "black");
			$(this).val("");
		}
	});

	$("#newemail").live("blur", function(){
		if($.trim($(this).val()).match(/^[\w!#$%&'*+\/=?^`{|}~-]+(?:\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i) != null){
			$.get("/ajax/lookup.php", {lookup: "email", search: $.trim($(this).val())}, function(data){
				if(data != null && data.result){
					$("#newemail").validationEngine("showPrompt", data.error, "error", "topRight", true);
				}else{
					$("#newemail").validationEngine("hide");
				}
			}, "json");
		}else{
			$("#newemail").validationEngine("hide");
		}
	});

	$("#ccpan").live("blur", function(){
		var cctype = "";

		if($.trim($(this).val()).match(/^4[0-9]{12}(?:[0-9]{3})?$/i) != null){
			cctype = "Visa";
		}else if($.trim($(this).val()).match(/^5[1-5][0-9]{14}$/i) != null){
			cctype = "Mastercard";
		}else if($.trim($(this).val()).match(/^6(?:011|5[0-9]{2})[0-9]{12}$/i) != null){
			cctype = "Discover";
		}else if ($.trim($(this).val()) != ""){
			cctype = "Invalid card";
		}

		if(cctype != ""){
			$("#ccpan").validationEngine("showPrompt", cctype, "load", "topRight", true);
			$(".ccpanformError").fadeTo(5000, 0.1, function(){
				$(".ccpanformError").remove();
			});
		}else{
			$("#ccpan").validationEngine("hide");
		}
	});

	$("#passwd-toggle").live("change", function(){
		if($(this).is(":checked")){
			$("#passwd").hide();
			$("#altpasswd").show();
		}else{
			$("#altpasswd").hide();
			$("#passwd").show();
		}
	});

	$("#passwd, #altpasswd").live("keyup", function(){
		if($.trim($(this).val()) == ""){
			$("#passwd, #altpasswd").validationEngine("hide");
		}
		else{
			var strength = 0;
			var text = "very weak";
			strength += ($(this).val().match(/[a-zA-Z0-9]/) ? ($.trim($(this).val()).length * 2) : 0);
			strength += ($(this).val().match(/[a-z]/) ? ($(this).val().match(/[a-z]+/g).length * 2) : 0);
			strength += ($(this).val().match(/[A-Z]/) ? ($(this).val().match(/[A-Z]+/g).length * 2) : 0);
			strength += ($(this).val().match(/\d/) ? ($(this).val().match(/\d+/g).length * 3) : 0);

			text = (strength > 10 ? "weak" : text);
			text = (strength > 20 ? "moderate" : text);
			text = (strength > 30 ? "strong" : text);
			text = (strength > 40 ? "very strong" : text);
			
			$(this).validationEngine("showPrompt", text, "load", "topRight", true);
		}
	});

	$("#passwd, #altpasswd").live("blur", function(){
		$("#passwd").val($.trim($(this).val()));
		$("#altpasswd").val($.trim($(this).val()));
		$(".passwdformError, .altpasswdformError").fadeTo(1500, 0.1, function(){
			$(".passwdformError, .altpasswdformError").remove();
		});
	});

	$("#breadcrumb-basic, #breadcrumb-advanced").live("click keypress", function(event){
		if(window.location.pathname.match(/register\.php/i) == null && (event.type.match(/click/i) || event.which == 32 || event.which == 13)){
			$.ajax({url: "/cgi-bin/logger.cgi", async: false, cache: false, data: {"modal": $("#register-dialog").dialog("option", "title"), "time": (new Date().getTime() - modaldate.getTime())}});
			modaldate = new Date();
			$.ajax({data: $(this).attr("href"), success: function(data){
				if(data != null && data.title && data.html){
					$("#register-dialog").dialog("option", "title", data.title);
					$("#register-dialog").html(data.html);
					$("#passwd, #altpasswd, #passwd-toggle, label[for=passwd-toggle]").toggle();
					$("#register-dialog #passwd-toggle").change();
					$("#register-dialog").find("input[name=use]").change();
					$(".ac-container").remove();
					$("#state").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "state"}});
					//$("#city").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "city"}});
					$("#country").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "country"}});
					$(".ac-container").css("position", "fixed");
				}
			}});
			return false;
		}else{
			return true;
		}
	});

	$("#auth-bank").live("click keypress", function(event){
		if(window.location.pathname.match(/register\.php/i) == null && (event.type.match(/click/i) || event.which == 32 || event.which == 13)){
			$.ajax({url: "/cgi-bin/logger.cgi", async: false, cache: false, data: {"modal": $("#register-dialog").dialog("option", "title"), "time": (new Date().getTime() - modaldate.getTime())}});
			modaldate = new Date();
			$.ajax({data: ($("#billing").is(":visible") ? $("#address, #city, #state, #country, #postalcode, #companycategory, #terms").serialize() + "&" : "") + $.trim($(this).attr("href").match(/\?.*/)).replace(/^\?/, ""), success: function(data){
				if(data != null && data.title && data.html){
					$("#register-dialog").dialog("option", "title", data.title);
					$("#register-dialog").html(data.html);
					$("#billing").validationEngine();
					$(".ac-container").remove();
					$("#state").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "state"}});
					//$("#city").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "city"}});
					$("#country").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "country"}});
					$(".ac-container").css("position", "fixed");
					$("#address").focus();
				}
			}});
			return false;
		}else{
			return true;
		}
	});

	$("#auth-cc").live("click keypress", function(event){
		if(window.location.pathname.match(/register\.php/i) == null && (event.type.match(/click/i) || event.which == 32 || event.which == 13)){
			$.ajax({url: "/cgi-bin/logger.cgi", async: false, cache: false, data: {"modal": $("#register-dialog").dialog("option", "title"), "time": (new Date().getTime() - modaldate.getTime())}});
			modaldate = new Date();
			$.ajax({data: ($("#billing").is(":visible") ? $("#address, #city, #state, #country, #postalcode, #companycategory, #terms").serialize() + "&" : "") + $.trim($(this).attr("href").match(/\?.*/)).replace(/^\?/, ""), success: function(data){
				if(data != null && data.title && data.html){
					$("#register-dialog").dialog("option", "title", data.title);
					$("#register-dialog").html(data.html);
					$("#billing").validationEngine();
					$(".ac-container").remove();
					$("#state").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "state"}});
					//$("#city").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "city"}});
					$("#country").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "country"}});
					$(".ac-container").css("position", "fixed");
					$("#address").focus();
				}
			}});
			return false;
		}else{
			return true;
		}
	});

	$("#auth-disable").live("click keypress", function(event){
		if(window.location.pathname.match(/register\.php/i) == null && (event.type.match(/click/i) || event.which == 32 || event.which == 13)){
			$.ajax({url: "/cgi-bin/logger.cgi", async: false, cache: false, data: {"modal": $("#register-dialog").dialog("option", "title"), "time": (new Date().getTime() - modaldate.getTime())}});
			modaldate = new Date();
			$.ajax({data: ($("#billing").is(":visible") ? $("#address, #city, #state, #country, #postalcode, #companycategory, #terms").serialize() + "&" : "") + $.trim($(this).attr("href").match(/\?.*/)).replace(/^\?/, ""), success: function(data){
				if(data != null && data.title && data.html){
					$("#register-dialog").dialog("option", "title", data.title);
					$("#register-dialog").html(data.html);
				}
			}});
			return false;
		}else{
			return true;
		}
	});
	
	$("#close-status").live("click keypress", function(){
		$("#status-dialog").dialog("close");
	});

	$("#close-register").live("click keypress", function(){
		$("#register-dialog").dialog("close");
	});

	$("#register").live("submit", function(event){
		var error = "";
		var field = "";
		
		if($("label[for=" + $("input[name=use]:checked").attr("id") + "]").text().match(/personal/i) == null){
			if($.trim($("#title").val()).match(/^[\x20-\x7E\xA0-\xFF]+$/i) == null){
		        //error
				error = (($.trim($("#title").val()) == "") ? "Position is required\n" : "Invalid position\n") + error;
				field += ((field == "" ? "" : ", ") + "#title");
			}

			if($.trim($("#company").val()).match(/^[\x20-\x7E\xA0-\xFF]+$/i) == null){
		        //error
				error = (($.trim($("#company").val()) == "") ? "Company is required.\n" : "Invalid company\n") + error;
				field += ((field == "" ? "" : ", ") + "#company");
			}
		}

		if($("input[name=use]:checked").val() == null){
			//error
			error = "Account type is required\n" + error;
			field = ((field == "" ? "" : ", ") + "input[name=use]");
		}
		
		if(($("#register-dialog").dialog("option", "title") == "Update" && $.trim($("#passwd").val()).match(/^[A-Za-z0-9]{2,50}$/i) == null) || ($("#register-dialog").dialog("option", "title") != "Upgrade" && $.trim($("#passwd").val()).match(/^[A-Za-z0-9]{5,50}$/i) == null)){
			//error
			error = (($.trim($("#passwd").val()) == "") ? "Password is required\n" : ($.trim($("#passwd").val()).match(/[^A-za-z0-9]/i) != null ? "Password may only contain letters and numbers\n" : "Passwords must have a minimum of 5 characters.\n")) + error;
			field += ((field == "" ? "" : ", ") + "#passwd");
		}

		if($.trim($("#postalcode").val()).match(/^\w[\w -]{2,9}$/i) == null){
			//error
			error = (($.trim($("#postalcode").val()) != "") ? "Postal code is required\n" : "Invalid postal code\n") + error;
			field += ((field == "" ? "" : ", ") + "#postalcode");
		}

		if($.trim($("#phone").val()).match(/^([+]?\d{1,3}[ .-]?)?(\(\d{2,6}\))?([\d .\/-]{3,20})(\s?(x|ext?|extension)\s?\d{1,4})?$/i) == null){
			//error
			error = (($.trim($("#phone").val()) == "") ? "Phone is required\n" : "Invalid phone number\n") + error;
			field += ((field == "" ? "" : ", ") + "#phone");
		}

		if($.trim($("#newemail").val()).match(/^[\w!#$%&'*+\/=?^`{|}~-]+(?:\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i) == null){
			//error
			error = (($.trim($("#newemail").val()) == "") ? "Email address is required\n" : "Invalid email address\n") + error;
			field += ((field == "" ? "" : ", ") + "#newemail");
		}

		if($.trim($("#lname").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF`'][\w\xC0-\xD6\xD8-\xF6\xF8-\xFF #,\.&\/\(\)"`'-]{0,75}$/i) == null){
			//error
			error = (($.trim($("#lname").val()) == "") ? "Lastname is required\n" : "Invalid lastname\n") + error;
			field += ((field == "" ? "" : ", ") + "#lname");
		}

		if($.trim($("#fname").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF`'][\w\xC0-\xD6\xD8-\xF6\xF8-\xFF #,\.&\/\(\)"`'-]{0,75}$/i) == null){
			//error
			error = (($.trim($("#fname").val()) == "") ? "Firstname is required\n" : "Invalid firstname\n") + error;
			field += ((field == "" ? "" : ", ") + "#fname");
		}

		if(error != ""){
			$("#register .required").removeClass("required");
			$(field).attr("class", "required");
			alert(error);
			return false;
		}else if(window.location.pathname.match(/register\.php/i) == null){
			$.ajax({url: "/cgi-bin/logger.cgi", async: false, cache: false, data: {"modal": $("#register-dialog").dialog("option", "title"), "time": (new Date().getTime() - modaldate.getTime())}});
			modaldate = new Date();
			$.ajax({data: $("#register").serialize(), beforeSend: function(){
				$("#register").validationEngine("hideAll");
				$("#register-dialog").html('<div class="loading"></div>');
			}, success: function(data){
				if(data != null && data.result && data.title && data.html){
					$("#register-dialog").dialog("option", "title", data.title);
					$("#register-dialog").html(data.html);
					$("#billing").validationEngine();
					$(".ac-container").remove();
					$("#state").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "state"}});
					//$("#city").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "city"}});
					$("#country").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "country"}});
					$("#address").focus();
					$(".ac-container").css("position", "fixed");
				}else if(data != null && data.title && data.html){
					$("#register-dialog").dialog("option", "title", data.title);
					$("#register-dialog").html(data.html);
				}
			}});
			return false;
		}else{
			return true;
		}
	});

	$("#billing").live("submit", function(event){
		var error = "";
		var field = "";

		if($("#terms:checked").val() != "true"){
			error = "You must accept Terms and Conditions\n" + error;
			field += ((field == "" ? "" : ", ") + "#terms");
		}

		if($("#bank").is(":visible")){
			if($.trim($("#bankphone").val()).match(/^(?:[+]?\d{1,3}[ .-]?)?(?:\(\d{2,6}\))?(?:[\d .\/-]{3,20})(?:\s?(?:x|ext?|extension)\s?\d{1,4})?$/i) == null){
				//error
				error = (($.trim($("#bankphone").val()) == "") ? "Bank phone is required\n" : "Invalid bank phone number\n") + error;
				field += ((field == "" ? "" : ", ") + "#bankphone");
			}

			if($.trim($("#bankcontact").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF`'][\w\xC0-\xD6\xD8-\xF6\xF8-\xFF #,\.&\/\(\)"`'-]{1,99}$/i) == null){
				//error
				error = (($.trim($("#bankcontact").val()) == "") ? "Bank contact is required\n" : "Invalid bank contact\n") + error;
				field += ((field == "" ? "" : ", ") + "#bankcontact");
			}

			if($.trim($("#bankname").val()).match(/^[\w\xC0-\xD6\xD8-\xF6\xF8-\xFF`'][\w\xC0-\xD6\xD8-\xF6\xF8-\xFF #,\.&\/\(\)"`'-]{1,74}$/i) == null){
				//error
				error = (($.trim($("#bankname").val()) == "") ? "Bank is required\n" : "Invalid bank\n") + error;
				field += ((field == "" ? "" : ", ") + "#bankname");
			}
		}

		if($("#cc").is(":visible") && (!$("#ccexists").is(":hidden") || $.trim($("#ccpan").val()) != "")){
			var cardnum = ($.trim($("#ccpan").val()).replace(/[^0-9]/gi, ""));
			var year = (Number($.trim($("#ccyear").val())) != 0 ? Number($.trim($("#ccyear").val())) : NaN);
			var month = (Number($.trim($("#ccmonth").val())) != 0 ? Number($.trim($("#ccmonth").val())) : NaN);
			var today = new Date();

			if(isNaN(year)){
				error = "Credit card expiration year is required\n" + error;
				field += ((field == "" ? "" : ", ") + "#ccyear");
			}
			
			if(isNaN(month)){
				error = "Credit card expiration month is required\n" + error;
				field += ((field == "" ? "" : ", ") + "#ccmonth");
			}
			
			if((month - 1) < today.getMonth() && year <= today.getFullYear()){
				//error
				error = "Credit card is expired\n" + error;
				field += ((field == "" ? "" : ", ") + "#ccyear, #ccmonth");
			}

			if(cardnum.match(/^5[1-5][0-9]{14}|4[0-9]{12}(?:[0-9]{3})?|6(?:011|5[0-9]{2})[0-9]{12}$/i) == null){
				//error
				error = "Invalid credit card number\n" + error;
				field += ((field == "" ? "" : ", ") + "#ccpan");
			}else{
				var cpan = cardnum.split("");
				var total = 0;

				for(idx = 0; idx < cpan.length; idx++){
					if(!isNaN(Number(cpan[idx]))){
						if((idx % 2) != 0){
							total += Number(cpan[idx]);
						}else{
							total += (Number(cpan[idx] * 2) > 9 ? Number(cpan[idx] * 2) - 9 : Number(cpan[idx] * 2));
						}
					}else{
						total = 0;
						break;
					}
				}

				if((total <= 0) || ((total % 10) != 0)){
					//error
					error = "Invalid credit card number\n" + error;
					field += ((field == "" ? "" : ", ") + "#ccpan");
				}
			}
		}
		
		if($("#companycategory").is(":visible") && $("#companycategory").val() == 0){
			//error
			error = "Company type is required\n" + error;
			field += ((field == "" ? "" : ", ") + "#companycategory");
		}

		if($.trim($("#postalcode").val()).match(/^\w[\w -]{2,9}$/i) == null){
			//error
			error = (($.trim($("#postalcode").val()) == "") ? "Postal code is required\n" : "Invalid postal code\n") + error;
			field += ((field == "" ? "" : ", ") + "#postalcode");
		}

		if($.trim($("#country").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF][a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF -]+$/i) == null){
			//error
			error = (($.trim($("#country").val()) == "") ? "Country is required\n" : "Invalid country\n") + error;
			field += ((field == "" ? "" : ", ") + "#country");
		}

		if($.trim($("#state").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF][a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF .-]+$/i) == null){
			//error
			error = (($.trim($("#state").val()) == "") ? "State is required\n" : "Invalid state\n") + error;
			field += ((field == "" ? "" : ", ") + "#state");
		}

		if($.trim($("#city").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF][a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF \/.-]+$/i) == null){
			//error
			error = (($.trim($("#city").val()) == "") ? "City is required\n" : "Invalid city\n") + error;
			field += ((field == "" ? "" : ", ") + "#city");
		}

		if($.trim($("#address").val()).match(/^[\w\xC0-\xD6\xD8-\xF6\xF8-\xFF# ,.&\/\\\(\)-]+$/i) == null){
			//error
			error = (($.trim($("#address").val()) == "") ? "Address is required\n" : "Invalid address\n") + error;
			field += ((field == "" ? "" : ", ") + "#address");
		}

		if(error != ""){
			$("#advanced-register .required").removeClass("required");
			$(field).attr("class", "required");
			alert(error);
			return false;
		}else if(window.location.pathname.match(/register\.php/i) == null){
			$.ajax({url: "/cgi-bin/logger.cgi", async: false, cache: false, data: {"modal": $("#register-dialog").dialog("option", "title"), "time": (new Date().getTime() - modaldate.getTime())}});
			modaldate = new Date();
			$.ajax({data: $("#billing").serialize(), beforeSend: function(){
				$("#register").validationEngine("hideAll");
				$("#register-dialog").html('<div class="loading"></div>');
			}, success: function(data){
				if(data != null && data.title && data.html){
					$("#register-dialog").dialog("option", "title", data.title);
					$("#register-dialog").html(data.html);
				}
			}});
			return false;
		}else{
			return true;
		}
	});
	
	$("#compcc").live("submit", function(event){
		var error = "";
		var field = "";
		var cardnum = ($.trim($("#ccpan").val()).replace(/[^0-9]/gi, ""));
		var year = (Number($.trim($("#ccyear").val())) != 0 ? Number($.trim($("#ccyear").val())) : NaN);
		var month = (Number($.trim($("#ccmonth").val())) != 0 ? Number($.trim($("#ccmonth").val())) : NaN);
		var today = new Date();
		
		if(isNaN(year)){
			error = "Credit card expiration year is required\n" + error;
			field += ((field == "" ? "" : ", ") + "#ccyear");
		}
		
		if(isNaN(month)){
			error = "Credit card expiration month is required\n" + error;
			field += ((field == "" ? "" : ", ") + "#ccmonth");
		}

		if((month - 1) < today.getMonth() && year <= today.getFullYear()){
			//error
			error = "Credit card is expired\n" + error;
			field += ((field == "" ? "" : ", ") + "#ccyear, #ccmonth");
		}

		if(cardnum.match(/^5[1-5][0-9]{14}|4[0-9]{12}(?:[0-9]{3})?|6(?:011|5[0-9]{2})[0-9]{12}$/i) == null){
			//error
			error = "Invalid credit card number\n" + error;
			field += ((field == "" ? "" : ", ") + "#ccpan");
		}else{
			var cpan = cardnum.split("");
			var total = 0;

			for(idx = 0; idx < cpan.length; idx++){
				if(!isNaN(Number(cpan[idx]))){
					if((idx % 2) != 0){
						total += Number(cpan[idx]);
					}else{
						total += (Number(cpan[idx] * 2) > 9 ? Number(cpan[idx] * 2) - 9 : Number(cpan[idx] * 2));
					}
				}else{
					total = 0;
					break;
				}
			}

			if((total <= 0) || ((total % 10) != 0)){
				//error
				error = "Invalid credit card number\n" + error;
				field += ((field == "" ? "" : ", ") + "#ccpan");
			}
		}
		
		if(error != ""){
			$("#cc .required").removeClass("required");
			$(field).attr("class", "required");
			alert(error);
			return false;
		}else if(window.location.pathname.match(/register\.php/) == null){
			$.ajax({url: "/cgi-bin/logger.cgi", async: false, cache: false, data: {"modal": $("#register-dialog").dialog("option", "title"), "time": (new Date().getTime() - modaldate.getTime())}});
			modaldate = new Date();
			$.ajax({data: $("#compcc").serialize(), beforeSend: function(){
				$("#register-dialog").html('<div class="loading"></div>');
			}, success: function(data){
				if(data != null && data.title && data.html){
					$("#register-dialog").dialog("option", "title", data.title);
					$("#register-dialog").html(data.html);
				}
			}});
			return false;
		}else{
			return true;
		}
	});
	
	$("#compbank").live("submit", function(event){
		var error = "";
		var field = "";
		
		if($.trim($("#bankphone").val()).match(/^(?:[+]?\d{1,3}[ .-]?)?(?:\(\d{2,6}\))?(?:[\d .\/-]{3,20})(?:\s?(?:x|ext?|extension)\s?\d{1,4})?$/i) == null){
			//error
			error = (($.trim($("#bankphone").val()) == "") ? "Bank phone is required\n" : "Invalid bank phone number\n") + error;
			field += ((field == "" ? "" : ", ") + "#bankphone");
		}

		if($.trim($("#bankcontact").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF`'][\w\xC0-\xD6\xD8-\xF6\xF8-\xFF #,\.&\/\(\)"`'-]{1,99}$/i) == null){
			//error
			error = (($.trim($("#bankcontact").val()) == "") ? "Bank contact is required\n" : "Invalid bank contact\n") + error;
			field += ((field == "" ? "" : ", ") + "#bankcontact");
		}

		if($.trim($("#bankname").val()).match(/^[\w\xC0-\xD6\xD8-\xF6\xF8-\xFF`'][\w\xC0-\xD6\xD8-\xF6\xF8-\xFF #,\.&\/\(\)"`'-]{1,74}$/i) == null){
			//error
			error = (($.trim($("#bankname").val()) == "") ? "Bank is required\n" : "Invalid bank\n") + error;
			field += ((field == "" ? "" : ", ") + "#bankname");
		}
		
		if(error != ""){
			$("#bank .required").removeClass("required");
			$(field).attr("class", "required");
			alert(error + "are required to save");
			return false;
		}else if(window.location.pathname.match(/register\.php/) == null){
			$.ajax({url: "/cgi-bin/logger.cgi", async: false, cache: false, data: {"modal": $("#register-dialog").dialog("option", "title"), "time": (new Date().getTime() - modaldate.getTime())}});
			modaldate = new Date();
			$.ajax({data: $("#compbank").serialize(), beforeSend: function(){
				$("#register-dialog").html('<div class="loading"></div>');
			}, success: function(data){
				if(data != null && data.title && data.html){
					$("#register-dialog").dialog("option", "title", data.title);
					$("#register-dialog").html(data.html);
				}
			}});
			return false;
		}else{
			return true;
		}
	});
	
	$("#update").submit(function(event){
		var cardnum = ($.trim($("#ccpan").val()).replace(/[^0-9]/gi, ""));
		var year = (Number($.trim($("#ccyear").val())) != 0 ? Number($.trim($("#ccyear").val())) : NaN);
		var month = (Number($.trim($("#ccmonth").val())) != 0 ? Number($.trim($("#ccmonth").val())) : NaN);
		var today = new Date();
		var basic = false;
		var error = "";
		var field = "";
		
		if($("#terms:checked").val() != "true"){
			//error
			error = "You must accept Terms and Conditions\n" + error;
			field += ((field == "" ? "" : ", ") + "#terms");
		}
		
		if($.trim($("#bankname").val()) != "" || $.trim($("#bankcontact").val()) != "" || $.trim($("#bankphone").val()) != ""){
			if($.trim($("#bankphone").val()).match(/^(?:[+]?\d{1,3}[ .-]?)?(?:\(\d{2,6}\))?(?:[\d .\/-]{3,20})(?:\s?(?:x|ext?|extension)\s?\d{1,4})?$/i) == null){
				//error
				error = (($.trim($("#bankphone").val()) == "") ? "Bank phone is required\n" : "Invalid bank phone number\n") + error;
				field += ((field == "" ? "" : ", ") + "#bankphone");
			}

			if($.trim($("#bankcontact").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF`'][\w\xC0-\xD6\xD8-\xF6\xF8-\xFF #,\.&\/\(\)"`'-]{1,99}$/i) == null){
				//error
				error = (($.trim($("#bankcontact").val()) == "") ? "Bank contact is required\n" : "Invalid bank contact\n") + error;
				field += ((field == "" ? "" : ", ") + "#bankcontact");
			}

			if($.trim($("#bankname").val()).match(/^[\w\xC0-\xD6\xD8-\xF6\xF8-\xFF`'][\w\xC0-\xD6\xD8-\xF6\xF8-\xFF #,\.&\/\(\)"`'-]{1,74}$/i) == null){
				//error
				error = (($.trim($("#bankname").val()) == "") ? "Bank is required\n" : "Invalid bank\n") + error;
				field += ((field == "" ? "" : ", ") + "#bankname");
			}
		}
		
		if(cardnum != ""){
			if(isNaN(year)){
				error = "Credit card expiration year is required\n" + error;
				field += ((field == "" ? "" : ", ") + "#ccyear");
			}
			
			if(isNaN(month)){
				error = "Credit card expiration month is required\n" + error;
				field += ((field == "" ? "" : ", ") + "#ccmonth");
			}
			
			if((month - 1) < today.getMonth() && year <= today.getFullYear()){
				//error
				error = "Credit card is expired\n" + error;
				field += ((field == "" ? "" : ", ") + "#ccyear, #ccmonth");
			}

			if(cardnum.match(/^5[1-5][0-9]{14}|4[0-9]{12}(?:[0-9]{3})?|6(?:011|5[0-9]{2})[0-9]{12}$/i) == null){
				//error
				error = "Invalid credit card number\n" + error;
				field += ((field == "" ? "" : ", ") + "#ccpan");
			}else{
				var cpan = cardnum.split("");
				var total = 0;

				for(idx = 0; idx < cpan.length; idx++){
					if(!isNaN(Number(cpan[idx]))){
						if((idx % 2) != 0){
							total += Number(cpan[idx]);
						}else{
							total += (Number(cpan[idx] * 2) > 9 ? Number(cpan[idx] * 2) - 9 : Number(cpan[idx] * 2));
						}
					}else{
						total = 0;
						break;
					}
				}

				if((total <= 0) || ((total % 10) != 0)){
					//error
					error = "Invalid credit card number\n" + error;
					field += ((field == "" ? "" : ", ") + "#ccpan");
				}
			}
		}
		
		if($.trim($("#use option:selected").text()).match(/personal/i) == null){
			if($("#companycategory").is(":visible") && $("#companycategory").val() == 0){
				//error
				error = "Company type is required\n" + error;
				field += ((field == "" ? "" : ", ") + "#companycategory");
			}
			
			if($.trim($("#title").val()).match(/^[\x20-\x7E]+$/i) == null){
				//error
				error = (($.trim($("#title").val()) == "") ? "Position is required\n" : "Invalid position\n") + error;
				field += ((field == "" ? "" : ", ") + "#title");
			}

			if($.trim($("#company").val()).match(/^[\x20-\x7E]+$/i) == null){
				//error
				error = (($.trim($("#company").val()) == "") ? "Company is required\n" : "Invalid company\n") + error;
				field += ((field == "" ? "" : ", ") + "#company");
			}
		}
		
		if($.trim($("#postalcode").val()).match(/^\w[\w -]{2,9}$/i) == null){
			//error
			error = (($.trim($("#postalcode").val()) != "") ? "Postal code is required\n" : "Invalid postal code\n") + error;
			field += ((field == "" ? "" : ", ") + "#postalcode");
		}
		
		if($.trim($("#country").val()) != "" || $.trim($("#state").val()) != "" || $.trim($("#city").val()) != "" || $.trim($("#address").val()) != ""){
			if($.trim($("#country").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF][a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF .-]+$/i) == null){
				//error
				error = (($.trim($("#country").val()) == "") ? "Country is required\n" : "Invalid country\n") + error;
				field += ((field == "" ? "" : ", ") + "#country");
			}

			if($.trim($("#state").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF][a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF -]+$/i) == null){
				//error
				error = (($.trim($("#state").val()) == "") ? "State is required\n" : "Invalid state\n") + error;
				field += ((field == "" ? "" : ", ") + "#state");
			}

			if($.trim($("#city").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF][a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF \/.-]+$/i) == null){
				//error
				error = (($.trim($("#city").val()) == "") ? "City is required\n" : "Invalid city\n") + error;
				field += ((field == "" ? "" : ", ") + "#city");
			}

			if($.trim($("#address").val()).match(/^[\w\xC0-\xD6\xD8-\xF6\xF8-\xFF# ,.&\/\\\(\)-]+$/i) == null){
				//error
				error = (($.trim($("#address").val()) == "") ? "Address is required\n" : "Invalid address\n") + error;
				field += ((field == "" ? "" : ", ") + "#address");
			}
		}else{
			basic = true;
		}
		
		if($.trim($("#passwd").val()).match(/^[a-z0-9]{2,50}$/i) == null){
			//error
			error = (($.trim($("#passwd").val()) == "") ? "Password is required\n" : "Invalid password\n") + error;
			field += ((field == "" ? "" : ", ") + "#passwd");
		}

		if($.trim($("#phone").val()).match(/^([+]?\d{1,3}[ .-]?)?(\(\d{2,6}\))?([\d .\/-]{3,20})(\s?(x|ext?|extension)\s?\d{1,4})?$/i) == null){
			//error
			error = (($.trim($("#phone").val()) == "") ? "Phone is required\n" : "Invalid phone number\n") + error;
			field += ((field == "" ? "" : ", ") + "#phone");
		}

		if($.trim($("#newemail").val()).match(/^[\w!#$%&'*+\/=?^`{|}~-]+(?:\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i) == null){
			//error
			error = (($.trim($("#newemail").val()) == "") ? "Email address is required\n" : "Invalid email address\n") + error;
			field += ((field == "" ? "" : ", ") + "#newemail");
		}

		if($.trim($("#lname").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF`'][\w\xC0-\xD6\xD8-\xF6\xF8-\xFF #,\.&\/\(\)"`'-]+$/i) == null){
			//error
			error = (($.trim($("#lname").val()) == "") ? "Lastname is required\n" : "Invalid lastname\n") + error;
			field += ((field == "" ? "" : ", ") + "#lname");
		}

		if($.trim($("#fname").val()).match(/^[a-z\xC0-\xD6\xD8-\xF6\xF8-\xFF`'][\w\xC0-\xD6\xD8-\xF6\xF8-\xFF #,\.&\/\(\)"`'-]+$/i) == null){
			//error
			error = (($.trim($("#fname").val()) == "") ? "Firstname is required\n" : "Invalid firstname\n") + error;
			field += ((field == "" ? "" : ", ") + "#fname");
		}
		
		if(error != ""){
			$("#update-register .required").removeClass("required");
			$(field).attr("class", "required");
			alert(error);
			return false;
		}else if(basic){
			return confirm("This will disable your account from bidding");
		}
	});
    
    $(".close-done, .ui-dialog-titlebar-close, #close-status").live("click keypress", function (){
        _ignoreHashChange = true;
        return true;
    })

	$("#register, #billing, #update").validationEngine();
	$("#passwd, #altpasswd, #passwd-toggle, label[for=passwd-toggle]").toggle();
	$("#passwd").keyup();
	$("#passwd").blur();
	$("#passwd-toggle").change();
	$("#state").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "state"}});
	//$("#city").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "city"}});
	$("#country").autocomplete({serviceUrl : "/ajax/address.php", minChars : 2, zIndex : 1100, params: {lookup: "country"}});
	$("#login a:first").hide();
	$.ajaxSetup({url: "/ajax/ajax.php", dataType: "json"});
});

