$.url = function(url) {
    return $("meta[name='Identifier-URL']").attr('content')+url.substr(1);
}

var fileCounter = 0;
var max_attachments = 6;

$(document).ready(function() {
    $("#divGoogleMaps").hide();
    $("#divGoogleMapsDescription").hide();
    $('#ClassifiedParentSectionId').val('');
    $('#ClassifiedStateId').val('');
    $("#change").click(function(){
        $("#sec").attr("src", $.url('/classifieds/captcha/' + Math.round(Math.random(0)*1000)+1));
        return false;
    });

    $("#ClassifiedPrice").format({precision: 2,decimal:',',autofix:true});

    $("#button3").click(function(){
        if (tinyMCE){
            tinyMCE.triggerSave();
        }
        if ($("#ClassifiedCaptcha").valid()){
            if($("#ClassifiedAddForm").valid()) {
                $.blockUI({
                    message: '<h1>Procesando su clasificado...</h1>'
                });
            }
        }
    });

    $("#ClassifiedAddForm").validate({
        rules: {
            "data[Classified][captcha]": {
                required: true,
                remote: $.url('/classifieds/verifyCaptcha/')
            }
        },
        messages: {
            "data[Classified][captcha]": {
                remote: 'El código debe ser igual a la imágen'
            }
        },
        //onkeyup: true,
        errorElement: 'span',
        errorClass: 'error-field',
        errorContainer: $('div.container')

    });


    //Uploads
    var template = jQuery.format($("#template").val());
    function addFile() {
        if (fileCounter >= max_attachments) {
            $("#add").css({
                background:"#FFE0BF"
            });
            $("#add").attr('disabled','disabled');
        } else {
            fileCounter++;
            $(template(fileCounter)).appendTo("#items tbody");
        }
    }
    addFile();
    $("#add").click(addFile);


	$("#url_videos").blur(function (){
        olink = $("#url_videos").val();
        $("#oembed").replaceWith("<div id='oembed'></div>");
        $("#oembed").oembed(olink, {embedMethod: "replace", maxWidth: 500, maxHeight: 400}, function(container, oembed) {
            container.replaceWith("<div id='oembed'>" + oembed.code + "</div>");
        });
    });

     //run the currently selected effect
    function runEffect(element, effect){
        $(element).show(effect);
    }

    function hideEffect(element, effect){
        $(element).hide(effect);
    }

    //set effect
    $("#googleMaps").click(function(){
		//Si es internet explorer 6 no habilita google maps
		if($.browser.msie && $.browser.version=="6.0") {return false};
			if ($('#ClassifiedCityId').val() > 0){
				runEffect("#divGoogleMaps", "blind");
				runEffect("#divGoogleMapsDescription", "blind");
				//Trabaja con el archivo maps.init.js donde se parametriza el mapa a utilizar
                var typeClassified = "add";
				updateMaps(typeClassified);
			}else{
				$("#ClassifiedStateId").focus();
				$.blockUI({ message: "Seleccione una provincia y una localidad antes de utilizar el mapa", css: {'font-size':'20px', 'width': '350px', 'height': '55px' }, overlayCSS: { backgroundColor: '#000' } });
				setTimeout($.unblockUI, 2000);
			}
    });

    //set effect from select menu value
    $("#cerrarGoogleMaps").click(function() {
        hideEffect("#divGoogleMaps", "blind");
        hideEffect("#divGoogleMapsDescription", "blind");
        clearLatitudeLongitude();
        return false;
    });

});

$(function() {
    $('#ClassifiedParentSectionId').chainSelect('#ClassifiedSectionId',$.url('/classifieds/loadSubsection/'),
    {
        before:function (target) //before request hide the target combobox and display the loading message
        {
            $(target).attr('disabled',true);
            $('#ClassifiedParentSectionId').attr('disabled',true);

            $("#LoadingDiv").css("display","block");
            $(target).css("display","none");

        },
        after:function (target) //after request show the target combobox and hide the loading message
        {
            $(target).attr('disabled',false);
            $('#ClassifiedParentSectionId').attr('disabled',false);

            $("#LoadingDiv").css("display","none");
            $(target).css("display","inline");
            //Se selecciona por defecto una opción con una leyenda
            $(target + " option[selected]").removeAttr("selected");
            $(target + " option[value='']").attr("selected", "selected");
        }
    });

    $('#ClassifiedStateId').chainSelect('#ClassifiedCityId',$.url('/cities/loadCity/'),
    {
        before:function (target) //before request hide the target combobox and display the loading message
        {
            $(target).attr('disabled',true);
            $('#ClassifiedStateId').attr('disabled',true);

            $("#LoadingDiv").css("display","block");
            $(target).css("display","none");
            //Se oculta google maps
            $("#divGoogleMaps").hide();
            $("#divGoogleMapsDescription").hide();
            clearLatitudeLongitude();
        },
        after:function (target) //after request show the target combobox and hide the loading message
        {
            $(target).attr('disabled',false);
            $('#ClassifiedStateId').attr('disabled',false);

            $("#LoadingDiv").css("display","none");
            $(target).css("display","inline");
            //Se selecciona por defecto una opción con una leyenda
            $(target + " option[selected]").removeAttr("selected");
            $(target + " option[value='']").attr("selected", "selected");
        }
    });
    
    $("#ClassifiedCityId").change(function(){$("#divGoogleMaps").hide();clearLatitudeLongitude();});

});
$(function() {
    $(".popupwindow").popupwindow();
});
function deleterow(id){
    if (fileCounter != 1) {
        $("#row-"+id).remove();
        if (fileCounter <= max_attachments) {
            $("#add").css({
                background:"#FF931F"
            });
            $("#add").removeAttr("disabled");
        }
        fileCounter--;
    }
}
