//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;

var thisPic=0;
var maxPics=0;

$(document).ready(function(){
	maxPics=parseInt($('#gallery-count').val());

$('#overlay').click(function(e) {
	e = e || window.event;
	var t = e.target || e.srcElement;
	if(t.parentNode.id=='sub1' || t.parentNode.id=='sub2'){
		uiAction('closeGallery');
		uiAction('closeQuery');
		uiAction('closeFeedback');
	}	
});	

$('#csi-field-email, #newsletter-button').click(function(e) {
	var url=$('#csi-settings-successurl').val();
	document.location.href=url;
});	

	
	$("#home-menu-1").mouseenter(function(event){
		$("#home-menu-1 > a").css('display','block');	
		var position=$(".home-menu-1").attr('src').lastIndexOf('_');
		var first=$(".home-menu-1").attr('src').slice(0,position);
		$(".home-menu-1").attr('src',first+'_on.png');
    }).mouseleave(function(){
		$("#home-menu-1 > a").css('display','none');			
		var position=$(".home-menu-1").attr('src').lastIndexOf('_');
		var first=$(".home-menu-1").attr('src').slice(0,position);
		$(".home-menu-1").attr('src',first+'_off.png');
    });
	$("#home-menu-2").mouseenter(function(){
		$("#home-menu-2 > a").css('display','block');		
		var position=$(".home-menu-2").attr('src').lastIndexOf('_');
		var first=$(".home-menu-2").attr('src').slice(0,position);
		$(".home-menu-2").attr('src',first+'_on.png');
    }).mouseleave(function(){
		$("#home-menu-2 > a").css('display','none');	
		var position=$(".home-menu-2").attr('src').lastIndexOf('_');
		var first=$(".home-menu-2").attr('src').slice(0,position);
		$(".home-menu-2").attr('src',first+'_off.png');
    });
	$("#home-menu-3").mouseenter(function(){
		$("#home-menu-3 > a").css('display','block');
		var position=$(".home-menu-3").attr('src').lastIndexOf('_');
		var first=$(".home-menu-3").attr('src').slice(0,position);
		$(".home-menu-3").attr('src',first+'_on.png');
    }).mouseleave(function(){
		$("#home-menu-3 > a").css('display','none');
		var position=$(".home-menu-3").attr('src').lastIndexOf('_');
		var first=$(".home-menu-3").attr('src').slice(0,position);
		$(".home-menu-3").attr('src',first+'_off.png');
    });
	
	$(".home-menu-1").mouseenter(function(){
		$("#home-menu-1 > a").css('display','block');
		var position=$(this).attr('src').lastIndexOf('_');
		var first=$(this).attr('src').slice(0,position);
		$(this).attr('src',first+'_on.png');
    }).mouseleave(function(){
		$("#home-menu-1 > a").css('display','none');
		var position=$(this).attr('src').lastIndexOf('_');
		var first=$(this).attr('src').slice(0,position);
		$(this).attr('src',first+'_off.png');
    });	
	$(".home-menu-2").mouseenter(function(){
		$("#home-menu-2 > a").css('display','block');
		var position=$(this).attr('src').lastIndexOf('_');
		var first=$(this).attr('src').slice(0,position);
		$(this).attr('src',first+'_on.png');
    }).mouseleave(function(){
		$("#home-menu-2 > a").css('display','none');
		var position=$(this).attr('src').lastIndexOf('_');
		var first=$(this).attr('src').slice(0,position);
		$(this).attr('src',first+'_off.png');
    });	
	$(".home-menu-3").mouseenter(function(){
		$("#home-menu-3 > a").css('display','block');
		var position=$(this).attr('src').lastIndexOf('_');
		var first=$(this).attr('src').slice(0,position);
		$(this).attr('src',first+'_on.png');
    }).mouseleave(function(){
		$("#home-menu-3 > a").css('display','none');
		var position=$(this).attr('src').lastIndexOf('_');
		var first=$(this).attr('src').slice(0,position);
		$(this).attr('src',first+'_off.png');
    });	
	
	$(".home-menu-4").mouseenter(function(){
		var position=$(this).attr('src').lastIndexOf('_');
		var first=$(this).attr('src').slice(0,position);
		$(this).attr('src',first+'_on.png');
    }).mouseleave(function(){
		var position=$(this).attr('src').lastIndexOf('_');
		var first=$(this).attr('src').slice(0,position);
		$(this).attr('src',first+'_off.png');
    });	
	
	
});


//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 'sendFeedback':			
				input['question']=$('textarea[name="fbquestion"]').val();
				input['name']=$('input[name="fbname"]').val();
				input['lastname']=$('input[name="fblastname"]').val();
				input['phone']=$('input[name="fbphone"]').val();
				input['email']=$('input[name="fbemail"]').val();
				input['pid']=$('input[name="pid"]').val();
				input['url']=$('input[name="fburl"]').val();
				input['type']=$('input[name="qtype"]').val();				
				input['company']='';
				// alert($('textarea[name="fbquestion"]').val());
				executeAjaxAction(action,input);
			break;		

			case 'sendQuery':			
				input['question']=$('textarea[name="fbquestion"]').val();
				input['name']=$('input[name="fbname"]').val();
				input['lastname']=$('input[name="fblastname"]').val();
				input['phone']=$('input[name="fbphone"]').val();
				input['email']=$('input[name="fbemail"]').val();
				input['pid']=$('input[name="pid"]').val();
				input['url']=$('input[name="fburl"]').val();
				input['type']=$('input[name="qtype"]').val();
				input['company']='';
	
				executeAjaxAction(action,input);
			break;				
			
			case 'openGallery':
				thisPic=data;
				$('#gallery-picture').attr('src',($('#gallery-large-'+thisPic).val()));
				$('#overlay').fadeIn(1);
				$('#gallery-box').fadeIn(1);
				
				function checkKeycode(e) {
					var keycode;
					if (window.event) keycode = window.event.keyCode;
					else if (e) keycode = e.which;
						if(keycode == 37){
							uiAction('galleryPrevious');
						}
						if(keycode == 39){
							uiAction('galleryNext');
						}
						if(keycode == 27){
							uiAction('closeGallery');
						}							
				}
				document.onkeydown = checkKeycode;
				
			break;
			
			case 'closeGallery':
				document.onkeydown = '';
				$('#gallery-picture').attr('src','/design/1x1.png');
				$('#overlay').fadeOut(1);
				$('#gallery-box').fadeOut(1);
			break;
			
			case 'closeQuery':
				document.onkeydown = '';
				$('#overlay').fadeOut(1);
				$('#query').fadeOut(1);
			break;
			
			case 'openQuery':
				$('#overlay').fadeIn(1);
				$('#query').fadeIn(1);
				function checkKeycode2(e) {
					var keycode;
					if (window.event) keycode = window.event.keyCode;
					else if (e) keycode = e.which;
						if(keycode == 27){
							uiAction('closeQuery');
						}							
				}
				document.onkeydown = checkKeycode2;				
			break;
			
			case 'closeFeedback':
				document.onkeydown = '';			
				$('#overlay').fadeOut(1);
				$('#feedback').fadeOut(1);
			break;
			
			case 'openFeedback':
				$('#overlay').fadeIn(1);
				$('#feedback').fadeIn(1);
				function checkKeycode3(e) {
					var keycode;
					if (window.event) keycode = window.event.keyCode;
					else if (e) keycode = e.which;
						if(keycode == 27){
							uiAction('closeFeedback');
						}							
				}
				document.onkeydown = checkKeycode3;						
			break;
			
			case 'galleryNext':
				if(thisPic==maxPics){
					thisPic=1;
				} else {
					thisPic++;
				}
				$('#gallery-picture').attr('src',($('#gallery-large-'+thisPic).val()));
			break;
			
			case 'galleryPrevious':
				if(thisPic==1){
					thisPic=maxPics;
				} else {
					thisPic--;
				}
				$('#gallery-picture').attr('src',($('#gallery-large-'+thisPic).val()));
			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;			
			case 'sendFeedback':
				if(json['message']=='success'){
					$('#errortext').html('');
					$('#successtext').html(json['message']);
					document.location.href=document.location.href;
				}else{
					$('#errortext').html(json['message']);
				}
			break;			
			case 'sendQuery':
				if(json['message']=='success'){
					$('#errortext').html('');
					$('#successtext').html(json['message2']);
					window.setTimeout('location.reload()', 2000);
				}else{
					$('#errortext').html(json['message']);
				}
			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!');
		}
	}
}
