/**
 * @author florent
 * 
 * fluxcms admin 4 frontend
 */

var adminContainer = 'body';

var loginStr = 'login';
var processingStr = 'en cours';
var finishedStr = 'terminé';
var deleteStr = 'supprimer';
var trashStr = 'poubelle';
var backupStr = 'archiver';
var editStr = 'modifier';
var saveStr = 'enregistrer';
var noeditStr = 'mode normal';
var closeStr = 'fermer';
var cancelStr = 'annuler';
var newStr = 'ajouter';
var uploadStr = 'upload';
var settingsStr = 'Réglages du site';
var helpStr = 'aide';
var helpPath = 'http://fluxoulou.ezoulou.be/aide/';
var statsStr = 'statistiques de visite';
var imgPath = pathTheme+'admin/images/';
var autoSave = 0;
var propertiesH = 130;


/* local var : do not edit */
var iframePage = 0; // increment each time the main iframe is loaded
var zedate = new Date();
var currentPath = window.location.pathname; // we use this instead of collectionUri bacause of teh case of the error pages... 
//var lang = defaultLanguage;
if (currentPath.substring(3,4) == '/') {
//	lang = currentPath.substring(1, 3);	
	currentPath = currentPath.substring(3);	
}

//var currentPath = collectionUri;

$(document).ready(function() {

			// THE body has an admin class (written by xsl) -> the user is
				// currently logged.
				if ($('body.with_admin').length > 0) {
					// write the admin block
					$(adminContainer).prepend('<div id="admin" />');

					//  ACTIONS
					$('#admin').append('<div class="actions" />');

					if ($('body.pageNotFound').length <= 0) {
						
						// EDIT	
						if ($('body.gallery2Plugin .mode_error').length <= 0) {
							createEditButton();
						}
	
						//  UPLOAD
						if ($('body.gallery2Plugin .mode_gallery').length > 0) {
							createUploadButton();
						}
	
						//  NEW
						if (currentPath != pathSearch && 
								currentPath != pathSitemap  && 
								lang == defaultLanguage && (
								$('body.gallery2Plugin').length <= 0  || $('body.gallery2Plugin').length > 0 && (
									$('body.gallery2Plugin .mode_galleries:not(.mode_error)').length > 0
									|| 
									$('body.gallery2Plugin .mode_gallery.mode_error').length > 0
								)
							)) {
							createNewButton();
						}
	
						if ($('body.gallery2Plugin .mode_gallery.mode_error').length > 0) {
							// in case of gallery error, we hide the errror page and display a nice friendly message
							displayEmptyGalleryWelcome();						
						}
	
						
						// lang??
						/* prevent deleting the homepage and other important pages!! ! */
						if (location.pathname != pathHome
							&& location.pathname != '/'+lang+pathHome
							&& location.pathname != '/'+lang+'/'
							&& location.pathname != '/'
							&& currentPath != pathSearch 
							&& currentPath != pathSitemap
							&& (location.pathname).indexOf(pathTrash)<0
							&& $('body.gallery2Plugin .mode_error:not(.mode_gallery)').length <= 0 
							&&  $('body.pageNotFound').length<=0
							&& $('body.blogPlugin').length <= 0
						) {
							// DELETE
							createDeleteButton();
						}
					}

					// BACKUP -- une idée...
// createBackupButton();

					// TOOLS
					$('#admin').append('<div class="tools" />');
					//  stats
					
					
					
					createSettingsButton();

					
					if (googleId != '') {
						$('#admin .tools').append('<a class="stats popup" title="' +
						statsStr +
						'" href="https://www.google.com/analytics/reporting/?id=' +
						googleAnalyticsProfile +
						'" target="_blank"><img src="' +
						imgPath +
						'stats.png" alt="' +
						statsStr +
						'" /><span class="marker popup"></span></a>');
					}
					
					// in case we have a cookie that means edit was opened
					// before
					if ($.cookie('with_admin') == 'edit' && $('body.gallery2Plugin .mode_error').length <= 0 &&  $('body.pageNotFound').length<=0) {
						// var node = $('#admin .edit');
						displayEdit();
					} else {
						// create default cookie
						$.cookie('with_admin', 'true', {
							path : '/', 
							expires: 999
						});
					}
					
					// activate dock effect
					$('#admin').jqDock( {
						labels : false,
						align : 'right',
						size : 40/*,
						labels : 'ml'*/
					});
					
					
			
					// allow edition of the footer
					//displayEditFooter();

					// allow edition of the blog on homepage
//					if (location.pathname == pathHome) displayEditBlog();					
				} else {
					// IN CASE the user HAS BEEN Logged in the past.
					if ($.cookie('with_admin')) {
						$(adminContainer).prepend(
								'<div id="admin"><a class="login" href="/admin/" title="'
										+ loginStr + '">' + loginStr
										+ '</a></div>');
						$('#admin .login').click(function() {
							displayLogin();
							return false;
						});

					}
				}
			});


//function fixSarisa() {
////	if ($('#content.with-admin').length > 0) {
//	    i18n = new bx_i18n(null);
//	    
//	    // load the xml translations using sarissa
//	    var oDomDoc = Sarissa.getDomDocument();
//	    oDomDoc.async = true;
//	
//	    function i18nLoaded() {
//	        if(oDomDoc.readyState == 4) {
//	            if(oDomDoc.documentElement) {
//	                i18n.xml = oDomDoc;
//	                i18n.init();
//	            }
//	        }
//	    }
//	    oDomDoc.onreadystatechange = i18nLoaded;
//	    oDomDoc.load('i18n/js.xml');
////	}
//}


function displayLogin() {

	if ($('body.with_admin').length > 0) {
		alert('Vous êtes déjà connecté! Les outils d\'édition se situent à droite ->');
	}
	else {

		$.cookie('with_admin', 'true', {
			path : '/', 
			expires: 999
		});
		var contentNode = getContentNode();
		contentNode = prepareContentNode(contentNode);
		// link for login page
		contentNode.append('<iframe id="admin_iframe" width="90%" height="350" />');
		$('#admin_iframe').attr('src', '/admin/').load(function(){
			$(this).contents().find('#top, legend, #container p:first, #container label:first, #container label:eq(3), #container input[type="checkbox"], #container #pwd + br , #container label:last').hide();
			$(this).contents().find('#container').css({
				'margin': '3em auto 0 auto'
			});
			$(this).contents().find('#container p').css({
				'text-align': 'center'
			});
			$(this).contents().find('#container label').css({
				'width': '40%',
				'padding-right' : '2%', 
				'text-align' : 'right'
			});
			$(this).contents().find('#container fieldset').css({
				'border': '0'
			});
			$(this).contents().find('label ').css( {
				'font-size' : '140%'
			});
			niceLargeTextfield($(this).contents().find('input[type=text], input[type=password]'));
			niceLargeButton($(this).contents().find('input[type="submit"]')); 

			$(this).contents().find('.version').css( {
				'margin-top' : '0'
			});
			$(this).contents().find('form').submit(function(){
				$('#admin_iframe').hide();
				setTimeout('parent.location.reload()', 1000);
			});
		});
	}
	return false;
}


function getContentNode () {
	var contentNode = $('#content'); 
	if ($('#page').length>0) contentNode = $('#page')
//	if ($('#gallery').length>0) contentNode = $('#gallery')
	return contentNode;
}

function prepareContentNode(node) {
	if (node.hasClass('with_admin')) {
		node.html('');
	} else {
		var origId = node.attr('id');
		var origClass = node.attr('class');
		node.hide().attr('id', origId+'_orig');
		$('#'+origId+'_orig').before('<div id="'+origId+'" class="'+origClass+' with_admin"/>');
		$('#'+origId+'_orig .pathnav').appendTo('#'+origId);
	}
	return $('#'+origId);
}



function niceLargeButton(node) {
	node.css( {
		'background-color' : '#009CC3',
		'border':'2px solid #006486',		
		'color' : 'white',
		'cursor': 'pointer',
		'-moz-border-radius': '5px',
		'font-size' : '140%'
	});
}
function niceNormalButton(node) {
	node.css( {
		'background-color' : '#006486',
		'border':'1px solid #009CC3',
		'color' : 'white',
		'cursor': 'pointer',
		'-moz-border-radius': '3px',
		'font-size' : '100%'
	});
}
function niceTitle(node) {
	node.css( {
		'background-color' : '#ccc',
		'border':'0',
		'color' : 'black',
		'-moz-border-radius': '5px',
		'font-size' : '140%',
		'font-style':'normal',
		'padding':'5px'
	});
}
function niceLargeTextfield(node) {
	node.css( {
		'background-color' : 'white',
		'border':'2px solid #666',
		'color' : 'black',
		'-moz-border-radius': '5px',
		'font-size' : '140%'
	});
}
function niceNormalTextfield(node) {
	node.css( {
		'background-color' : 'white',
		'border':'1px solid #666',
		'color' : 'black',
		'-moz-border-radius': '3px',
		'font-size' : '100%'
	});
}
function niceNormalLabel(node) {
	node.css({
		'text-align' : 'right'
	});
}

function niceAjaxTxt(node) {
	node.css ({
		'background-color':'white',
		'border':'0',
		'color':'#777',
		'float':'right'
	});
}
