(function($) {

	var app = $.sammy('#main', function() {

		/*this.around(function(callback) {
			if (!isOnline()) {
				showMessage(glbAppOffline);
			} else {
				callback();
			}
		});*/

		this.get('#/', function(context) {

			preparePage();

			request('/api/login/index', {}, function(ret) {
				handlePage(ret);
			});

		});
		
		this.get('#/survey/:survey_code', function(context) {
			
			preparePage();
			
			var data = {code:this.params['survey_code']};
						
			request('/api/survey/index', data, function(ret) {
				handlePage(ret);
			});
			
		});
		
		this.get('#/survey-list/:timestamp/:orderField/:orderDir/:pageNumb', function(context) {
			
			preparePage();
			
			var searchData = null;
			var form = $('#form-survey-list');
			if (form.length > 0) {
				searchData = form.serialize();
			}
			
			var data = {orderField:this.params['orderField'], orderDir:this.params['orderDir'], pageNumb:this.params['pageNumb'], searchData:searchData};
						
			request('/api/survey/surveyList', data, function(ret) {
				handlePage(ret);
			});
			
		});
		
		this.get('#/survey-edit/:timestamp/:id', function(context) {
			
			preparePage();
			
			var data = {id:this.params['id']};
						
			request('/api/survey/surveyEdit', data, function(ret) {
				handlePage(ret, null, function() {
					
					wsConnect();
					
					$('.chosen-select').chosen({no_results_text: glbNothingFound});
					
					$('#request_cc').trigger('change');
					$('#request_cc').prop('disabled', true);
					$('#is_remote_visit').prop('checked', true);
					$('#is_remote_visit').trigger('change');
					
					$.datetimepicker.setLocale(getLanguage());
					
					$('.datepicker').datetimepicker({
						format:'d/m/Y',
						timepicker:false
					});
					
					$('.datetimepicker').datetimepicker({
						format:'d/m/Y H.i'
					});
				});
				
			});
			
		});

		this.get('#/auto-login/:autologinToken/:requestId', function(context) {

			var data = {autologinToken:this.params['autologinToken'], requestId:this.params['requestId']};

			request('/api/login/autoLogin', data, function(ret) {

				if (typeof ret.RequestID !== 'undefined') {
					gotoDest('requests-edit/'+ret.ts+'/'+ret.RequestID+'/view/hashtag/my/hashtag/created_at/desc/1');
				} else {
					gotoDest('');
				}

			});

		});

		this.get('#/success-login', function(context) {
			gotoDest('dashboard');
		});

		this.get('#/disclaimers-accepted', function(context) {
			gotoDest('dashboard');
		});

		this.get('#/dashboard', function(context) {

			preparePage();

			request('/api/dashboard/index', {}, function(ret) {
				handlePage(ret);
			});

		});

		this.get('#/profile/:timestamp', function(context) {

			preparePage();

			request('/api/user/index', {}, function(ret) {
				handlePage(ret, null, function() {
					$('.chosen-select').chosen({no_results_text: glbNothingFound});
					loadGlobalVariables(); //Update the localised strings
				});
			});

		});

		this.get('#/users/:timestamp/:orderField/:orderDir/:pageNumb', function(context) {

			preparePage();

			var searchData = null;
			var form = $('#table-search-users');
			if (form.length > 0) {
				searchData = form.serialize();
			}

			var data = {orderField:this.params['orderField'], orderDir:this.params['orderDir'], pageNumb:this.params['pageNumb'], searchData:searchData};

			request('/api/user/usersList', data, function(ret) {
				handlePage(ret, null, function() {
					$('html, body').animate({
				        scrollTop: 0
				    }, 500);
				});
			});

		});

		this.get('#/users-edit/:timestamp/:userId/:orderField/:orderDir/:pageNumb', function(context) {

			preparePage();

			var data = {userId:this.params['userId'], orderField:this.params['orderField'], orderDir:this.params['orderDir'], pageNumb:this.params['pageNumb']};

			request('/api/user/usersEdit', data, function(ret) {
				handlePage(ret, null, function() {
					$('.chosen-select').chosen({no_results_text: glbNothingFound});
					$('html, body').animate({
				        scrollTop: 0
				    }, 500);
				});
			});

		});

		this.get('#/users-search/:timestamp/:orderField/:orderDir/:pageNumb', function(context) {

			preparePage();

			var searchData = null;
			var form = $('#users-advanced-search');
			if (form.length > 0) {
				searchData = form.serialize();
			}

			var data = {orderField:this.params['orderField'], orderDir:this.params['orderDir'], pageNumb:this.params['pageNumb'], searchData:searchData};

			request('/api/user/usersSearch', data, function(ret) {
				handlePage(ret, null, function() {
					$('.chosen-select').chosen({no_results_text: glbNothingFound});

					$('html, body').animate({
				        scrollTop: $('#search-scroll-pointer').offset().top
				    }, 500);
				});
			});

		});

		this.get('#/users-sessions/:pageNumb', function(context) {

			preparePage();

			var data = {pageNumb:this.params['pageNumb']};

			request('/api/user/usersSessions', data, function(ret) {
				handlePage(ret);
			});

		});

		this.get('#/users-access-logs/:pageNumb', function(context) {

			preparePage();

			var data = {pageNumb:this.params['pageNumb']};

			request('/api/user/usersAccessLogs', data, function(ret) {
				handlePage(ret);
			});

		});

		this.get('#/notification-tracker/:timestamp/:notifType/:pageNumb', function(context) {

			preparePage();

			var data = {pageNumb:this.params['pageNumb'], notifType:this.params['notifType']};

			request('/api/user/usersNotificationTracker', data, function(ret) {
				handlePage(ret);
			});

		});

		this.get('#/requests/:timestamp/:scope/:orderField/:orderDir/:pageNumb', function(context) {

			preparePage();

			var searchData = null;
			var form = $('#table-search-requests');
			if (form.length > 0) {
				searchData = form.serialize();
			}

			var data = {scope:this.params['scope'],orderField:this.params['orderField'], orderDir:this.params['orderDir'], pageNumb:this.params['pageNumb'], searchData:searchData};

			request('/api/request/index', data, function(ret) {
				handlePage(ret);
				globalICD10List = []; //Reset the ICD10 list
			});

		});

		this.get('#/requests-edit/:timestamp/:requestID/:viewType/:parentTitle/:parentScope/:parentBaseUri/:orderField/:orderDir/:pageNumb', function(context) {

			preparePage();

			var searchData = null;
			var form = $('#request-edit-form');
			if (form.length > 0) {
				searchData = form.serialize();
			}

			var data = {requestID:this.params['requestID'],viewType:this.params['viewType'],parentTitle:this.params['parentTitle'], parentScope:this.params['parentScope'], parentBaseUri:this.params['parentBaseUri'], orderField:this.params['orderField'], orderDir:this.params['orderDir'], pageNumb:this.params['pageNumb'], searchData:searchData};

			var viewType = this.params['viewType'];

			request('/api/request/requestEdit', data, function(ret) {

				handlePage(ret, '#main', function() {
					//$('.chosen-select').chosen({no_results_text: glbNothingFound});
					//$('[data-toggle="tooltip"]').tooltip();

					//$('#chosen_view_request_chosen .chosen-search-input').prop('disabled', true); //Avoid removing and searching
					//choosenHideDeleteCross();

					if (viewType == 'new-edit') {
						
						if ($('#is_remote_visit').length > 0) {
							//$('#request_cc').trigger('change');
							$('#is_remote_visit').trigger('change');
						}
						
						$.datetimepicker.setLocale(getLanguage());
						
						$('.datepicker').datetimepicker({
							format:'d/m/Y',
							timepicker:false
						});
						
						$('.datetimepicker').datetimepicker({
							format:'d/m/Y H.i'
						});
						
						wsConnect();
						
						console.log('Connection called');
						
						setTimeout(function() {
							$('#request_cc').trigger('change');
							$('#request_cgprovince').trigger('change');
														
							$('.chosen-select').chosen({no_results_text: glbNothingFound});
							$('[data-toggle="tooltip"]').tooltip();
						}, 500);
						
					}

					if (viewType == 'view') {
						$('.tooltipstered').tooltipster();
						var wsRequestDataDreamPDF = ret.jsonData.requestDreamPDF;

						//if (ret.jsonData.userIsAuthor) {
						if (ret.jsonData.hasDreamIntegration && ret.jsonData.userIsAuthor) {
							wsConnect();

							setTimeout(function() {
								
								var ms = '';
								if ($('#medical-specialties-obj').length > 0) {
									ms = $('#medical-specialties-obj').val();
								}
								
								var attachlink = '';
								if ($('#dream-attach-link').length > 0) {
									attachlink = $('#dream-attach-link').val();
								}
								
								wsSend(JSON.stringify({op:'request-pdf-info', ms:ms, attachlink:attachlink, dataPDF:wsRequestDataDreamPDF}), false);
								console.log(wsRequestDataDreamPDF);
								console.log('Data sent');
							}, 1000)
						}
						
						//$('#pdf_postponed_date').mask('00/00/0000', {placeholder: "gg/mm/aaaa"});
				    }

						/*setInterval(function() {
							wsConnect();
						}, 1000);*/

				});
			});

		});

		this.get('#/requests/:timestamp/logs', function(context) {

			preparePage();

			request('/api/request/logs', {}, function(ret) {
				handlePage(ret);
			});

		});

		this.get('#/centers/:timestamp', function(context) {

			preparePage();

			request('/api/center/centersList', {}, function(ret) {
				handlePage(ret);
			});

		});
		
		this.get('#/said/:request_code', function(context) {

			preparePage();
			
			var data = {request_code:this.params['request_code']};

			request('/api/public/showAttachementsInDream', data, function(ret) {
				handlePage(ret);
			});

		});

	    this.get('#/centers/:timestamp/:center_id', function(context) {

	      preparePage();

	      var searchData = null;
	      var form = $('#center-form');
	      if (form.length > 0) {
	        searchData = form.serialize();
	      }

	      var data = {center_id:this.params['center_id']};

	      request('/api/center/index', data, function(ret) {
	        handlePage(ret, null, function() {
	        	$('.chosen-select').chosen({no_results_text: glbNothingFound});
	        });
	      });
	    });

	});

	$(function() {
		app.run('#/');
	});

})(jQuery);
