//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;


function carousel1_initCallback(carousel) {
	$('#carousel1_forward').bind('click', function() {
		carousel.next();
		return false;
	});
	
	$('#carousel1_back').bind('click', function() {
		carousel.prev();
		return false;
	});
}

function carousel2_initCallback(carousel) {
	$('#carousel2_forward').bind('click', function() {
		carousel.next();
		return false;
	});
	
	$('#carousel2_back').bind('click', function() {
		carousel.prev();
		return false;
	});
}

$(document).ready(function(){
	
	/**
	 * Carousel for gallery
	 */
	$("#carousel1").jcarousel({
		initCallback: carousel1_initCallback,
		buttonNextHTML: null,
		buttonPrevHTML: null,
		wrap: 'circular',
		scroll: 1,
		auto: 0
//        speed: "fast",
	});
	
	/**
	 * Carousel for plans
	 */
	$("#carousel2").jcarousel({
		initCallback: carousel2_initCallback,
		buttonNextHTML: null,
        buttonPrevHTML: null,
		wrap: 'circular',
		scroll: 1,
        auto: 0
//        speed: "fast",
	});
	
	/**
	 * 
	 * Fancybox for objects:
	 * 
	 */
	$(".fancy").fancybox({
		'cyclic'			: true,
		'padding'			: 0,
		'centerOnScroll'	: true,
		'hideOnContentClick': true,
		'overlayColor' 		: '#000000',
		'transitionIn'		:	'elastic',
		'transitionOut'		:	'elastic',
		'onStart'			: function() {
			$(".carousel_arrow_image").css("z-index", "0");
		},
		'onClosed'			: function() {
			$(".carousel_arrow_image").css("z-index", "99999");
		},
		'showCloseButton'	: false,
		'titlePosition' 	: 'inside',
		'titleFormat'		: formatTitle
//		'index': 4
	});
	
	
	/**
	 * 
	 * Modal for object help 
	 * 
	 */
	$('.more_help_modal_trigger').click(function (e) {
		$('#object-more-help-modal-container').modal({
			overlayId:			'object-more-help-modal-overlay',
			opacity: 			80,
			overlayClose: 		true,
			closeTitle: 		'Sulge',
			persist:			true,
			position: 			50,
			onOpen: function (dialog) {
				$(".carousel_arrow_image").css("z-index", "0");
				dialog.overlay.fadeIn(200, function () {
					dialog.container.fadeIn(200, function () {
						dialog.data.fadeIn(200);
					});
				});
			},
			onClose: function (dialog) {
				dialog.data.fadeOut(200, function () {
					dialog.container.fadeOut(200, function () {
						dialog.overlay.fadeOut(200, function () {
							jQuery.modal.close();
							$(".carousel_arrow_image").css("z-index", "99999");
						});
					});
				});
				// also hide related emails:
//				$j(".toggle_minus_name").hide();
//				$j(".toggle_plus_name").show();
//				$j("#names-related-to-domain").hide();
			}
		});
		return false;
	});
	
	/**
	 * 
	 * Submit "more-help" form
	 * 
	 */
	$('#more-help-submit').click(function (e) {
		
		var errors = 0;
		// Validate form:
		var email_regexp = new RegExp("^.+@[^\.].*\.[a-z]{2,}$", "i"); // will allow addresses with + sign too - like raido.aasoja+test@mikare.net
		
		var name_field = $("input[name='f_name']");
		var email_field = $("input[name='f_email']");
		var content_field = $("textarea[name='f_content']");
		var object_id_field = $("input[name='f_object_id']");
		
		if ($.trim(name_field.val()) == '') {
			name_field.css({"border-color" : "red", "color" : "red", "background" : "#FFBDCB"});
			errors = 1;
		} else {
			name_field.css({"border-color" : "#AAAAAA", "color" : "#989898", "background" : "#FFFFFF"});
		}
		
		var email_validated = email_regexp.test(removeSpaces(email_field.val()));
		if ( ! email_validated) {
			errors = 1;
			email_field.css({"border-color" : "red", "color" : "red", "background" : "#FFBDCB"});
		} else {
			email_field.css({"border-color" : "#AAAAAA", "color" : "#989898", "background" : "#FFFFFF"});
		}
		
		if ($.trim(content_field.val()) == '') {
			content_field.css({"border-color" : "red", "color" : "red", "background" : "#FFBDCB"});
			errors = 1;
		} else {
			content_field.css({"border-color" : "#AAAAAA", "color" : "#989898", "background" : "#FFFFFF"});
		}
		
		
		// Submit form:
		if (errors == 0) {
			$("#object-more-help-ajax-loader").show();
			
			$.ajax({
				type: "POST",
				url: "/controllers/ajax.php",
				data: {
					act: "submit-feedback",
					name: name_field.val(),
					email: email_field.val(),
					content: content_field.val(),
					object_id: object_id_field.val()
				},
				dataType: "json",
				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(msg){
					if (msg.status == "OK") {
//						location.reload(true);
						$("#object-more-help-ajax-loader").hide();
						$("#object-more-help-form").hide();
						$("#object-more-help-finishtext").fadeIn(500);
					} else {
						$("#object-more-help-ajax-loader").hide();
					}
				},
				error: function(xml_request, textStatus, errorThrown) { // somth went completly wrong
					var error_html = "Ilmnes kriitiline viga :-( <br />Info vea kohta:<br /><br /> textStatus: " + textStatus + "<br /<br />Vea sisu: <br /><br />" + errorThrown;
	
						alert(error_html);
				}
			}); // END: $j.ajax
		}
	});
	
	
});

/**
 * Function for removing spaces from string
 */
function removeSpaces(string) {
	return string.split(' ').join('');
}

function formatTitle(title, currentArray, currentIndex, currentOpts) {
    return '<div id="tip7-title"><p id="fancy-title"><span style="text-align: center;"' + (title && title.length ? '<b></span>' + title + '</b>' : '' ) + '</p><p id="fancy-buttons"><span><a href="javascript:;" onclick="fancy_original_image(this);" style="margin-right: 1px;"><img src="/design/zoom.png" /></a></span><span><a href="javascript:;" onclick="$.fancybox.close();"><img src="/design/x.png" /></a></span></p></div>';
}

function fancy_original_image(object) {
	// get current image
	var current_image = $("#fancybox-img").attr("src");
	// remove 'medium' from URL:
	var new_image = current_image.replace(/medium\//i, "");
	// Try to open image in new window:
	window.open (new_image);
	
	return false;
	
}
//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!');
		}
	}
}
