/**
 * Client key login script
 * 
 * @author Simplimation
 */


jQuery(document).ready(function(){

	/*
	 * Client access key form submit action
	 */ 
	
	// form id
	var flContent = jQuery("#grefriends .rounded-content");
	var flForm = jQuery("#grefriends-login-form");
	var flField = flForm.find("#grefriends-login-key");
	flField.dirty = false;
	// setup text field onFocus event
	flField.focus(function(){
		if (flField.dirty) {
		} else {
			// add active class to form
			flForm.addClass("active");
			// add active class to field and clear field
			jQuery(this).val("").addClass("active");
		}
	});
	// add loading element
	flForm.append('<span class="loading"><img src="/client/images/ajax-loader-green.gif" alt="loading" /></span>');
	var flLoading = flForm.find(".loading");
	// add message element
	flContent.append('<div class="message"></div>');
	var flMessage = flContent.find(".message");
	// form submit
	flForm.submit(function(){
		// target url if successful
		var target = "/client/viewer.php";
		// AJAX url
		var url = jQuery(this).attr("action");
		// get key from form
		var key = jQuery(this).find("input[name=key]").val();
		// set AJAX options		
		var options = {
			key: key
		};
		if(key != ""){
			// hide message
			flMessage.hide();
			// show loading indicator
			flLoading.show();			
			// AJAX call to check key
			jQuery.getJSON(url,options,function(data){
		      	jQuery.log(data);
				if(data === true){
					jQuery.log("success");
					// load page
					window.location = target;
					//window.open(target);
				} else {
					// hide loading indicator
					flLoading.hide();
					// show message
					flMessage
						.text("Access code is invalid")
						.fadeIn('slow',function(){
							// focus on field
							flField.dirty = true;			
							flField.focus();
						});
					jQuery.log("failed");
				}
			});
		} else {
			// no key
			flMessage
				.text("Please enter your access code")
				.fadeIn('slow',function(){
					// focus on field
					flField.focus();
				});
			
		}
		// cancel default submit action
		return false;
	});

});