jQuery(function(){
var store = new Persist.Store('Claromentis Data Store');
_.templateSettings = {
  interpolate : /\{\{=(.+?)\}\}/g,
  evaluate : /\{\{(.+?)\}\}/g,
  escape : /\{\{-(.+?)\}\}/g
};

jQuery.ajaxSetup({cache: true});

var MainRouter = Backbone.Router.extend({
	routes: {
		"list": "defaultRoute",
		"list/:folder_id?:getQuery": "list",
		"list/:folder_id": "list",
		"checkedout": "checkedout",
		'drafts': 'drafts',
		'approvals': 'approvals',
		"bookmarks": "bookmarks",
		"trashcan": "trashcan",
//		"search/:folder_id/*keywords": "search",
//		"workflow": "workflow",
		"*path": "defaultRoute"
	},

	defaultRoute: function () {
		var folder_id = 0;
		folder_id = store.get('docs_folder_id');
		this.list(folder_id);
	},

	list: function (folder_id) {
		// folder_id can contains GET request
		folder_id = (folder_id > 0 ? folder_id : 0);
		var url = '#list/' + folder_id;

		if (Modernizr.history) { // Uses html5 history if available.
			window.history.replaceState(folder_id, null, url);
		}
		else {
			window.location.hash = url;
		}

		docs_list_state.set({'folder_id': folder_id});
        docs_list_state.set({'sort_by': 0});

		$('.js-select-all').prop('checked', false);
		views_manager.show('list');
	},

	// checkedout: function () {
		// views_manager.show('checkedout');
	// },

	approvals: function () {
		views_manager.show('approvals');
	},

	bookmarks: function () {
		views_manager.show('bookmarks');
	},

	drafts: function () {
		views_manager.show('drafts');
	},

	trashcan: function () {
		views_manager.show('trashcan');
	} /*,

	search: function (folder_id, keywords) {
		//console.log('Searching for '+ keywords + ' in folder ' + folder_id);
		search_view.setParams(folder_id, keywords);
		views_manager.show('search');
	}*/

});


// main model that stores the current state of documents list
var DocsListStateModel = Backbone.Model.extend({
	defaults: { folder_id: null }
});


@import(src/ViewsManager.js);


@import(src/DocsListViewBase.js);

@import(src/DocsListViewMain.js);

@import(src/DocElementModel.js);
@import(src/DocsCollection.js);

@import(src/UISettings.js);
@import(src/Permission.js);
@import(src/breadcrumb.js);

@import(src/ListActionsView.js);
@import(src/InfoMenuActionsView.js);
@import(src/StdNavigationView.js);


@import(src/CheckedOutModel.js);
@import(src/CheckedOutCollection.js);
@import(src/CheckedOutView.js);

@import(src/DraftsModel.js);
@import(src/DraftsCollection.js);
@import(src/DraftsView.js);

@import(src/ApprovalsModel.js);
@import(src/ApprovalsCollection.js);
@import(src/ApprovalsView.js);

@import(src/BookmarkModel.js);
@import(src/BookmarksCollection.js);
@import(src/BookmarksView.js);


@import(src/SearchFormModel.js);
@import(src/SearchFormView.js);
/*@ import(src/SearchResultElementModel.js);
@ import(src/SearchCollection.js);
@ import(src/SearchView.js);*/

@import(src/SelectedDocsCollection.js);
@import(src/DashboardActionsView.js);

@import(src/DashboardActionBase.js);
@import(src/dashboard_actions.js);

@import(src/ClipboardCollection.js);
@import(src/ClipboardActionsView.js);
@import(src/ClipboardView.js);

@import(src/TrashCanModel.js);
@import(src/TrashCanCollection.js);
@import(src/TrashCanView.js);
@import(src/TrashCanSelectedCollection.js);
@import(src/TrashCanActionsView.js);
@import(src/TrashCanMenuActionsView.js);

@import(src/AsideView.js);

var oldsync = Backbone.sync;
Backbone.sync = function(method, model, options) {
	//console.log(method, model, options);
	oldsync(method, model, options);
};

$(".main-content-block").hide();

var docs_list_state = new DocsListStateModel();

// these are always visible
var ui_settings = new UISettingsModel();
ui_settings.setDocsListStateModel(docs_list_state);
var navigationView = new StdNavigationView();
navigationView.setDocsListStateModel(docs_list_state);
list_actions = new ListActionsView();
list_actions.setDocsListStateModel(docs_list_state);

var search_form = new SearchFormView();

// preloading bookmarks
bookmarks = new BookmarksCollection();
bookmarks.reset(docs_list_preload_data['bookmarks']);

aside_view = new AsideView();
clipboard_docs = new ClipboardCollection();
aside_view.setClipboardCollection(clipboard_docs);

var checkedout_view = new CheckedOutView();
checkedout_view.collection.reset(docs_list_preload_data['checkedout'], {silent: true});
checkedout_view.collection.is_loaded = true;

drafts_view = new DraftsView();
drafts_view.collection.reset(docs_list_preload_data['drafts'], {silent: true});
drafts_view.collection.is_loaded = true;

approvals_view = new ApprovalsView();
approvals_view.collection.reset(docs_list_preload_data['approvals'], {silent: true});
approvals_view.collection.is_loaded = true;

// as draft and approvals views are inside a drafts panel, we need to hide it if they become empty.
refreshDraftViews = function(){
	$('#drafts_listings').hide();
	drafts_view.collection.fetch({reset:true});
	approvals_view.collection.fetch({reset:true});
}


// creating switchable views and storing them in views manager
list_view = new DocsListViewMain();
list_view.setModel(docs_list_state);

var bookmarks_view = new BookmarksView();
bookmarks_view.setCollection(bookmarks);

var trashcan_view = new TrashCanView();
trashcan_view.collection.reset(docs_list_preload_data['trashcan']);
trashcan_view.collection.is_loaded = true;
navigationView.setTrashCanCollection(trashcan_view.collection);

var views_manager = new ViewsManager();
views_manager.addView('bookmarks', bookmarks_view);
views_manager.addView('list', list_view);
views_manager.addView('trashcan', trashcan_view);
//views_manager.addView('search', search_view);

// adding reaction on setting checkboxes
$('.documentList').on('change', "input[name=selected_doc]", function(event){
	views_manager.getActiveView().onCheckbox($(event.currentTarget).val(), $(event.currentTarget).prop('checked'));
});

// list type switch
$("#documentViewSize").find("a").click(function() {
	var view_mode = $(this).data("view-mode");
	$(this).addClass("active").siblings().removeClass("active");
	$(".documentLayout").attr("class", "documentLayout " + $(this).data("set-class"));
	if (views_manager.getActiveView())
		views_manager.getActiveView().setViewMode(view_mode);

	$.post('/intranet/documents/ajax_server.php?action=docs_view', {view: view_mode});
	return false;
});

// sorting the documents by title/date
const SORT_TITLE_ASC = 0;
const SORT_TITLE_DESC = 1;
const SORT_DATE_LAST_MODIFIED_ASC = 2;
const SORT_DATE_LAST_MODIFIED_DESC = 3;

// react on sorting button click
const btnSortNameSelector = document.querySelector('button.js-sort-name');
const btnSortDateSelector = document.querySelector('button.js-sort-date');

btnSortNameSelector.addEventListener('click', function () {
    this.classList.add('active');
    btnSortDateSelector.classList.remove('active');

    if (docs_list_state.attributes.sort_by === SORT_TITLE_ASC)
        docs_list_state.set({'sort_by': SORT_TITLE_DESC});
    else
        docs_list_state.set({'sort_by': SORT_TITLE_ASC});
});

btnSortDateSelector.addEventListener('click', function () {
    this.classList.add('active');
    btnSortNameSelector.classList.remove('active');

    if (docs_list_state.attributes.sort_by === SORT_DATE_LAST_MODIFIED_ASC)
        docs_list_state.set({'sort_by': SORT_DATE_LAST_MODIFIED_DESC});
    else
        docs_list_state.set({'sort_by': SORT_DATE_LAST_MODIFIED_ASC});
});

var main_router = new MainRouter();

@import(functions.js);

// Infinite scroll. Request checking if "load next" block is in view on every scroll event
$(window).on("load", function() {
	$(window).scroll(function() {
		if ($('#load_next_trigger').is(':visible'))
		{
			var docEnd = $(document).height() - $(window).height();
			if ($(window).scrollTop() >= docEnd - 200)
			{
				$('#load_next_trigger').trigger('loadNextIsInView');
			}
		}
	});
});

// Check all hook
$('.js-select-all').change(function() {
	var check = $(this).prop('checked');
	$.each($('input[name=selected_doc]'), function(index, item) {
		$(item).prop('checked', check).change();
	});
});

// Show actions menu when clicked on a document/folder area
$(".documentLayout").on("click", '.documentItem', function(event) {
	var doc_node = $(event.currentTarget);
	if (doc_node.parent().size() == 0) // this happens if docs list is being redrawn and this node is already detached
		return;

	if (event.target.tagName == 'A' || $(event.target).parents('a').size() > 0 || event.target.tagName == 'INPUT')
	{
		doc_node.parent().children().removeClass("open").find(".dropdown-menu").hide();
	} else
	{
		if (!doc_node.hasClass('open'))
		{
			doc_node.addClass("open").trigger("showMenu");
			//views_manager.getActiveView().onCheckbox($(event.currentTarget).val(), $(event.currentTarget).prop('checked'));
		} else {
			doc_node.removeClass('open').find(".dropdown-menu").hide();
		}
		doc_node.siblings().removeClass("open").find(".dropdown-menu").hide();
	}
});


//// MODAL MOVE WINDOW

// close modal move window
$(document).on("click", ".close, .modalCover", function() {
	$("#modalMove").fadeOut();
});

// toggle selected document folder
$(".documentLocationPicker").on("click", "a", function() {
	if(!$(this).hasClass("ui-icon") || $(this).hasClass("home")) {
		$(".documentLocationPicker").find("li.selected").removeClass("selected");
		$(this).parent().parent().addClass("selected");
		$("#confirm").attr("disabled", "");
		//			$.uniform.update("#confirm");
	} else {
		// toggle child folders
		$(this).parent().parent().toggleClass("active");
	}
	return false;
});
var modalMove = {
	self : $("#modalMove"),
	show : function(ui) {
		$(modalMove.self).fadeIn();
	}
};

$(document).ready(function() {
	checkedout_view.setVisible(true);
	approvals_view.setVisible(true);
	drafts_view.setVisible(true);
	var docs_view = docs_list_preload_data['docs_view'];
	// @todo don't click
	$("#documentViewSize").find('a[data-view-mode="' + docs_view + '"]').click();

});

Backbone.history.start();
if (views_manager.getActiveView() === undefined)
	main_router.list();

// end of DOMready
});


function hideTooltips()
{
	// hide tooltips on click to prevent problems with 'orphan' tooltips that
	// can't be removed after their elements have been removed from the DOM
	$('body a[rel="tooltip"]').tooltip('hide');
}

