//Sandbox Engine
//PHP AJAX JSON Controller and front-end functions file

//Used for convenient internal variables
var SB_System=new Object();

//If you ever set systemLock to true, then this prevents user interface actions from taking place
SB_System.systemLock=false;

$(document).ready(function(){
	
	$("ul.dropdown li").hover(function(){
	    // simplejquerydropdowns
//		$(".wysiwyg").css("z-index", "-9999");
	  	$(this).closest("ul").css("z-index", "9999");
		$(this).addClass("hover");
		$('ul:first',this).hide();
		$('ul:first',this).slideDown(400);
	}, function(){
//		$(".wysiwyg").css("z-index", "0");
		$(this).removeClass("hover");
		$('ul:first',this).slideUp(400);
	});
    
	$("ul.dropdown li ul li:has(ul)").find("a:first").append(" &raquo; ");
    
	$(".fancy").fancybox({
		'type' 				: 'image',
		'cyclic' 			: true,
		'autoDimensions'	: false,
		'centerOnScroll'	: true,
		'onStart'			: function() {
//			$("#sidebar-right embed").hide();
			$("embed").css("visibility", "hidden");
		},
		'onClosed'			: function() {
//			$("#sidebar-right embed").show();
		    $("embed").css("visibility", "visible");
		}
	});
	
	$('#booking-show-trigger').bind('click', function() {
//		if ($(this).hasClass('collapsed')) {
		$("#booking-form-placeholder").slideDown(1000);
		$(this).hide();
		$('#booking-hide-trigger').fadeIn(1000);
//			$(this).attr('class', '');
//		} else {
//			$(this).attr('class', 'collapsed');
//			$("#booking-form-placeholder").slideUp(1000);
//		}
	});
	
	$('#booking-hide-trigger').bind('click', function() {
		$("#booking-form-placeholder").slideUp(1000);
		$(this).hide();
		$('#booking-show-trigger').fadeIn(1000);
//		if ($(this).hasClass('collapsed')) {
//			$(this).attr('class', '');
//		} else {
//			$(this).attr('class', 'collapsed');
//			$("#booking-form-placeholder").slideUp(1000);
//		}
    });
	
	$("#order-form-trigger").bind("click", function() {
		$("#order-form-trigger").slideUp(500);
		$("#update-cart").slideUp(500);
		$(".quantity_input").attr("readonly", "readonly");
		$(".quantity_input").css("background", "#EEEEEE");
		$(".quantity_input").css("cursor", "default");
		$("#order-form-placeholder").slideDown(500);
		goToByScroll('order-form-placeholder');
		$("#f_name").focus();
	});
	
	$("#order-form").bind("keypress", function(e) {
		if (e.keyCode == 13) {
			if ($("textarea:focus").hasClass('txtarea')) {
				
			} else {
				return false;
			}
		}
	});
    
	// dynamic form validation
	$("#f_dyn_form").submit(function() {
		
		var error_flag = 0;
		
		$("[required='1']").each(function(){
			var tag_name = $(this).attr('tagName').toLowerCase();
			if ($(this).is('input:text')) {
				var input_length = $.trim($(this).val()).length;
				if (input_length == 0) {
					error_flag = 1;
					$(this).css("border", "1px solid red");
				} else {
					$(this).css("border", "1px solid #BCB98C");
				}
			}
			if ($(this).is('input:checkbox')) {
				var checked_count = $(this + ':checked').length;
				if (checked_count == 0) {
					error_flag = 1;
				}
			}
			if ($(this).is('input:radio')) {
				var checked_count = $(this + ':checked').length;
				if (checked_count == 0) {
					error_flag = 1;
				}
			}
			if ($(this).is('textarea')) {
				var input_length = $.trim($(this).val()).length;
				if (input_length == 0) {
					$(this).css("border", "1px solid red");
					error_flag = 1;
				} else {
					$(this).css("border", "1px solid #BCB98C");
				}
			}
			if ($(this).is('select')) {
				var select_length = $.trim($(this + ':selected').val()).length;
				if (select_length == 0) {
					error_flag = 1;
				}
			}
		});
		if (error_flag == 0) {
			return true;
		} else {
			goToByScroll('booking-form-placeholder');
			$("#form_msg_holder").fadeIn(1000);
			
			return false;
		}
	});
	
	var content_height = $("#content-container").height();
	if (content_height != null) {
		$("#sidebar-right").height(content_height);
	}
	
	// when user tries submit order, we check if fields are not empty:
	$("#f_to_bank_trigger").click(function() {
		var error_flag = 0;
		
		$("#order-form-placeholder .required").each(function(){
			var tag_name = $(this).attr('tagName').toLowerCase();
			if ($(this).is('input:text')) {
				var input_length = $.trim($(this).val()).length;
				if (input_length == 0) {
					error_flag = 1;
					$(this).css("border", "1px solid red");
				} else {
					$(this).css("border", "1px solid #BCB98C");
				}
			}
			if ($(this).is('input:checkbox')) {
				var checked_count = $(this + ':checked').length;
				if (checked_count == 0) {
					error_flag = 1;
				}
			}
			if ($(this).is('input:radio')) {
				var checked_count = $(this + ':checked').length;
				if (checked_count == 0) {
					error_flag = 1;
					$("#payment_selection_td").css("border", "1px solid red");
				} else {
					$("#payment_selection_td").css("border", "none");
				}
			}
			if ($(this).is('textarea')) {
				var input_length = $.trim($(this).val()).length;
				if (input_length == 0) {
					$(this).css("border", "1px solid red");
					error_flag = 1;
				} else {
					$(this).css("border", "1px solid #BCB98C");
				}
			}
			if ($(this).is('select')) {
				var select_length = $.trim($(this + ':selected').val()).length;
				if (select_length == 0) {
					error_flag = 1;
				}
			}
		});
		
		// if any errors, we prevent moving forward
		if (error_flag == 1) {
			return false;
		}
	});
	
	$(".update-cart").click(function(e) {
		e.preventDefault();
		$("#f_update_cart").attr("name", "f_update_cart"); // set name to 'f_update_cart' so php can trigger quantity update command
		$('#order-form').submit();
	});
	
	
	
	
}); // END: document.ready 

function goToByScroll(id){
	$('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}

//This is front-end input controller. Data can be whatever you want, 
//you can use it in different context depending on action.
function uiAction(action,data){
	//input is an object used to be sent to AJAX backend.
	var input=new Object();
	if(SB_System.systemLock==false){
		switch(action){
		
			//This is a template and shows how the system works
			case 'simpleExample':	
				//Most UI actions are usually simple and don't require AJAX, this simply throws an alert
				alert('Hello world!');
			break;
			
			//This is a template and shows how the system works
			case 'ajaxExample':			
				//this does not have to be the same as action, but usually is
				input['testvariable']='testing';
				executeAjaxAction(action,input);
			break;
			
			case 'reader':			
				SB_Reader(data);
			break;
			
			default:
				alert('UI ERROR: This action ['+action+'] does not exist in user interface!');
		}
	}
}

//This should not be modified, it is standardized function for sending data to backend
//and retreiving the JSON string before forwarding it to frontend callback
function executeAjaxAction(action, rawdata, ajaxurl){
	if(!ajaxurl){ ajaxurl='/controllers/ajax.php'; }
	if(!rawdata){ rawdata=new Object(); }
	//data is an array or an object serialized for use in a URL
	data=$.param(rawdata);
	//Lock is used to prevent action spamming
	//If you don't want to lock AJAX actions, then comment this out or at least display an error
	if(SB_System['lock_'+action]!=1){
		SB_System['lock_'+action]=1;
		$.ajax({
			type: 'POST',
			url: ajaxurl,
			dataType: 'json',
			cache: false,
			async: true,
			data: ({action : action, data : data}),
			beforeSend: function(header){
				//Recommended, however for IE browsers this is an unsupported method, so leave it commented out (for now).
				//header.overrideMimeType('text/plain');
				header.setRequestHeader('From',SB_SandboxKey);
			},
			success: function(json){
				//If successful the JSON returned from backend is forwarded to be parsed by frontend actions
				parseAjaxReturn(json);
				SB_System['lock_'+action]=0;
			},
			error: function(obj,msg,detailedmsg){
				//In case there was any unexpected error in the backend (PHP errors and whatnot), alert everything
				alert('ENGINE ERROR: '+msg+' ('+detailedmsg+')');
				SB_System['lock_'+action]=0;
			}
		});
	} else {
		//You can comment this alert out
		alert('ENGINE ERROR: This action is already in progress');
	}
}

//This function takes the AJAX returned JSON and executes actions depending on the type
//You can call new user interface actions from here as well
function parseAjaxReturn(json){
	//If backend defines an error and a message for the error, alert this
	if(json['error']==1){
		alert('ERROR: '+json['message']);
	} else {
		switch(json['action']){
		
			//this is used for example, it simply throws an alert
			case 'exampleAction':
				alert(json['message']);
			break;
			
			//Do not remove this, it is used by backend engine in case session needs to be refreshed
			case 'refresh':
				document.location.href=document.location.href;
			break;
			
			//Backend should always define action to be 'none' if no callback is defined
			case 'none':
			break;
			
			//In case no action was defined, alert an error
			default:
				alert('UI ERROR: Callback action ['+json['action']+'] does not exist in user interface!');
		}
	}
}
