/**
 * @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 editStr = 'modifier';
var noeditStr = 'mode normal';
var closeStr = 'fermer';
var cancelStr = 'annuler';
var newStr = 'ajouter';
var uploadStr = 'upload';
var adminStr = 'édition avancée';
var helpStr = 'aide';
var helpPath = 'http://fluxoulou.ezoulou.be/aide/';
var statsStr = 'stats';
var imgPath = '/themes/2009/admin/images/';

/* local var : do not edit */
var iframePage = 0;
var zedate = new Date();
var currentPath = window.location.pathname;
var lang = defaultLanguage;
if (currentPath.substring(3,4) == '/') { 
	lang = currentPath.substring(1, 3);	
	currentPath = currentPath.substring(3);	
}

$(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" />');

					// EDIT
					createEditButton();

					//  UPLOAD
					if ($('body.gallery2Plugin .modeGallery').length > 0
							||

							($('body.gallery2Plugin .modeGalleries').length > 0 && $('body.gallery2Plugin .item').length <= 0

							)) {
						createUploadButton();
					}

					//  NEW
					if ($('body.gallery2Plugin .modeGallery').length <= 0 && $('body.blogPlugin').length <= 0) {
						createNewButton();
					}

					// lang??
					/* prevent deleting the homepage and other important pages!! ! */
					if (location.pathname != '/'
							&& location.pathname != contactPath
							&& location.pathname != sitemapPath
							&& location.pathname != searchPath
							&& (location.pathname).indexOf(trashPath)<0
// voir à mettre un bouton delete sur le pages articles du blog
							&& $('body.blogPlugin').length <= 0
					) {
						// DELETE
						createDeleteButton();
					}

					// TOOLS
					$('#admin').append('<div class="tools" />');
					//  stats
					$('#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="popUpMarker"></span></a>');

					//  help
					$('#admin .tools')
							.append(
									'<a class="help popUp" title="'
											+ helpStr
											+ '" href="'+helpPath+'" target="_blank"><img src="'
											+ imgPath
											+ 'help.png" alt="'
											+ helpStr
											+ '" /><span class="popUpMarker"></span></a>');

					//  admin
					$('#admin .tools')
							.append(
									'<a class="admin popUp" title="'
											+ adminStr
											+ '" href="/admin/" target="_blank"><img src="'
											+ imgPath
											+ 'admin.png" alt="'
											+ adminStr
											+ '" /><span class="popUpMarker"></span></a>');

					// in case we have a cookie that means edit was opened
					// before
					if ($.cookie('with_admin') == 'edit') {
						var node = $('#admin .edit');
						displayEdit();
					} else {
						// create default cookie
						$.cookie('with_admin', 'true', {
							path : '/', 
							expires: 999
						});
					}

					
							//$('#content').append('<script src="/webinc/js/bx/i18n.js"> </script>');

							// insert script needed for blog plugin
					var script2 = document.createElement( 'script' );
					script2.type = 'text/javascript';
					script2.src = '/admin/webinc/js/frameset.js';
					document.getElementsByTagName('head')[0].appendChild(script2);

					
					var script = document.createElement( 'script' );
					script.type = 'text/javascript';
					script.src = '/webinc/js/bx/i18n.js';
					document.getElementsByTagName('head')[0].appendChild(script);

					var script3 = document.createElement( 'script' );
					script3.type = 'text/javascript';
					script3.src = '/webinc/js/bx/helpers.js';
					document.getElementsByTagName('head')[0].appendChild(script3);

					var script4 = document.createElement( 'script' );
					script4.type = 'text/javascript';
					script4.src = '/webinc/js/sarissa_0.9.9.4.js';
					document.getElementsByTagName('head')[0].appendChild(script4);
					

					
					
					
					//					$("head").append( script );
//					
					// activate dock effect
					$('#admin').jqDock( {
						align : 'right',
						size : 40,
						labels : 'ml'
					});

				} 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 createEditButton() {
	$('#admin .actions').append(
			'<a class="edit" href="#edit" title="' + editStr + '"><img src="'
					+ imgPath + 'edit.png" alt="' + editStr + '" /></a>');
	$('#admin .edit').click(function() {
		displayEdit();
		$.cookie('with_admin', 'edit', {
			path : '/', 
			expires: 999
		});
		return false;
	});
}

function createNewButton() {
	$('#admin .actions').append(
			'<a class="new" href="#new" title="' + newStr + '"><img src="'
					+ imgPath + 'new.png" alt="' + newStr + '" /></a>');
	$('#admin .new').click(function() {
		displayNew();
		return false;
	});
}

function createUploadButton() {
	$('#admin .actions').append(
			'<a class="upload" href="#upload" title="' + uploadStr
					+ '"><img src="' + imgPath + 'upload.png" alt="'
					+ uploadStr + '" /></a>');
	$('#admin .upload').click(function() {
		displayUpload();
		return false;
	});
}

function createDeleteButton() {
	var path = currentPath.substring(1, currentPath.lastIndexOf('/'));
	var parentPath = path.substring(0, path.lastIndexOf('/'));
//	var trashPath = '/system/trash/';
	// a améliorer un jour : construire le chemin de la poubelle des galleries depuis le chemind ela poublle générale. 
	if ($('body.gallery2Plugin .modeGallery').length > 0) { trashPath = '/system/trash-gallery/'; } 
	
	
	var deleteUrl = '/admin/copy/' + path + '/?to='+trashPath
			+ zedate.getFullYear() + '-' + zedate.getMonth() + '-'
			+ zedate.getDay() + '-' + zedate.getHours() + 'h'
			+ zedate.getMinutes() + '_' + (path.replace(/\//gi, "-"))
			+ '&move=1';
	$('#admin .actions').append(
			'<a class="delete" href="' + deleteUrl + '" title="' + deleteStr
					+ '"><img src="' + imgPath + 'delete.png" alt="'
					+ deleteStr + '" /></a>');
	$('#admin .delete').click(
			function() {
				if (confirm(deleteStr + ' ' + currentPath + '?')) {
					displayDelete(deleteUrl);
					eval("setTimeout(\"window.location = '/" + parentPath
							+ "'\", 500);");
				}
				return false;
			});
}

function displayEdit() {
	var editH = $(window).height() - 333;
	var propertiesH = 130;
	prepareContent();
	
	// link for editing text
	if ($('body.xhtmlPlugin').length > 0) {
		var editUrl = '/admin/edit' + currentPath + '/index.' + lang + '.xhtml?editor=fck';
		$('#content')
				.append(
						'<iframe id="admin_iframe_fckeditor" width="100%" height="' + editH + '" />');
		$('#admin_iframe_fckeditor').attr('src', editUrl).load(function() {
			$(this).contents().find('#save').hide();
		});
		// auto save 
		setInterval('savefckeditor()', 60000);
	} 
	
	else
		// blog
		if ($('body.blogPlugin').length > 0) {
		var editUrl = '/admin/edit' + blogPath + currentPath.substring(currentPath.lastIndexOf('/')+1);
		if (currentPath == blogPath) editUrl = '/admin/edit' + blogPath;
		$('#content')
				.append(
						'<iframe id="admin_iframe" width="100%" height="' + editH + '" />');
		$('#admin_iframe').attr('src', editUrl);
	} else {
		// create new page (translation for example)
		if (isTranslated==false && $('body.gallery2Plugin').length <= 0 && currentPath!=searchPath) {
			$('#content').append('<div class="warning"><h2>Cette page n\'est pas encore traduite.</h2><p>Voulez vous copier la version française et <a href="/" class="next">commencer la traduction</a>?</p></div><br /><br />'); 
			
			$('#content .warning .next').click(function(){
				duplicateDefaultPage();
				return false;
			});

			
		}
	}
	
	
	
	
	
	// collection properties
	if ($('body.blogPlugin').length <= 0 || currentPath == blogPath){
	
	var propertiesUrl = '/admin/properties' + currentPath;
	$('#content')
			.append(
					'<iframe id="admin_iframe_properties" width="100%" height="' + propertiesH + '" />');
	$('#admin_iframe_properties').attr('src', propertiesUrl);
	$('#admin_iframe_properties')
			.load(function() {
				$(this).contents().find('h2').hide();
				$(this).contents().find('span').hide();
				$(this).contents().find('table tr:first').hide();
				$(this).contents().find('#admincontent').css( {
					'padding' : '0 0.5em'
				});
				$(this).contents().find('.bigUglyBorderedEditTable').css( {
					'background-color' : 'white',
					'border' : 0,
					'float' : 'left',
					'margin-top' : '-5px',
					'width' : '90%'
				});
				// $(this).contents().find('#admincontent').css('padding-left',
					// 0);
					$(this)
							.contents()
							.find('input:last')
							.css( {
								'background-color' : '#009CC3',
								'font-size' : '140%'
							})
							.click(function() {
								//  double iframe submit mechanism
									if ($('#admin_iframe_fckeditor').length > 0) {
										savefckeditor();
									} else if ($('body.gallery2Plugin .modeGallery').length > 0) {
										for (i = 0; i < $('#content #gallery iframe').length; i++) {
											// alert($('#content #gallery
											// iframe:eq('+i+')').contents().find('#save'));
											$(
													'#content #gallery iframe:eq(' + i + ')')
													.contents().find('form')
													.submit();
										}
										// return false;
									}

								});
				});
	}
	// edit xhtml content (text) images

	/*
	 * EN CHANTIER... Un jour...
	 * 
	 * if ($('body.xhtmlPlugin').length > 0) { $('#content').append('<div
	 * id="admin_text_images"><h3>This page images</h3></div>');
	 * $('#content_orig img').clone().appendTo('#admin_text_images'); for (i =
	 * 0; i < $('#admin_text_images img').length; i++) { $('#admin_text_images
	 * img:eq(' + i + ')').wrap('<div></div>').parent().append('<br /><a
	 * href="">edit</a> + dynimages ou pas? '); } } else
	 */
	// GALLERY EDITION
	if ($('body.gallery2Plugin .modeGallery').length > 0) {
		$('#gallery').appendTo('#content');
		// avoid double lightbox images in admin mode
		// $('#content_orig #gallery').remove();

		for (i = 0; i < $('#content #gallery .image').length; i++) {
			// classical case : images
			var lightboxLink = $('#content #gallery .image:eq(' + i + ')')
					.find('a.lightbox').attr('href');

			var imgCleanUrl = lightboxLink;
			// remove the dynimages stuff
			if (lightboxLink.indexOf('/dynimages/') >= 0) {
				imgCleanUrl = lightboxLink.substring(lightboxLink
						.indexOf('/dynimages/') + 11);
				imgCleanUrl = imgCleanUrl.substring(imgCleanUrl.indexOf('/'));
			}
			// remove the /files/_galleries/ bit...
			if (imgCleanUrl.indexOf('/files/_galleries/') >= 0) {
				imgCleanUrl = imgCleanUrl.substring(imgCleanUrl
						.indexOf('/files/_galleries/') + 17);
			}

			var deleteUrl = '/admin/copy/files/_galleries' + imgCleanUrl
					+ '?to=/system/trash-gallery/' + zedate.getFullYear() + '-'
					+ zedate.getMonth() + '-' + zedate.getDay() + '-'
					+ zedate.getHours() + 'h' + zedate.getMinutes() + '_'
					+ (imgCleanUrl.replace(/\//gi, "-")) + '&move=true';

			$('#content #gallery .image:eq(' + i + ')')
					.append(
							'<iframe id="admin_iframe'
									+ i
									+ '" width="450" height="160" /><a class="button delete" href="#delete">'
									+ deleteStr
									+ '</a><a class="button edit" href="/admin/edit/'
									+ imgCleanUrl
									+ '?editor=image" target="_blank">'
									+ editStr + '</a>');

			$('#admin_iframe' + i).attr('src',
					'/admin/properties' + imgCleanUrl).load(function() {
				$(this).contents().find('h2, input:last, span').hide();
				$(this).contents().find('.bigUglyBorderedEditTable').css( {
					'background-color' : 'white',
					'border' : 0
				});
			});

			// action for the image delete button

			$('#admin_iframe' + i).parent().find('.button.delete').bind(
					"click", {
						imgCleanUrl : imgCleanUrl,
						deleteUrl : deleteUrl
					}, deleteGalleryImage);

		}

	}

	// happend the close button
	$('#admin .edit').attr('title', noeditStr).addClass('active').click(
			function() {
				$(this).addClass('processing');
				$.cookie('with_admin', 'true', {
					path : '/', 
					expires: 999
				});
				location.reload();
			}).find('img').attr('src', imgPath + 'noedit.png').attr('alt',
			noeditStr);

	$('#admin .actions a:not(".active")').remove();

}

function duplicateDefaultPage() {
	var path = currentPath.substring(1, currentPath.lastIndexOf('/'));
	
	var duplicateUrl = '/admin/copy/'+ path + '/index.' + defaultLanguage + '.xhtml?to=/'+path + '/index.' + lang + '.xhtml&move=0';
	if (defaultLanguage == lang) duplicateUrl = '/admin/copy/system/not-translated/index.' + lang + '.xhtml?to=/'+path + '/index.' + lang + '.xhtml&move=0';
	
	$('#content .warning').hide();
					$('#content').prepend(
	'<iframe id="admin_iframe_fckeditor" width="100%" height="100" />');
	$('#admin_iframe_fckeditor').attr('src', duplicateUrl).load(function() {
		parent.location.reload();
	});
}

function savefckeditor () {
	$('#admin_iframe_fckeditor').contents().find('#save').trigger('click');
}

function deleteGalleryImage(event) {
	if (confirm(deleteStr + ' ' + event.data.imgCleanUrl + '?')) {
		$(this).parent().find('iframe').attr('src', event.data.deleteUrl);
		$(this).parent().fadeIn('2000').fadeOut(function() {
			$(this).remove();
		});
	}
	return false;
}

function displayNew() {
	prepareContent();
	// link for adding a new collection

	var newUrl = '/admin/collection' + currentPath;
	$('#content').append(
			'<iframe id="admin_iframe" width="100%" height="500" />');
	$('#admin_iframe').attr('src', newUrl);
	$('#admin_iframe')
			.load(
					function() {
						if (iframePage == 0) {
							$(this).contents().find(
									'select:first option[value="gallery"]')
									.remove();
							$(this).contents().find(
									'select:first option[value="file"]')
									.remove();
							$(this).contents().find('h2:eq(0), select:first')
									.hide();
							$(this).contents().find('input:first').focus();
						} else if (iframePage == 1) {
							if ($('body.gallery2Plugin', top.document).length > 0) {
								$(this).contents().find('input:first').change(
										function() {
											$(this).parent().find('input:last')
													.trigger('click');
										});
								$(this)
										.contents()
										.find(
												'h2, p:eq(3), p:eq(4), p:eq(5), input:last')
										.hide();
							} else {
								$(this).contents().find(
										'h2, select:eq(2), input:first').hide();
								$(this).contents().find('input:last').focus();
							}
						} else if (iframePage == 2) {
							if ($('body.gallery2Plugin', top.document).length > 0) {
								$(this).hide();
								parent.location.reload();
							}
						}
						iframePage++;
					});

	// happend the close button
	$('#admin .new').attr('title', cancelStr).addClass('active').click(
			function() {
				$.cookie('with_admin', 'true', {
					path : '/', 
					expires: 999					
				});
				location.reload();
			}).find('img').attr('src', imgPath + 'close.png').attr('alt',
			cancelStr);
	$('#admin .actions a:not(".active")').remove();
}

function displayUpload() {
	prepareContent();
	// link for adding a new collection
	var uploadUrl = '/admin/addresource' + currentPath;

	$('#content').append(
			'<iframe id="admin_iframe_archive" width="100%" height="500" />');
	$('#admin_iframe_archive')
			.attr('src', uploadUrl + '?type=archive')
			.load(
					function() {
						if (iframePage == 0) {
							$(this).contents().find('input:first').change(
									function() {
										$(this).parent().find('input:last')
												.trigger('click');
									});
							$(this)
									.contents()
									.find(
											'h2, p:eq(3), p:eq(4), p:eq(5), input:last')
									.hide();
						} else {
							$(this).hide();
							parent.location.reload();
						}
						iframePage++;
					});

	// happend the close button
	$('#admin .upload').attr('title', cancelStr).addClass('active').click(
			function() {
				$.cookie('with_admin', 'true', {
					path : '/', 
					expires: 999
				});
				location.reload();
			}).find('img').attr('src', imgPath + 'close.png').attr('alt',
			cancelStr);
	$('#admin .actions a:not(".active")').remove();
}

function displayDelete(url) {
	prepareContent();
	$('#content').append(
			'<iframe id="admin_iframe" width="100%" height="200" />');
	$('#admin_iframe').attr('src', url).load(function() {
		$(this).contents().find('.error').hide();
	});
}
function displayLogin() {
	prepareContent();
	// link for adding a new collection
	$('#content').append(
			'<iframe id="admin_iframe" width="100%" height="500" />');
	$('#admin_iframe').attr('src', '/admin/').load(function() {
		$(this).contents().find('#top').hide();
		$(this).contents().find('#container').css( {
			'margin' : '0 auto'
		});
		$(this).contents().find('form').submit(function() {
			// $(this).contents().find('input:last')
				$('#admin_iframe').hide();
				setTimeout('parent.location.reload()', 1000);
			});
	});
}

function prepareContent() {
	if ($('#content.with_admin').length > 0) {
		$('#content.with_admin').html('');
	} else {
		$('#content').hide().attr('id', 'content_orig');
		// place a new empty content block
		$('#content_orig').before('<div id="content" class="with_admin"/>');
	}
}