// JavaScript Document
//init delete on lists attachment
function initDeleteFile() {
	$('ul#attachedFileList li a, ul#libraryList li a').click(function(){
		$(this).parent().remove();
		$('.field2 .library a.openPopin, .field2 #postFile').css('visibility','visible');
		$('.field2 #file').removeAttr('disabled');
		return false;
	});
}

function ajaxFileUpload(id){

		$.ajaxFileUpload({
				url:'/handlers/FileUpload.ashx',
				secureuri:false,
				fileElementId:id,
				dataType: 'json',
				success: function (data, status)
				{
					if(data.tooBig=='true'){
						$('#'+id).next().before('<p style="color:red;font-weight:bold">'+l10n.errors.required.EM_SW_19+'</p>')
					} else {
						$('ul#attachedFileList').append('<li><input type="hidden" name="'+data.name+'" value="'+data.value+'" /><span>'+data.filename+'</span><a href="#">'+l10n.text.del+'</a></li>');
						//init delete on lists attachment
						initDeleteFile();
					}
				}
			})
		
		return false;
	}

$(document).ready(function() {
	$('.commentsBlog h4').click(function() {
		if($(this).parent().hasClass('off')){
			$(this).parent().removeClass('off').addClass('on');	
		} else {
			$(this).parent().removeClass('on').addClass('off');	
		}
		if($(this).parent().hasClass('formOn')){
			$(this).parent().removeClass('formOn').addClass('formOff');
		}
	});
		
	$('.commentsBlog .addComment').click(function(){
		if($(this).parent().hasClass('formOff')){
			$(this).parent().removeClass('formOff').addClass('formOn');
		} else {
			$(this).parent().removeClass('formOn').addClass('formOff');
		}
		if($(this).parent().hasClass('on')){
			$(this).parent().removeClass('on').addClass('off');
		}
	});
	
	$('.commentsBlog .reset').click(function(){
		$(this).parents('.formOn').addClass('formOff').removeClass('formOn');									 
	});
	
	//gestion upload file
	$('#postFile').click(function(){
		ajaxFileUpload('file');
		return false;
	});
});

	var ajaxPostForm = function(e,originalEvent) {
		$('div.alert').hide();
		var urlAction = $('#libraryFilterForm').attr('action');
		var getDataForm = $('#libraryFilterForm').serialize();
		originalEvent.preventDefault();
		$.ajax({url: urlAction+'?'+getDataForm, cache: false, success: function(html){
				$(".tableLibrary").html(html);
				ajaxLinkInit();
			}
		});
		return false;
	}
	
	var ajaxLinkInit = function(){
		$('#popinLibrary tfoot a, #popinLibrary .listFauxSelect a, #popinLibrary table thead a').click(function(){
				var urlPopin = $(this).attr('href');
				$.ajax({url: urlPopin, cache: false, success: function(html){
						$(".tableLibrary").html(html);
						ajaxLinkInit();
					}
				});
				return false;
		});
		$('#popinLibrary td.selectContent a').click(function(){
			var href = $(this).attr('href');
			var contentName = href.substring(href.indexOf('contentname=')+12,href.indexOf('&name='));
			var value = href.substring(href.indexOf('&id=')+4,href.length);
			var name = href.substring(href.indexOf('&name')+6,href.indexOf('&id='));
			box.ui('generic.popin').animate({top: 'viewport:before'}, 500, 'close');
			box.ui('generic.pagemask').animate({opacity: 0}, 180, 'close').removeFromDOM();
			$('ul#libraryList').append('<li><input type="hidden" name="'+name+'" value="'+value+'" />'+contentName+'<a href="#">Supprimer</a></li>');
			$('.field2 .library a.openPopin, .field2 #postFile').css('visibility','hidden');
			$('.field2 #file').attr("disabled","disabled");
			return false;
		});
	}
	
    // binding des événements
    box.bind({
		'open.generic.popin.library': function(e) {
			listFauxSelect.init();
			ajaxLinkInit();
				box.ui('form').create({
					element: '#libraryFilterForm'
				}).addReplacement().mustValidate(function(form) {
					form.field('librarySearch').mustValidate(function(field) {
					if(field.isEmpty()) {
						return l10n.errors.required.msg;
					}
				});
					return l10n.errors.form;
			});
			
		},
		'valid.form.libraryFilterForm': ajaxPostForm,
		'close.generic.popin.library': function(e) {
			initDeleteFile();
		}
    });
	$('ul#attachedFileList li a, ul#libraryList li a').click(function(){
		$(this).parent().remove();
		return false;
	});
	//JS Popin Library
	
box.dom(document).ready(function() {
	if(document.getElementById('feelBlogForm')){
	box.ui('form').addPatterns({
		password: /^[a-zA-Z0-9]{6,}$/
	});
	
    box.ui('form').create({
        element: '#feelBlogForm'
    }).mustValidate(function(form) {
		
		form.field('texte').mustValidate(function(field) {
            if(field.isEmpty()) {
                return l10n.errors.required.EM_SW_35;
            }
        });
		
		return l10n.errors.form;
    });
    
    var errorCls = 'error';
    
    var getErrorTarget = function(field) {
        if('radio' != field.type) {
            return field.getLabel();
        } else {
            return field.getElements().parent().parent().prev();
        }
    };
	
	var addErrorIcon = function(field, target) {
		var id = field.name + 'Error';
		var img = box.dom('#' + id);
		if(img.length) {
		  img.attr('alt', field.getError());
		} else {
		  target.append('<span id="' + id + '">- ' + field.getError() + '<br/></span>');
		}
	  };
    
     var addFieldError = function(e) {
		getErrorTarget(e.source).addClass(errorCls);
		var sourceForm = $('#'+e.id).parents('form').attr('id');
		addErrorIcon(e.source, $('#'+sourceForm+' div.alert .content p'));
    };
    
    var removeFieldError = function(e) {
        getErrorTarget(e.source).removeClass(errorCls);
		box.dom('#' + e.source.name + 'Error').remove();
    };
    
    var addFormError = function(e) {
        var id = e.source.id + 'Error';
        //var msg = '<p>' + e.source.msg + '</p>';
		var msg = e.source.msg;
        var error = box.dom('#' + id);
        if(error.length) {
            error.html(msg);
        } else {
			$('#' + e.source.id + ' div.alert').show();
        }
    };
    
    var removeFormError = function(e) {
        box.dom('#' + e.source.id + 'Error').remove();
    };
    
    // binding des événements
    box.bind({
        'error.form': addFormError,
        'valid.form': removeFormError,
        'error.field.text': addFieldError,
		'error.field.select': addFieldError,
        'error.field.radio': addFieldError,
        'error.field.checkbox': addFieldError,
        'valid.field.text': removeFieldError,
		'valid.field.select': removeFieldError,
        'valid.field.radio': removeFieldError,
        'valid.field.checkbox': removeFieldError
    });
	}
});