$(document).ready(function() {
    if(document.getElementById("commentform") != undefined) {
        $("#commentform").submit(function() {
            tinyMCE.triggerSave();
            var data = $(this).serialize();                    
            $.post("/bin/comentario", data, function(json) {                    
                    if(json.error == undefined) {
                        $("#commentHeaderText").fadeIn(800); 
                        $("#commentFooterLine").fadeIn(800);                 
                        $("#comentarios #comentarioT:last").after(json.output);
                        $("#comentarios #comentarioT:last").hide().fadeIn(1500);
                        $("#commentText").val("");
                        tinyMCE.activeEditor.setContent("");
                        var commentCount = $("#comentarios #comentarioT").size() - 1;
                        var commentText = commentCount + (commentCount == 1 ? " Comentario" : " Comentarios");
                        $("#commentCount").text(commentText);
                    } else {
                        $("#commentText").val("");
                        tinyMCE.activeEditor.setContent("");                    
                        alert(json.error);
                    }
                }, "json");
            return false;
        });
    }    

    if(document.getElementById("mercadilloform") != undefined) {
        $("#mercadilloform").submit(function() {
            tinyMCE.triggerSave();
            var data = $(this).serialize();
            $.post("/bin/mercadillo", data, function(json) {
                    if(json.error == undefined) {                    
                        window.location = json.redirect;
                    } else {
                        alert(json.error);
                    }
                }, "json");
            return false;
        });
    }    

    if(document.getElementById("usuarioRegistroForm") != undefined) {        
       var ajaxUpload = new AjaxUpload("upload_button_idX", {
            action: "/bin/upload",
            onSubmit: function(file, extension) {
                var userImage = $("#userImage").val();
                ajaxUpload.setData({action: "user-image", image: userImage});
            },
            onComplete: function(file, response){
                $("#upload_button_idX").css("background", "url(/script/image.php?f=" + response + "&w=120&h=90)");
                $("#userImage").val(response);
            }
            });
        $("#usuarioRegistroForm").submit(function() {
            var result = true;
            result = validateEmail();
            result = validateAlias() && result;
            result = validatePassword() && result;
            if(result) {
                tinyMCE.triggerSave();
                var data = $(this).serialize();
                $.post("/bin/usuario", data, function(json) {
                        if(json.error == undefined) {
                            if(json.redirect != undefined) {
                                window.location = json.redirect;
                            } else {
                                alert(json.redirect);
                            }
                        } else {
                            alert(json.error);
                        }
                    }, "json");
            }
            return false;
        });
    }    
});

function votoComentario(id, type) {
    $.post("/bin/comentario",{action: "vote", id: id, type: type}, function(json) {
            if(json.error == undefined) {
                var selector = "#commentVote_" + id;
                $(selector).text(json.data.value);
            } else {
                alert(json.error);
            }
        }, "json");
    return false;
}

function votoNoticia(id, type) {
    $.post("/bin/noticia",{action: "vote", id: id, type: type}, function(json) {
            if(json.error == undefined) {
                var selector = "#noticiaValor_" + id;
                $(selector).text(json.data.value);
                selector = "#noticiaVotos_" + id;
                var countText = json.data.count + (json.data.count != 1 ? " votos " : " voto ");
                $(selector).text(countText);
            } else {
                alert(json.error);
            }
        }, "json");
    return false;
}

function eliminarComentario(id) {
    $.post("/bin/comentario",{action: "delete", id: id}, function(json) {   
    }, "json");
    return false;
}

function moderarComentario(id) {
    $.post("/bin/comentario",{action: "moderate", id: id}, function(json) {                
    }, "json");
    return false;
}

function seeModerated(id) {
    var selector = "#commentP_" + id;
    $(selector).hide();
    selector = "#commentDiv_" + id;
    $(selector).fadeIn(800);
    return false;
}

function denunciar(id) {
    $.post("/bin/comentario",{action: "advice", id: id}, function(json) {
            if(json.error == undefined) {
                var data = json.output;
		        $(data).modal({
			        position: ["10%",],		
			        overlayId:'form-overlay', 
			        containerId: 'form-container',
			        onOpen: denunciarForm.open,
			        onShow: denunciarForm.show,
			        onClose: denunciarForm.close
		        }); 		                   
            } else {
                alert(json.error);
            }
        }, "json");
    return false;
}

var denunciarForm = {
	message: null,
	open: function (dialog) {
	    dialog.overlay.fadeIn(200);
	    dialog.container.fadeIn(200);
	    dialog.data.fadeIn(200);
	},
	show: function (dialog) {
	    $('#denunciarFormData').submit(function (e) {
	        tinyMCE.triggerSave();
	        tinyMCE.execCommand("mceRemoveControl", true, "motivo");
	        var data = $(this).serialize();
            $.post("/bin/comentario", data, function(json) {
                    if(json.error == undefined) {
	                    dialog.overlay.fadeOut(200);
	                    $.modal.close();                        
                    } else {
                        alert(json.error);
                    }
                }, "json");
            return false;
	    });
	},
	close: function (dialog) {
	    dialog.overlay.fadeOut(200);
	    $.modal.close();
	}
};

function validateEmail() {
    var result = true;
    var email = $("#email").val();
    email = $.trim(email);
    var at = email.lastIndexOf("@");
    if (at < 1 || (at + 1) === email.length)
	    result = false;
    if (/(\.{2,})/.test(email))
	    result = false;
    var local = email.substring(0, at);
    var domain = email.substring(at + 1);
    if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
	    result = false;
    if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
	    result = false;
    if (!/^"(.+)"$/.test(local)) {
	    if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
		   result = false;
    }
    if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
	    result = false;
	if(result == true) {
	    var formAction = $("#action").val();
        $.post("/bin/usuario", {email: email, action: "email", formAction: formAction}, function(json) {
                if(json.msg != "ok") {
                    $("#emailTR").fadeIn(200);
                    $("#emailError").text("La direcci\xf3n de correo ya esta en uso");
                    result = false;
                } else {
                    $("#emailTR").hide();
                }
            }, "json");
    } else {
        $("#emailTR").fadeIn(200);
        $("#emailError").text("La direcci\xf3n de correo no es v\xe1lida");
        result = false;
    }
    return result;
}

function validateAlias() {
    var result = true;
    if($("#action").val() != "upd") {
        var alias = $("#alias").val();
        email = $.trim(alias);
        var local = email;
        if (local.length < 4 || local.length > 16) {
            $("#aliasTR").fadeIn(200);
            $("#aliasError").text("El alias no es v\xe1lido, debe tener entre 4 y 16 caracteres");
	        result = false;
        }
        if (/(^\.|\.$)/.test(local)) {
            $("#aliasTR").fadeIn(200);
            $("#aliasError").text("Seg");
	        result = false;
        }
        if (!/^"(.+)"$/.test(local)) {
	        if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local)) {
                $("#aliasTR").fadeIn(200);
                $("#aliasError").text("Solo se permiten caracteres alfanumericos, ni espacios ni caracteres especiales");
		        result = false;
		    }
        }
        if(result == true) {
            $.post("/bin/usuario", {alias: alias, action: "alias"}, function(json) {
                    if(json.msg != "ok") {
                        $("#aliasTR").fadeIn(200);
                        $("#aliasError").text("El alias ya esta en uso");
                        result = false;
                    } else {
                        $("#aliasTR").hide();
                    }
            }, "json");
       }
   }
   return result;
}

function validatePassword() {
    var result = true;
    if($("#password").val().length < 6) {
        $("#passwordTR").fadeIn(200);
        $("#passwordError").text("Las contrase\u00F1a debe tener entre 6 y 16 caracteres");
    } else {
        if($("#password").val() == $("#password2").val()) {
            $("#passwordTR").hide();
        } else {
            $("#passwordTR").fadeIn(200);
            $("#passwordError").text("Las contrase\u00F1as no coinciden");
            result = false;
        }
    }
    return result;
}

function upload(id) {
    $.post("/bin/upload",{action: "form-show", id: id}, function(json) {
            if(json.error == undefined) {                
                var data = json.output;
		        $(data).modal({
			        position: ["10%",],		
			        overlayId:'form-overlay', 
			        containerId: 'form-container'
		        });		        
		        $("#pbUpload").progressBar({max: 100, width: 220, height: 24, showText: false, boxImage: '/css/images/progressbar.gif', barImage: '/css/images/progressbg_red.gif'});
		        document.forms["postform"].submit();
		        progress();
            } else {
                alert(json.error);
            }
        }, "json");
    return false;
}

function printVar(v) {
    var s = "";
    for(var i in v) {
        s = s + i + ": " + v[i] + "\r\n";
    }
    return s;
}