//var g_cheminAsyncCms = g_urlMiVersionCms + 'async/';
var g_cheminAsyncCms = g_webroot + 'async/';
var encoursDestX;
var mvt = false;
var mediapoTimeoutId = false;
var mediapoLargVign = 50;
var g_ready = false;
var g_msgZzz = '';
var ie=document.all;
var g_paramsAsyncCms = {codeAppli: g_codeAppli, cmsEnv: g_cmsEnv};
popBoxShowRevertBar = false;
popBoxShowRevertImage = false;
popBoxShowRevertText = false;
popBoxShowCaption = false;

function fo_cheminMedia(cat, id, f) {
	return 'fm.php?cat=' + cat + '&id=' + id + '&f=' + f; 
} 

function miEncoderUrl(u) {
	u = u.replace(/\?/g, '%3F');
	u = u.replace(/=/g, '%3D');
	u = u.replace(/&/g, '%26');
	return u
}

function cmsFichierUpload(e) {
	var $fi = $(e);
	var fn = $fi.val();
	var ts = new Date().getTime();
	var types = $fi.attr('types');
	if (types != '' && types != 'all') {
		if (types == 'img') {
			types = 'jpg|jpeg|png|gif|bmp|tif|tiff|xbm|xpm';
		}
		var aTypes = types.split('|');
		var typeOk = false;
		for ( var i = 0; i < aTypes.length; i++) {
			var re = new RegExp('\.' + aTypes[i] + '$', 'i');
			if (fn.match(re)) {
				typeOk = true;
				break;
			}
		}
		if (!typeOk) {
			alert("Type de fichier non accepté :\nLes extensions permises sont "
					+ aTypes.join(', ') + ".");
			return false;
		}
	}
	var $fs = $fi.parents('.fichierSaisie:first');
	$fs.find('.encours').show();
	$fi.hide();
	$.ajaxFileUpload( {
				url : g_cheminAsyncCms + 'upload.php',
				ts : ts,
				args : {
					ts : ts,
					idx : $fi.attr('idx'),
					dest : $fi.attr('dest'),
					maxSize : $fi.attr('maxSize'),
					types : types
				},
				secureuri : false,
				fileElementId : $fi.attr('id'),
				dataType : 'json',
				success : function(data, status) {
					//zzz(status);
					//zzz(data);
					$fs.find('.encours').hide();
					if (typeof (data.error) != 'undefined'
							|| data.msg != 'ok') {
						if (data.error != '') {
							$fs.find('.erreur').html('- Erreur : ' + data.error).show();
						} else {
							$fs.find('span.filename').html(data.fileName + " (" + Math.ceil(data.fileSize / 1024) + " ko)");
							$fs.find('input.vpost').val(data.dest);
							$fs.find('a.cmsFichierEnlever').attr('fic', data.dest).attr('cle', data.cle);
							$fs.find('.fichier:first').show();
							$fs.find('.fichierBtn:first').hide();
						}
					}
				},
				error : function(data, status, e) {
					alert(e);
				}
			});
	return false;
}

function cmsFichierEnlever(e) {
	var $e = $(e);
	$.post(g_cheminAsyncCms + 'supprimerFichier.php', { _fic: $e.attr('fic'), _cle: $e.attr('cle') });
	var $fs = $e.parents('.fichierSaisie:first');
	$fs.find('span.filename').html('');
	$fs.find('input.vpost').val('');
	$e.attr('fic', '');
	$fs.find('.fichier:first').hide();
	$fs.find('.fichierBtn:first').show().find('input[type=file]').show();
	return false;
}

function cmsFormValider(elt, formCode) {
	var $f = $('form[name=cmsForm_' + formCode + ']');
	var ok = true;
	$f.find('.obligatoire').each(function(i, e) {
		var $e = $(e);
		if ($e.find('input:checkbox').length > 1) {
			// liste de cases à cocher
			var coche = false;
			$e.find('input:checkbox').each(function(i2, e2) {
				if ($(e2).is(':checked')) coche = coche || true;
			});
			if (!coche) ok = false;
		} else if ($e.val().length == 0) {
			ok = false;
			$e.addClass('cmsFormSaisieErr').focus(function() { $(this).removeClass('cmsFormSaisieErr').parents('.cmsFormChamp:first').removeClass('cmsFormSaisieErr'); })
				.parents('.cmsFormChamp:first').addClass('cmsFormSaisieErr');
		}
	});
	if (ok) {
		$(elt).attr('onclick', '').click(function() {return false;}).css('opacity', 0.25).parents('.cmsFormValider:first').find('.cmsFormEncours').show();
		$f.submit();
	} else {
		alert("Tous les champs obligatoires doivent être renseignés.\nMerci de compléter et de valider à nouveau.");
	}
	return ok;
}

function zzz(s, src) {
	if (!src || src == undefined) {
		src = "js";
	}
	var msg = '<p class="' + src + '">' + src + '&gt;&nbsp;' + (typeof s == 'object' ? bao_toString(s) : s) + '</p>';
	if (g_ready) {
		$("#console").prepend(msg);
	} else {
		g_msgZzz = msg + g_msgZzz;
	}
}

function bao_toString(o){
    var parse = function(_o){
        var a = [], t;
        for(var p in _o){
            if(_o.hasOwnProperty(p)){
                t = _o[p];
                if(t && typeof t == "object"){
                    a[a.length]= p + ":{ " + arguments.callee(t).join(", ") + "}";
                }
                else {
                    if(typeof t == "string"){
                        a[a.length] = [ p+ ": \"" + t.toString() + "\"" ];
                    }
                    else{
                        a[a.length] = [ p+ ": " + (t && t.length ? t.toString() : "") ];
                    }
                }
            }
        }
        return a;
    }
    return "{" + parse(o).join(", ") + "}";
}

function fo_initPage($o) {
	var $o = $o ? $o : $('body');
	
	// charger les swf
	$o.find('.cmsFlashContent').each(function(i, e) {
		var id = $(e).attr('id').replace('flashcontent_', '');
		var f = $(e).attr('f');
		var l = $(e).attr('l');
		var h = $(e).attr('h');
		var v = $(e).attr('v');
		v = (!v || v == 'undefined') ? '7' : v;
		var p = $(e).attr('p');
		p = (!p || p == 'undefined') ? '' : p;
		var so = new SWFObject(f,"ply",l,h,v,"#ffffff");
		if (p != '') {
			var params = p.replace('?', '').replace(/\s/g, '').split(';');
			for (var i=0; i<params.length; i++) {
				var param = params[i].split('=');
				so.addVariable(param[0], param[1]);
			}
		}
		so.addParam("wmode", "transparent");
		so.write($(e).parents(':first')[0]);
	});
	
	// charger les flv
	$o.find('.cmsVideoContent').each(function(i, e) {
		var $e = $(e);
		var f = miEncoderUrl($e.attr('f'));
		var ext = $e.attr('ext');
		var fn = $e.attr('fn');
		var l = $e.attr('l');
		var h = $e.attr('h');
		var ia = miEncoderUrl($(e).attr('src'));
		var autostart = $(e).attr('autostart');
		var id = $(e).attr('id').replace('videocontent_', '');
		if (ext == 'm4v') {
			$e.hide();
			var fic = g_webroot + $(e).attr('f');
			var ia = g_webroot + $(e).attr('src');
			var htm = '<div id="jp_container_' + id + '" class="jp-video jp-video-360p" style="height:' + h + 'px;width:' + l + 'px;">'
					+ '<div class="jp-type-single">'
					+ '<div id="jquery_jplayer_' + id + '" class="jp-jplayer"></div>'
					+ '<div class="jp-gui">'
					+ '	<div class="jp-video-play">'
					+ '		<a href="javascript:;" class="jp-video-play-icon" tabindex="1">play</a>'
					+ '	</div>'
					+ '	<div class="jp-interface">'
					+ '		<div class="jp-progress">'
					+ '			<div class="jp-seek-bar">'
					+ '				<div class="jp-play-bar"></div>'
					+ '			</div>'
					+ '		</div>'
					+ '		<div class="jp-current-time"></div>'
					+ '		<div class="jp-duration"></div>'
					+ '		<div class="jp-title">'
					+ '			<ul>'
					+ '				<li>' + $(e).attr('title') + '</li>'
					+ '			</ul>'
					+ '		</div>'
					+ '		<div class="jp-controls-holder">'
					+ '			<ul class="jp-controls">'
					+ '				<li><a href="javascript:;" class="jp-play" tabindex="1">play</a></li>'
					+ '				<li><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li>'
					+ '				<li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li>'
					+ '				<li><a href="javascript:;" class="jp-mute" tabindex="1" title="mute">mute</a></li>'
					+ '				<li><a href="javascript:;" class="jp-unmute" tabindex="1" title="unmute">unmute</a></li>'
					+ '				<li><a href="javascript:;" class="jp-volume-max" tabindex="1" title="max volume">max volume</a></li>'
					+ '			</ul>'
					+ '			<div class="jp-volume-bar">'
					+ '				<div class="jp-volume-bar-value"></div>'
					+ '			</div>'
					+ '			<ul class="jp-toggles">'
					+ '				<li><a href="javascript:;" class="jp-full-screen" tabindex="1" title="full screen">full screen</a></li>'
					+ '				<li><a href="javascript:;" class="jp-restore-screen" tabindex="1" title="restore screen">restore screen</a></li>'
					+ '				<li><a href="javascript:;" class="jp-repeat" tabindex="1" title="repeat">repeat</a></li>'
					+ '				<li><a href="javascript:;" class="jp-repeat-off" tabindex="1" title="repeat off">repeat off</a></li>'
					+ '			</ul>'
					+ '		</div>'
					+ '	</div>'
					+ '</div>'
					+ '<div class="jp-no-solution">'
					+ '	<span>Update Required</span>'
					+ '	To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>.'
					+ '</div>'
					+ '</div>'
					+ '</div>';
			$e.after(htm);
			$("#jquery_jplayer_" + id).jPlayer({
				errorAlerts: false,
				error: function (ev) {
					zzz("jplayer error : type=" + ev.type);
				},
				warningAlerts: false,
				warning: function (ev) {
					zzz("jplayer warning : type=" + ev.type);
				},
				ready: function () {
					// ne fonctionne pas sur Opera pour fic = ... getfic.php...
					if (g_cmsEnv == 'prod') {
						fic = g_webroot + 'media/cmsvideo/' + id + '/' + fn;
					} else {
						fic = g_urlMiVersionCms + '../../intranets/' + g_codeAppli + '/documents/cmsvideo/' + id + '/' + fn;
					}
					//zzz("ready! fic=" + fic);
					$(this).parent().find('.jp-no-solution').hide();
					$(this).jPlayer("setMedia", { m4v: fic, poster: ia });
					if (autostart) {
						$(this).parent().find('.jp-interface').hide();
						$(this).jPlayer('play');
						//$(this).parent().find('.jp-gui a.jp-play').click();
					}
				},
				cssSelectorAncestor: '#jp_container_' + id,
				swfPath: g_urlMiVersionCms + 'jquery',
				supplied: 'm4v',
				size: {
					width: l + "px",
					height: h + "px",
					cssClass: "jp-video-360p"
				},
				ended: function() {
					if (g_codeAppli == 'cms2' || g_codeAppli == 'delane') {
						setTimeout(function() { window.location.href = 'http://www.delanesi.com'; }, 1000);
					}
				}
			});
		} else {
			var so = new SWFObject("flvplayer.swf","ply",l,h,"8","#ffffff");
			var flashvars = "file=" + f + "&amp;autostart=" + autostart + "&amp;screencolor=dddddd&amp;bufferlength=5&amp;image=" + ia;
			so.addParam("flashvars", flashvars);
			so.addVariable("type","flv");
			so.addParam("wmode", "transparent");
			so.write($(e).parent()[0]);
		}
	});
	
	// activer jplayer pour les fichiers audio
	$o.find('img.audioContent').each(function(i, e) {
		var id = $(e).attr('id').replace('audio_', '');
		var titre = $(e).attr('title').replace(/_/g, ' ');
		var fn = $(e).attr('fn').replace(/_/g, ' ');
		//var fic = $(e).attr('f').replace('../../..', 'http://localhost/mon-intranet');
		var fic = g_webroot + $(e).attr('f');
		$(e).after('<div id="jquery_jplayer_' + id + '" /><div id="jp_container_' + id + '" class="jp-audio jp-mini">'
			+ '<div class="jp-type-single">'
			+ '	<div class="jp-gui jp-interface">'
			+ '		<ul class="jp-controls">'
			+ '			<li><a href="javascript:;" class="jp-play" tabindex="1">play</a></li>'
			+ '			<li><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li>'
//			+ '			<li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li>'
//			+ '			<li><a href="javascript:;" class="jp-mute" tabindex="1" title="mute">mute</a></li>'
//			+ '			<li><a href="javascript:;" class="jp-unmute" tabindex="1" title="unmute">unmute</a></li>'
//			+ '			<li><a href="javascript:;" class="jp-volume-max" tabindex="1" title="max volume">max volume</a></li>'
			+ '		</ul>'
//			+ '		<div class="jp-progress">'
//			+ '			<div class="jp-seek-bar">'
//			+ '				<div class="jp-play-bar"></div>'
//			+ '			</div>'
//			+ '		</div>'
//			+ '		<div class="jp-volume-bar">'
//			+ '			<div class="jp-volume-bar-value"></div>'
//			+ '		</div>'
			+ '		<div class="jp-title">'
			+ '			<div class="jp-time-holder">'
//			+ '				<div class="jp-current-time"></div>'
//			+ '				<div class="jp-duration"></div>'
			+ '				<ul class="jp-toggles">'
			+ '					<li><a href="javascript:;" class="jp-repeat" tabindex="1" title="Jouer en boucle">repeat</a></li>'
			+ '					<li><a href="javascript:;" class="jp-repeat-off" tabindex="1" title="repeat off">Ne pas jouer en boucle</a></li>'
			+ '				</ul>'
			+ '			</div>'
			+ '		' + titre + (fn != titre ? '<br />' + fn : '') + '</div>'
			+ '	</div>'
			+ '	<div class="jp-no-solution">'
			+ '		<span>Mise à jour nécessaire</span>'
			+ '		Pour écouter ou voir le média proposé vous devez utiliser une version plus récente de navigateur ou installer le <a href="http://get.adobe.com/flashplayer/" target="_blank">plugin Flash</a>.'
			+ '	</div>'
			+ '</div>'
			+ '<div class="cleaner"></div>'
			+ '</div>');
		$('#jquery_jplayer_' + id).jPlayer({
			ready: function (event) {
				var autostart = false;
				//zzz("ready fic=" + fic);
				$(this).jPlayer("setMedia", {
					mp3: fic
				});
				if (autostart) $(this).jPlayer('play');
			},
			cssSelectorAncestor: '#jp_container_' + id,
			swfPath: g_urlMiVersionCms + 'jquery',
			supplied: 'mp3',
			wmode: 'window'
		});
		$(e).hide();
	});
	
	$o.find('img[pbsrc]').addClass('PopBoxImageSmall');
	
	$o.find('.stylerPremierDernier').children(':first').addClass('premier').end().children(':last').addClass('dernier').length;
}

function fo_menuDeroule() {
	$('#menu .menuDeroule > li').mouseenter(function() { $(this).addClass('menuItemSurvol').find('.ssmenu').show(); })
		.mouseleave(function() { $(this).removeClass('menuItemSurvol').find('.ssmenu').fadeOut('fast'); });
}

function fo_initFormRechSite() {
	$('input#cmsInputRechSite').keyup(function(ev) {
		if (ev.keyCode == 13 && $(this).val().length) {
			$(this).parents('form:first').submit();
		}
	})
}

function fo_initListesAlternees() {
	$('#page .cmsListeAlt .items').children().each(function(i, e) {
		$(e).addClass(i % 2 == 0 ? 'paire' : 'impaire');
	});
}

function fo_initBoiteLien() {
	$('a.lienBoite').each(function(i, e) {
		var $a = $(e);
		var u = $a.attr('href');
		if (u.length > 1) {
			$a.parents('.boiteLien:first')
				.mousedown(function() { window.location.href = u; })
				.mouseover(function() { $(this).addClass('survol'); })
				.mouseout(function() { $(this).removeClass('survol'); });
		}
	});	
}

$(document).ready(function() {
	g_ready = true;
	$('#console').html(g_msgZzz.length > 0 ? g_msgZzz : g_codeAppli + ", webroot=" + g_webroot + ", version=" + g_version + ", urlMiVersionCms=" + g_urlMiVersionCms + " : prêt!").css('opacity', 0.85).click(function() {
		$(this).css('width', ($(this).width() > 20 ? '10px' : '320px'));
		$(this).css('height', ($(this).height() > 20 ? '10px' : '160px'));
	});
	g_msgZzz = "";
	fo_initPage();
	fo_menuDeroule();
	fo_initFormRechSite();
	fo_initListesAlternees();
	fo_initBoiteLien();
	
	// custom
	if (g_codeAppli == 'av05') {
		var h = $('body').height();
		var $e = $('#fond');
		if ($e.length) {
			var hf = $e.height();
			if (h > hf) {
				var dh = h - hf; 
				$e.height(h);
				// déplacer aussi le pied en augmentant la taille de la page
				var hp = $('#corpsPage').height();
				$('#corpsPage').height(hp + dh);
			}
		}
	}
});
