jQuery(function() {
	_.templateSettings = {
		interpolate : /\{\{=(.+?)\}\}/g,
		evaluate : /\{\{(.+?)\}\}/g,
		escape : /\{\{-(.+?)\}\}/g
	};
	jQuery.ajaxSetup({cache: true});
});

$(document).ready(function() {
	var MainRouter = Backbone.Router.extend({
		routes : {
			"!/preview" : "preview",
			"preview/:name" : "componentView",
			"!/properties" : "properties",
			"!/permissions" : "permissions",
			"export-transfer" : "exportTransfer",
			"!/view-schedule" : "viewSchedule",
			"set-reminder" : "setReminder",
			"!/audit" : "audit",
			"!/version-history" : "versionHistory",
			"!/review-history" : "reviewHistory",
			"!/workflow" : "workflow",
			"comment-tab" : "commentTab",
			"*path" : "defaultRoute"
		},

		defaultRoute : function() {
			this.preview();
		},
		preview : function() {
			injectIframe('.dropdown-menu, #notification_list, .navbar-fixed-top');

			views_manager_main.show('preview');
			if (doc_components && doc_components[0] && doc_components[0]['download_pdf_link'])
				$('#component_download_pdf').show().attr('href', doc_components[0]['download_pdf_link']);
			else
				$('#component_download_pdf').hide();
		},
		componentView : function(name) {
			views_manager_main.show('component');
			$('#preview_' + name).show().siblings().hide();
			if (doc_components && doc_components[name] && doc_components[name]['download_pdf_link'])
				$('#component_download_pdf').show().attr('href', doc_components[name]['download_pdf_link']);
			else
				$('#component_download_pdf').hide();
		},
		properties : function() {
			$('#edit_details').empty();
			views_manager_main.show('edit-details');
			xajax_show_edit_document_dialog(doc.doc_id, doc.version, doc.parent_id, 'edit_details');
		},
		permissions : function() {
			views_manager_main.show('permissions');
			perms_dialog_show(doc.doc_id, doc.aggregation, doc.parent_id, doc.version, reload_window);
		},
		viewSchedule : function() {
			views_manager_main.show('edit-schedule');
			xajax_show_schedule_dialog(doc.obj_id, doc.aggregation, 'schedules');
		},
		exportTransfer : function() {
			$('#editTransfer').modal('toggle');
		},
		setReminder : function() {
			$('#setReminder').modal('toggle');
		},
		audit : function() {
			views_manager_main.show('audit');
			xajax_show_erms_audit(doc.doc_id, doc.obj_type, doc.version, 'audit_log');
		},
		versionHistory : function() {
			views_manager_main.show('version');
			xajax_show_document_versions(doc.doc_id, doc.parent_id, doc.version, 'version_log');
		},
		reviewHistory : function() {
			views_manager_main.show('review-history');
			xajax_show_review_history_dialog(doc.obj_id, doc.aggregation, 'review_history');
		},
		workflow : function() {
			views_manager_main.show('workflow');
			xajax_show_workflow_dialog(doc.doc_id, doc.parent_id, doc.version, doc.workflow_id);
		},

		commentTab : function() {
			$('#comment-tab').parent().siblings().removeClass(activeTabClass);
			$('#comment-tab').parent().addClass(activeTabClass);
			views_manager_aside.show('comment-tab');
		}
	});


	@import(src/ViewsManager.js);
	var views_manager_main = new ViewsManager();
	var views_manager_aside = new ViewsManager();

	@import(src/DocsDetailsViews.js);
	var details_preview_view = new DetailsPreviewView();
	var details_component_view = new DetailsComponentView();
	var details_edit_view = new DetailsEditView();
	var details_permissions_view = new DetailsPermissionsView();
	var details_edit_schedule = new DetailsEditSchedule();
	var details_set_reminder_view = new DetailsSetReminderView();
	var details_audit_view = new DetailsAuditView();
	var details_version_veiw = new DetailsVersionView();
	var details_review_history_veiw = new DetailsReviewHistoryView();
	var details_workflow_veiw = new DetailsWorkflowView();
	views_manager_main.addView('preview', details_preview_view);
	views_manager_main.addView('component', details_component_view);
	views_manager_main.addView('permissions', details_permissions_view);
	views_manager_main.addView('edit-details', details_edit_view);
	views_manager_main.addView('edit-schedule', details_edit_schedule);
	views_manager_main.addView('set-reminder', details_set_reminder_view);
	views_manager_main.addView('audit', details_audit_view);
	views_manager_main.addView('version', details_version_veiw);
	views_manager_main.addView('review-history', details_review_history_veiw);
	views_manager_main.addView('workflow', details_workflow_veiw);

	@import(src/DocsTabsViews.js);
	var tab_overview_view = new TabOverviewView();
	var tab_meta_view = new TabMetaView();
	var tab_comment_view = new TabCommentView();
	views_manager_aside.addView('overview-tab', tab_overview_view);
	views_manager_aside.addView('comment-tab', tab_comment_view);

	@import(src/breadcrumb.js);

	var activeTabClass = 'active';

	$('#overview-tab').click(function() {

		$('#comment-tab').removeClass(activeTabClass);
		$('#overview-tab').addClass(activeTabClass);
		views_manager_aside.show('overview-tab');
		return false;
	});

	$('#comment-tab').click(function() {
		$('#overview-tab').removeClass(activeTabClass);
		$('#comment-tab').addClass(activeTabClass);
		views_manager_aside.show('comment-tab');
		return false;
	});

	$('#md5CheckVerify').click(function() {
		checkMD5Signature(false, doc.doc_id, doc.title);
		return false;
	});

	// checkout button in "check out" modal dialog
	$('#btnDocumentCheckout').click(function() {
		if (doDocumentCheckout(doc.doc_id, doc.parent_id)) {
			$('#documentCheckoutDialog').modal('toggle');
			$('#documentCheckinIcon').show();
			$('#documentCancelCheckoutIcon').show();
			$('#checkedOutDisplayIcon').show();
			$('#documentCheckoutIcon').hide();
            $('#documentRenewIcon').hide();
		}
	});

	$('body').on('show.bs.modal', '.modal', function() {
		injectIframe(this);
	});

    var DETAILS_STORAGE_KEY = 'showDetails';
    var panel = document.querySelector('.document-panel-details');
    var toggleDetailsButton = document.querySelector('.js-toggle-details');

    function getState() {
        return localStorage.getItem(DETAILS_STORAGE_KEY) === 'true';
    }

    function setState(state) {
        localStorage.setItem(DETAILS_STORAGE_KEY, String(state));
    }

    function render(state) {
        if (!panel) return;

        if (state) {
            panel.classList.add('is-visible');
            toggleDetailsButton.setAttribute("aria-expanded", "true");
        } else {
            panel.classList.remove('is-visible');
            toggleDetailsButton.setAttribute("aria-expanded", "false");
        }
    }

    function toggleDetails() {
        state = !state;
        setState(state);
        render(state);
    }

    var state = getState();
    render(state);

    // Use requestAnimationFrame to ensure it's after paint
    requestAnimationFrame(function () {
        panel.classList.add('is-ready');
    });

    toggleDetailsButton.addEventListener('click', toggleDetails);

	var main_router = new MainRouter();

	Backbone.history.start();
	if(views_manager_main.getActiveView() === undefined)
		main_router.preview();

});
@import(functions.js);
var show_stop_monitoring = function() {
    $('a[name=stop_monitoring_link]').show();
    $('a[name=start_monitoring_link]').hide();
    $('a[name=start_monitoring_once_link]').hide();
    $('.js-monitoring-badge').show()
};
var show_start_monitoring = function() {
	$('a[name=stop_monitoring_link]').hide();
	$('a[name=start_monitoring_link]').show();
	$('a[name=start_monitoring_once_link]').show();
    $('.js-monitoring-badge').hide();
};

var approveDocument = function(doc_id) {
	if (confirm(lmsg('documents.misc.doc_approve_confirm'))){
		var url = '/intranet/rest/documents/document/' + doc.doc_id + '/' + doc.version + '/approve/?parent_id=' + doc.parent_id;
		$.ajax({
			type: 'PUT',
			url: url,
			success: function(data){
				reload_window(lmsg('documents.misc.doc_approve_success'));
			},
			error: function(jqXHR, message, thrown){
				cla.showMessage(message, '', true);
			}
		});
	}
};

var reuploadDocument = function(){
	xajax_show_reupload_dialog(doc.doc_id, doc.parent_id);
};

var deleteDocument = function() {
	if (confirm(lmsg('documents.details.deleting_whole_doc_and_all_versions'))) {
		$.ajax({
			url : '/intranet/rest/documents/document/' + doc.doc_id + '?parent_id=' + doc.parent_id,
			type : 'delete',
			success : function(data, status, jqXJR) {
				var loc = '/intranet/documents/#list/' + doc.parent_id;
				if (doc.draft_in_progress)
				{
					loadPageWithMessage(loc, lmsg('documents.delete_with_draft.success'));
				}
				else
				{
					loadPageWithMessage(loc, lmsg('documents.delete.success'));
				}

			},
			error : function(jqXHR, message, thrown) {
				cla.showMessage(message, '', true);
			}
		});
	}
};
var deleteDocumentSingle = function() {
		$.ajax({
			url : '/intranet/rest/documents/document/' + doc.doc_id + '?parent_id=' + doc.parent_id,
			type : 'delete',
			success : function(data, status, jqXJR) {
				var loc = '/intranet/documents/#list/' + doc.parent_id;
				if (doc.draft_in_progress)
				{
					loadPageWithMessage(loc, lmsg('documents.delete_with_draft.success'));
				}
				else
				{
					loadPageWithMessage(loc, lmsg('documents.delete.success'));
				}

			},
			error : function(jqXHR, message, thrown) {
				cla.showMessage(message, '', true);
			}
		});
};

var deleteDocumentVersion = function(version) {
	if (confirm(lmsg('documents.details.confirm_delete_version'))) {
		$.ajax({
			url : '/intranet/rest/documents/document/' + doc.doc_id + '/' + version + '?parent_id=' + doc.parent_id,
			type : 'delete',
			success : function() {
				// prevent error when trying to display docs where sole version has been deleted
				var loc = '';
				if (doc.total_versions > 1)
				{
					loc = '/intranet/documents/' + doc.parent_id + '/' + doc.doc_id;
				}
				else
				{
					loc = '/intranet/documents/#list/' + doc.parent_id;
				}
				if (doc.is_draft)
				{
					loadPageWithMessage(loc, lmsg('documents.misc.doc_delete_success'));
				}
				else
				{
					loadPageWithMessage(loc, lmsg('documents.common.version_deleted'));
				}

			},
			error : function(jqXHR, message, thrown) {
				cla.showMessage(message, '', true);
			}
		});
	}
};
var deleteDocumentLink = function() {
    jQuery.ajax({
        url : '/intranet/rest/documents/document/' + doc.doc_id + '?parent_id=' + doc.parent_id,
        type : 'delete',
        success : function() {
            var loc = '/intranet/documents/#list/' + doc.parent_id;
			loadPageWithMessage(loc, 'documents.delete.success');
        },
        error : function(jqXHR, message, thrown) {
            cla.showMessage(message, '', true);
        }
    });
}
var checkMD5Signature = function(component_id, document_id, title) {
	var url = component_id ? '/intranet/documents/ajax/check_md5.php?component_id=' + component_id : '/intranet/documents/ajax/check_md5.php?document_id=' + document_id;
	$.ajax({
		url : url + '&title=' + title,
		success : function(data) {
			if(data.equalsig) {
				jQuery('#md5CheckVerified').show();
				jQuery('#md5CheckFailed').hide();
				jQuery('#md5CheckVerify').hide();
			} else {
				jQuery('#md5CheckFailed').show();
				jQuery('#md5CheckVerified').hide();
				jQuery('#md5CheckVerify').hide();
			}
		},
		error : function(jqXHR, message, thrown) {
			cla.showMessage(message, '', true);
		}
	});
};

var deleteDialog = function() {
	var data = {};
	data.mode = 'details';
    data.is_document_link = is_document_link;
    data.title = doc.title;
	data.version_count = doc.total_versions;
	$('#delete-files').empty();
	var deleteControls = _.template($('#deleteTemplate').html())(data);
	$('#delete-files').append(deleteControls);
	$('#deleteDocument').modal('toggle');
	$('#deleteConfirm').click(function() {
		var delete_type = $('input[name=delete_type]:checked').val();
        var mode = delete_type !== undefined ? delete_type : jQuery('#deleteDocumentLink').val();

		switch(mode) {
			case '0' :
				deleteDocumentVersion(doc.version);
				break;
			case '1' :
				deleteDocument();
				break;
            case '2' :
                deleteDocumentLink();
                break;
			default :
				if (doc.total_versions === 1)
				{
					deleteDocumentSingle();
				}else {
					$('#deleteDocument').modal('toggle');
					cla.showMessage(lmsg('documents.details.delete_type_not_sel'), '', true); // Delete type not selected
				}

				break;
		}
	});
}

var onReminderSet = function(datetime, message) {
	if (datetime.length > 0)
	{
		$('#reminder_date_time').text(datetime);
		$('#reminder_display').show();
	} else
	{
		$('#reminder_display').hide();
	}
	$('#setReminder').modal('hide');
	cla.showMessage(message, '', 'info');
}

var cancelCheckout = function(doc_id) {
	if (confirm(lmsg('documents.details.cancel_checkout_confirm'))){
		var url = '/intranet/rest/documents/checkin/' + doc_id;
		$.ajax({
			type: 'delete',
			url: url,
			success: function(data){
				cla.showMessage(lmsg('documents.details.doc_checkout_cancelled'), '', 'info');
				$('#documentCancelCheckoutIcon').hide();
				$('#documentCheckinIcon').hide();
				$('#checkedOutDisplayIcon').hide();
				$('#checkedOutDisplay').hide();
				$("#documentCheckoutIcon").show();
				$("#documentRenewIcon").show();
			},
			error: function(jqXHR, message, thrown){
				cla.showMessage(message, '', true);
			}
		});
	}
};

var bookmarkToggle = function(bookmarked) {
	if (bookmarked) {
		$('#addBookmarkIcon').show();
		$('#removeBookmarkIcon').hide();
	} else {
		$('#addBookmarkIcon').hide();
		$('#removeBookmarkIcon').show();
	}
};

var doDocumentCheckout = function(document_id, parent_id) {
	var include_file = !$('#no_download').prop('checked');
	var url = '/intranet/rest/documents/checkout/' + document_id + '/?parent_id=' + parent_id;
	$.ajax({
		type : 'post',
		url : url,
		success : function(data) {
			cla.showMessage(lmsg('documents.details.doc_checked_out'), '', 'info');
		},
		error : function(jqXHR, message, thrown) {
			cla.showMessage(message, '', true);
			return false;
		}
	});
	if (include_file === true)
	{
		url = '/intranet/documents/view.php?action=download&doc_id=' + document_id + '&parent_id=' + parent_id;
  		$("body").append("<iframe src='" + url+ "' style='display: none;' ></iframe>");
	}
	return true;
};


function show_error(message)
{
	edit_document_show_error(message);
}
function edit_document_show_error(message)
{
	cla.showMessage(message, '', true);
}
function start_edit(content)
{
	var el = jQuery('#middle_area_block');
	el.html(content);
}
function reload_window(message)
{
	window.location.href = '/intranet/documents/' + doc['parent_id'] + '/' + doc['doc_id'] + '/?message=' + encodeURIComponent(message);
}
function show_doc_preview_block()
{
	window.location.hash = '#preview';
	return false;
}

function perms_dialog_show(id, aggregation, parent_id, version_num)
{
	jQuery('#edit_permissions').empty();
	xajax_load_perms_dialog(id, aggregation, parent_id, version_num, 'edit_permissions', '');
	return false;
}
function perms_dialog_hide()
{
	window.location.hash = '#preview';
	return false;
}
function perms_dialog_success(message)
{
	perms_dialog_hide();
	cla.showMessage(message);
}

function injectIframe(elem) {
	if($('html').hasClass('ie')) {
		var iframe = document.createElement('iframe');
		iframe.className = 'cover';
		iframe.src = 'about:blank';

		$(elem).append(iframe);
	}
}

function loadPageWithMessage(location, message)
{
	var param = encodeURIComponent(message);
	var message_section = '';

	if (location.indexOf('?') == -1)
	{
		message_section = '?message=' + param;
	}
	else
	{
		message_section += '&message=' + param;
	}

	var hash_loc = location.indexOf('#');

	if (hash_loc > -1)
	{
		var first_part = location.substr(0, hash_loc);
		var second_part = location.substr(hash_loc);
		location = first_part + message_section + second_part;
	}
	else
	{
		location += message_section;
	}

	window.location.replace(location);
}


function getVisibleIframe() {
    var els = document.querySelectorAll('.document-preview__iframe');

    for (var i = 0; i < els.length; i++) {
        if (els[i].offsetParent !== null) {
            return els[i];
        }
    }

    return null;
}

function setFullScreenMode(doc) {
    if (!document.fullscreenElement && doc) {
        doc.requestFullscreen();
    } else {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        }
    }
}
