// requires AjaxHandler class
// requires generalfunctions.js

function AjaxNavigator(AjaxHandler, historyStatus) {
	this.historyData = new Array();
	this.currentNavigationId = 0;
	this.currentNavigation = {
		pageData: {
			page:		null,
			pageid:		null,
			module:		null,
			moduleid:	null
		},
		urlData: {
			title:	null,
			url:	null
		},
		mobileData: {
			menu:	null,
			title:	null
		},
		editData: null,
		parameters: new Array()
	}
	this.tempNavigation = jQuery.extend(true, {}, this.currentNavigation);
	this.emptyNavigation = jQuery.extend(true, {}, this.tempNavigation);
	this.HistoryJS = {
		allowHistoryPushPop:	true,
		manualStateChange:		true,
		status:					false,
		History:				false
	}
	this.loading={
		mobileLoading: false,
		desktopLoading: false
	}
		

	if ((typeof AjaxHandler != 'undefined') && (AjaxHandler instanceof AjaxCalls)) this.AjaxHandler=AjaxHandler;
	else this.AjaxHandler=new AjaxCalls();

	if (typeof historyStatus != 'undefined') this.switchHistoryJS(historyStatus);

	this.setCurrentPage(null, true);
}

/** Switch functions **/
AjaxNavigator.prototype.switchHistoryJS = function(switchto) {
	if (typeof switchto == 'undefined') switchto=true;
	else switchto=evBool(switchto);
	if (switchto===true)
	{
		this.HistoryJS.status=true;
		console.log("BU");
		if (this.HistoryJS.History === false) {
			if (!this.initializeHistoryJS()) this.HistoryJS.status=false;
		}
	} else this.HistoryJS.status=false;
}

/** Initialization functions **/


AjaxNavigator.prototype.initializeHistoryJS = function() {
    this.HistoryJS.History = window.History;
    if ( !this.HistoryJS.History.enabled ) {
		this.HistoryJS.History = false;
		console.log("Not enabled!");
        return false;
    }

	//History.replaceState({id:0}, ConvNavigate.currentNavigation.pageTitle, ConvNavigate.currentNavigation.pageUrl);

    // Bind to StateChange Event
    this.HistoryJS.History.Adapter.bind(window,'statechange',this.historyStateChange);
	return true;
};

AjaxNavigator.prototype.historyStateChange = function() {
	if (this.HistoryJS.manualStateChange)
	{
		this.AjaxHandlar.stopCalls();
		this.back();
	}
}

AjaxNavigator.prototype.confirmDialog = function(data) {
	var confirmation;

	if ((data.cancel === undefined) || (!jQuery.isPlainObject(data.cancel))) data.cancel={ label : 'Cancel', action : null, parameters : new Array() };
	else {
		if (data.cancel.label === undefined) data.cancel.label='Cancel';
		if (data.cancel.action === undefined) data.cancel.action=null;
		if ((data.cancel.parameters === undefined) || (!jQuery.isArray(data.cancel.parameters))) data.cancel.parameters=new Array();
	}

	if ((data.confirm === undefined) || (!jQuery.isPlainObject(data.confirm))) data.confirm={ label: 'Continue', action : null,	parameters : new Array() };
	else {
		if (data.confirm.label === undefined) data.confirm.label='Continue';
		if (data.confirm.action === undefined) data.confirm.action=null;
		if ((data.confirm.parameters === undefined) || (!jQuery.isArray(data.confirm.parameters))) data.confirm.parameters=new Array();
	}


		
	confirmation=new BootstrapDialog({
		title: data.title,
		type: BootstrapDialog.TYPE_DANGER,
        message: data.message,
        closable: false,
        buttons: [
			{
				label: data.cancel.label,
				action: function(dialog) {
						if (data.cancel.action != null)
						{
							data.cancel.parameters.push(dialog);
							if (typeof(data.cancel.action) === "function") data.cancel.action.apply(this, data.cancel.parameters);
							else window[data.cancel.action].apply(this, data.cancel.parameters);
						} else dialog.close();
					}
			}, 
			{
				label: data.confirm.label,
				cssClass: 'btn-primary',
				action: function(dialog) {
						if (data.confirm.action != null)
						{
							data.confirm.parameters.push(dialog);
							if (typeof(data.confirm.action) === 'function') data.confirm.action.apply(this, data.confirm.parameters);
							else window[data.confirm.action].apply(this, data.confirm.parameters);
						} else dialog.close();
				}
			}
		]
	});
	
	confirmation.realize();
	jQuery(confirmation.getModal()).css('margin-top','100px');
	confirmation.open();
}

AjaxNavigator.prototype.startDelete = function(elem, data) {
	var confirm, confirmData;
	
	if (elem===undefined) elem=null;
	if (data===undefined) data=null;

	if ((elem!=null) && (jQuery(elem).attr("data-confirm") !== undefined)) confirmData=JSON.parse(jQuery(elem).attr("data-confirm"));
	else if ((data!=null) && (data.confirm !== undefined)) confirmData=jQuery.extend(true, {}, data.confirm);
	else {
		confirmData=JSON.parse(this.currentNavigation.editData);
		if (confirmData.data.delete === undefined) confirmData={};
		else confirmData=jQuery.extend(true, {}, confirmData.data.delete);
	}


	
	if (confirmData.status === undefined) confirmData.status=true;
	confirm=confirmData.status;

	
	console.log(confirmData);
	console.log(confirm);
	if (confirm)
	{
		this.confirmDialog(confirmData);
	}
}

AjaxNavigator.prototype.startEdit = function() {
	var editData=JSON.parse(this.currentNavigation.editData), navData, navEndData={mobileData: {}};

	if (editData.type=='contact')
	{
		navData={
				pageData: {
					page: 'quickactions',
					module:	'addedit-contact'
				},
				urlData: {
					url: baseUrl+'edit/contact/',
					title: 'Edit Contact'
				}
			}
		
		navEndData['mobileData']['title']='Edit Contact';
		navEndData['mobileData']['menu']=null;
		navEndData['mobileData']['buttons']={
			mobileEditButton : false,
			mobileDeleteButton: false
		}

		this.changePageTitle(jQuery("#addEditContact"),'edit',editData.data['firstname']+" "+editData.data['lastname']);
		ConvNavigate.navigate('openContactEditor',navData, editData.data, null, null, navEndData);
	}
}

AjaxNavigator.prototype.changePageTitle = function(page, variant, addition) {
	var variants, pagetitle='';
	if (page.find('.pagetitle').attr('data-variants') !== undefined) variants=JSON.parse(page.find('.pagetitle').attr('data-variants'));
	else variants=null;

	if ((variants!=null) && ((variant !== undefined) && (variant != null)) && (variants[variant] !== undefined)) pagetitle=variants[variant];
	
	if (addition !== undefined)
	{
		if (pagetitle=='') pagetitle=addition;
		else pagetitle=pagetitle+" - " + addition;
	}
	
	page.find(".pagetitle").find("small").html(pagetitle);
	console.log(pagetitle);
}

AjaxNavigator.prototype.isLoading = function() {
	return ((this.loading.mobileLoading) || (this.loading.desktopLoading));
}

AjaxNavigator.prototype.start = function(navDat, closeMenu) {
	if (closeMenu===undefined) closeMenu=true;
	if (navDat===undefined) navDat=null;

	this.startDesktop(navDat);
	this.startMobile(closeMenu);	
}

AjaxNavigator.prototype.startDesktop = function(navDat) {
	if ((navDat===undefined) || (navDat==null)) return;
	var test1=(this.currentNavigation.pageData.page != navDat.pageData.page) || (this.currentNavigation.pageData.pageid != navDat.pageData.pageid); // page changes
	var test2=(navDat.pageData.page != 'quickactions');
	if (test1 && test2) {
		jQuery("#loadingScreen_full").addClass('loading');
		this.loading.desktopLoading=true;
	}
}

AjaxNavigator.prototype.startMobile = function(closeMenu) {
	if (closeMenu===undefined) closeMenu=true;

	if (closeMenu) jQuery("#navbar_mobile_menu").removeClass("expanded");
	jQuery("#navbar_mobile_menu_button").removeClass('fa-bars').addClass('fa-spin').addClass('fa-spinner');
	this.loading.mobileLoading=true;
}

AjaxNavigator.prototype.stop = function(closeMenu) {
	if (closeMenu===undefined) closeMenu=true;

	this.stopDesktop();
	this.stopMobile();
}

AjaxNavigator.prototype.stopDesktop = function() {
	jQuery("#loadingScreen_full").removeClass("loading");
	this.loading.desktopLoading=false;
}


AjaxNavigator.prototype.stopMobile = function(closeMenu) {
	if (closeMenu===undefined) closeMenu=true;

	if (closeMenu) jQuery("#navbar_mobile_menu").removeClass("expanded");
	jQuery("#navbar_mobile_menu_button").removeClass('fa-spin').removeClass('fa-spinner').addClass('fa-bars');
	this.loading.mobileLoading=false;
}

AjaxNavigator.prototype.setCurrentPage = function(data, push) {
	if ((data === undefined) || (data == null)) {
		var pageData=jQuery("#page-information");
		data=JSON.parse(pageData.attr("data-page"));
	}
	
	var currentPageToSet = jQuery.extend(true, {}, data);
	currentPageToSet=jQuery.extend({}, this.tempNavigation, currentPageToSet);

	if (currentPageToSet.mobileData.title==null) currentPageToSet.mobileData.title=appName;

	this.currentNavigation=jQuery.extend(true, {}, currentPageToSet);
	this.tempNavigation=jQuery.extend(true, {}, this.emptyNavigation);
	console.log("Current page is ", jQuery.extend({},this.currentNavigation.pageData));

	
	if (this.HistoryJS.allowHistoryPushPop)
	{
		if (this.historyData.length > this.currentNavigationId+1) {
			console.log("THIS IS REACHED!");
			this.historyData.splice(this.currentNavigationId+1, this.historyData.length);
		}
		this.historyData.push(currentPageToSet);
		this.currentNavigationId=this.historyData.length - 1;

		if (this.HistoryJS.status)
		{
			var curState=History.getState();
			var urlData={};

			if (currentPageToSet['urlData']) urlData=currentPageToSet['urlData'];

			if (!urlData['title']) urlData['title']=curState.title;
			if (!urlData['url']) urlData['url']=curState.url;
			this.HistoryJS.manualStateChange=false;
			History.pushState({id:this.currentNavigationId}, urlData['title'], urlData['url']);
			this.HistoryJS.manualStateChange=true;
		}
	}
}

AjaxNavigator.prototype.setTempPage = function(data) {
	if ((data === undefined) || (data == null)) {
		var pageData=jQuery("#pageData");
		data=JSON.parse(pageData.attr("data-page"));
	}

	var currentPageToSet = jQuery.extend(true, {}, data);
	currentPageToSet=jQuery.extend({}, this.tempNavigation, currentPageToSet);
	if (currentPageToSet.mobileData.title==null) currentPageToSet.mobileData.title=appName;

	this.tempNavigation=jQuery.extend(true, {}, currentPageToSet);
}

AjaxNavigator.prototype.navigate = function(gotofunc, navDat) {
		if (typeof navDat !== "object") navDat=JSON.parse(stripslashes(String(navDat)));
		//console.log(navDat);
		this.start(navDat);
		closeQuickActions();

		navDat['parameters']=new Array();
		if (arguments.length>2) for (i=2;i<arguments.length ;i++) navDat['parameters'].push(arguments[i]);
		//this.setCurrentPage(navDat, true);
		this.setTempPage(navDat);
		window[gotofunc].apply(this, this.tempNavigation.parameters);
}

AjaxNavigator.prototype.showQuickActionPage = function (pagename, navEndData) {
	jQuery("#"+pagename).addClass("shown");

	this.navigateEnd(navEndData);
}

AjaxNavigator.prototype.spinnerToggle = function(elem) {
	var icon=jQuery(elem).find("i"), container;

	if (icon.length==0)
	{
		container=jQuery("<div></div>").css("display","inline-block").css('padding-left','4px').html(jQuery(elem).html());
		jQuery(elem).html("");
		icon=jQuery(createIcon('spinner', '', 'appendedSpinner'));
		jQuery(elem).append(createIcon('spinner', '', 'appendedSpinner fa-spin'));
		jQuery(elem).append(container);
	}

	if (icon.hasClass('fa-spin'))
	{
		if (icon.attr("data-originalIcon") === undefined) icon.css('display','none');
		else {
			icon.removeClass('fa-spinner');
			icon.addClass(icon.attr("data-originalIcon"));
		}
		icon.removeClass('fa-spin');
	} else {
		if (icon.attr('data-originalIcon') === undefined) icon.css('display','inline-block');
		else {
			icon.removeClass(icon.attr("data-originalIcon"));
			icon.addClass('fa-spinner');
		}
		icon.addClass('fa-spin');
	}
}




AjaxNavigator.prototype.navigateEnd = function(data) {
	this.setMobileNavigation(data);
	this.setCurrentPage(data, true);	
	this.stop();
	this.showMobileBack();
	this.HistoryJS.allowHistoryPushPop=true;
}

AjaxNavigator.prototype.loadPageFromMemory = function (memoryId) {
	var gotoStateFull, gotoState, currentState, sendData;

	gotoStateFull=this.historyData[memoryId];
	gotoState=this.historyData[memoryId].pageData;
	currentState=this.currentNavigation.pageData;

	
	console.log("Current object: ", jQuery.extend({},this));
	console.log("Current page: ", jQuery.extend({},currentState));
	console.log("Going to page: ", jQuery.extend({},gotoState));

	this.HistoryJS.allowHistoryPushPop=false;			
	if (currentState.page=='quickactions')
	{
		if (gotoState.page=='quickactions')
		{
			this.setCurrentPage(gotoStateFull, true);
			this.navigateEnd(gotoStateFull);
		} else {
			closeQuickActions();
			this.setCurrentPage(gotoStateFull, true);
			this.navigateEnd(gotoStateFull);
		}
		//this.setCurrentPage(gotoStateFull);
	}
	else if ((gotoState.page==currentState.page) && (gotoState.pageid==currentState.pageid)) 
	{
		this.navigate('loadSubpage',gotoStateFull,null,gotoState.page,gotoState.module);
	}
	else 
	{
		sendData={module: gotoState.module, moduleid: gotoState.moduleid};
		if (gotoState.page=='contacts') 
		{
			sendData=jQuery.extend(sendData, {id: gotoState.pageid, menu: true});
			this.navigate('loadPage', gotoStateFull, gotoState.page, sendData);
		}
		else if (gotoState.page=='groups') 
		{
			this.navigate('loadGroup',gotoStateFull,gotoState.pageid, sendData);
		}
		else if (gotoState.page=='quickactions')
		{
			if (gotoState.module=='addedit-task')
			{
				console.log("I am here!");
				functionParams=new Array('openTaskEditor', gotoStateFull);
				if (gotoStateFull.parameters.length>0) for (i=0;i<gotoStateFull.parameters.length ;i++ ) functionParams.push(gotoStateFull.parameters[i]);
				this.navigate.apply(this, functionParams);
				console.log(functionParams);
			}
		} else {
			console.log("Back to DASHBOARD");
		}
	}
}


AjaxNavigator.prototype.setMobileNavigation = function(data) {
	if (data['mobileData']) {
		//console.log(data['mobileData']);
		if (data['mobileData']['menu'] !== undefined) {
			if (data['mobileData']['menu'] == null)
			{
				jQuery("#dynamic_mobile_menu").html('');
			} else if (data['mobileData']['menu']!='')
			{
				var mobileMenu=htmlspecialchars_decode(data['mobileData']['menu']);
				jQuery("#dynamic_mobile_menu").html(mobileMenu);
			}
		}

		if (data['mobileData']['title'])
		{
			var mobileTitle=data['mobileData']['title'];
			jQuery("#dynamic_mobile_title").html(mobileTitle);
		}

		if (data['mobileData']['buttons'])
		{
			var mobileButtonHolder=jQuery("#navbar_mobileButtons");
			mobileButtonHolder.find(".mobile-button-holder.pageNavigated").each(function() {
				//console.log(this.id);
				if ((data['mobileData']['buttons'][this.id]) && (data['mobileData']['buttons'][this.id]==true)) jQuery(this).removeClass('hiddenButton');
				else jQuery(this).addClass('hiddenButton');
			});
		}
	}
}

AjaxNavigator.prototype.hideMobileBack = function() {
	jQuery("#mobileBackButton").addClass('hiddenButton');
}

AjaxNavigator.prototype.showMobileBack = function() {
	jQuery("#mobileBackButton").removeClass('hiddenButton');
	
}

AjaxNavigator.prototype.preback = function() {
	if (this.HistoryJS.status==true) window.history.back();
	else {
		this.AjaxHandler.stopCalls();
		this.back();
	}
}

AjaxNavigator.prototype.updateEditData = function (data) {
	var tempEditData;
	
	for (var i=0;i<this.historyData.length;i++)
	{
		if ((this.historyData[i].editData === undefined) || (this.historyData[i].editData == null)) continue;
		tempEditData=JSON.parse(this.historyData[i].editData);
		console.log(tempEditData);
		if (tempEditData.data.id == data.id) {
			tempEditData.data=jQuery.extend(true, {}, data);
			this.historyData[i].editData=JSON.stringify(tempEditData);
		}
	}
}

AjaxNavigator.prototype.getPreviousMainAction = function() {
	var startFrom, goBack=0, found=false;
	
	if (this.HistoryJS.status==true) startFrom=History.getState().data.id;
	else startFrom=this.currentNavigationId;

	while ((!found) && (startFrom>0))
	{
		startFrom--;
		if (this.historyData[startFrom].pageData.page != 'quickactions') found=true;
		goBack--;
	}



	if (this.HistoryJS.status==true) {
		History.go(goBack);
		this.HistoryJS.manualStateChange=false;
		History.back();
		History.pushState({id:startFrom}, this.historyData[startFrom].urlData.title, this.historyData[startFrom].urlData.url);
		this.HistoryJS.manualStateChange=true;
	} else {		
		this.currentNavigationId=startFrom+1;
		this.back();
		for (var i=this.currentNavigationId+1;i<this.historyData.length;i++) delete this.historyData[i];
	}
}

AjaxNavigator.prototype.back = function() {

	if (this.HistoryJS.status==true) this.currentNavigationId=History.getState().data.id;
	else this.currentNavigationId--;
		
	if (this.currentNavigationId==0) this.hideMobileBack();
	this.loadPageFromMemory(this.currentNavigationId);
}

AjaxNavigator.prototype.showMessage = function(type, message, autohide) {
	if (message!==undefined) jQuery("#main_"+type+"_box").find(".box_message").html(message);

	console.log(jQuery("#main_"+type+"_box"));

	jQuery("#main_"+type+"_box").addClass("showThis");
	
	var navigationObject=this;

	setTimeout(function() {
		console.log(navigationObject);
		navigationObject.hideMessage(type);
	},5000);
}

AjaxNavigator.prototype.hideMessage = function(type) {
	jQuery("#main_"+type+"_box").removeClass('showThis');
}
