var origHref;

function checkLogin(obj, onSuccess) {
	try {
		origHref = obj.href;
		$.get('/ajax-cmd.php?cmd=isRecognized', '', function(text) {
			if(text == '1') {
				onSuccess(origHref, obj, true);
			} else {
				tb_show('', '#TB_inline?height=550&width=400&inlineId=register');
				
				$('#loginform')[0].onsubmit = function() {
					try {
						if(this.purl.value) {				
							$.post('/ajax-cmd.php?cmd=login', $(this).serialize(), function(text) {
								if(text=='1'){
									if(typeof _pclick != "undefined") _pclick.trackEvent('Login');
									onSuccess(origHref, obj, false);
								}else{
									alert('Invalid Purl! Please try again, or click "Register" if you do not have an account.');
								}
							});
						}
					} catch(e) { console.debug(e); }
					return false;
				}
				
				$('#registerform')[0].onsubmit = function() {
					$('#register_submit')[0].disabled = true;
					try {
						if(this.first_name.value && this.last_name.value && this.business.value && this.address.value && this.city.value && this.state.value && this.postal.value && this.country.selectedIndex && this.email.value && this.market.selectedIndex) {				
							$.post('/ajax-cmd.php?cmd=createPurl', $(this).serialize(), function(text) {
								if(text=='1'){
									if(typeof _pclick != "undefined"){
										var lbl = 'Registered for PURL';
										// check for a global _pageName.
										if(typeof _pageName != 'undefined' && _pageName){
											lbl += '_' + _pageName;
										}
										_pclick.trackEvent(lbl);
									}
									onSuccess(origHref, obj, false);
								}else{
									alert(text);
									$('#register_submit')[0].disabled = false;
								}
							});
						}
						else
						{
							alert('Please complete all the required fields.');
							$('#register_submit')[0].disabled = false;
						}
					} catch(e) { console.debug(e); }
					return false;
				}
			}
		});
	} catch(e) { console.debug(e); }
	return false;
}

