// JavaScript Document

if (window.console == null) window.console = { log: function(p) { }, error: function(p) { } };

var self, mens, actions;

Actions = function() {
    self = this;

    self.init()
}
Actions.fn = Actions.prototype;
Actions.fn.extend = jQuery.extend;
Actions.fn.extend(
{
    init: function() {
        self.content = $("#content");
        self.verif = 0;
        self.masked($("div.subscribe, div.virtualCapsule", self.content));
        self.limit($(".counter", self.content));
        self.pngFix();

        $(".musicaSend").length
    	    && self.prepareUploadMusica();

        $("div.main.validate", this.content).length
			&& self.validate()

        $("div.login input").resetDefaultValue();

        if ($("div.main").length)
            $("#content").addClass("bg-" + $.trim($("#content div.wrapper").attr("class").replace(/wrapper/gi, "")));
        // Botao voltar
        $(".bt_back").click(function() {
            window.history.back()
        });

        // Ver regulamento
        $(".bt_regulation").click(function() {
            $.modal.show();
            $("div.modal.modalRegulation").modal(function() {
                $("div.modal.modalRegulation").fadeIn();
            });

            return false;
        });

//        if ($("div.virtualCapsule").length) {
//            $("a.bt_seek").click(function() {
//                $("input[type=text]", "div.virtualCapsule").each(function() {
//                    this.value == "Busca por palavra-chave"
//						&& (this.value = "");
//                });

//                __doPostBack('ctl00$ContentPlaceHolder1$lkbBuscar', '');

//                return false;
//            });
//        }

        if ($(document).getUrlParam && $(document).getUrlParam("categoria")) {
            $("div.box." + $(document).getUrlParam("categoria"))
		            .addClass("active")
		            .siblings("div.box:visible").removeClass("active");

            $("ul.themes li a.active").removeClass("active");
            $("ul.themes li." + $(document).getUrlParam("categoria") + " a").addClass("active");
        }

        $("div.box:not(:visible) :input").attr("disabled", "disabled");

        $("ul.themes li a").click(function() {
            var $this = $(this),
		            currentClass = $(this).parent().attr("class").split(" ")[0];

            $this.addClass("active");

            $("a.active", $this.parent().siblings("li")).removeClass("active");

            $("div." + currentClass)
    	            .addClass("active")
		            .siblings(".active").removeClass("active").end()
		            .find(":input").removeAttr("disabled");

            $("div.box:not(:visible) :input").attr("disabled", "disabled");

            $("label.error").remove();

            return false;
        });

        $(".musicaCadastrada").length
            && self.playerMusic($(".musicaCadastrada", self.content));

        $(".reviews li", $("virtualCapsule"))
    	    && $(".reviews li:first, .reviews li:last").removeClass("borderTopBottom").addClass("borderBottom");

        $(".uploadImage").length
            && self.prepareUploadFoto();

        // Arruma lista de Jurados
        $("div.jurors").length && $("div.poetry li:last").removeClass("borderBottom");

        DD_roundies && $.browser.msie && $.browser.version < 7
    		&& DD_roundies.addRule('.main,.roundedEdge,ul.inscribedParts li,div.regulation div,div.main div.contAccess', '4px');

        if ($("body.home").length) {


            setTimeout(function() {
                if ($(document).width() < 800)
                    window.scrollTo(0, 265);

                else if ($(document).width() < 1020)
                    window.scrollTo(0, 465);
            }, 2500);
        }

        if ($('.seekKeyword').length) {

            $('.seekKeyword').bind('keydown', function(e) {
                if (e.which == 13) {
                    $('.bt_seek').click();
                    return false;
                }
            });
        }
    },

    pngFix: function() {

        if ($.browser.msie && $.browser.version == 6)
            DD_belatedPNG.fix('.pngfix');
    },

    validate: function() {
        $("form").validate(
		{
		    submitHandler: function(form) {
		        if ($("div.register div.main").length) {
		            $.modal.show();

		            $("div.modal.modalConfirmacao").show().modal(
		            {
		                buttonClose: ".btNao, .btFechar"
		            },
		            function() {
		                $(".btSim").unbind().click(function() {

		                    $("#__EVENTTARGET").val($("div.box:visible input:submit").attr("name"));

		                    form.submit()

		                    $.browser.msie && $.browser.version == "6.0"
		                    	&& form[0].submit();

		                    /*setTimeout(function() {
		                    window.location.reload();
		                    }, 5000);*/

		                    return false;
		                });
		            });

		            return false;
		        }
		        else {
		            form.submit();

		            return true;
		        }
		    }
		});

    },

    masked: function(div) {
        $("input.cpf", div).onlyNumber().mask("999.999.999-99");
    },

    limit: function(input) {
        input.each(function() {
            var elem = $(this),
				strong = elem.parent().siblings("span.caracter").find("strong"),
				char = Number(strong.text());

            elem
				.keyup(function() {
				    var texto = $(this).val(),
						tamanho = texto.length,
						line = texto.replace(/\s+$/g, ""),
						separate = line.split("\n"),
						separateLength = separate.length;

				    if (tamanho > char) {
				        elem.val(texto.substr(0, char));
				        return false;
				    }
				    else {
				        strong.html(char - tamanho);
				        return true;
				    }
				})
				.keypress(function(e) {
				    //if (e.keyCode == 13)
				       // return false;
				});

            strong.html(char - elem.val().length);

        });
    },

    // Inicializa o player
    playerMusic: function(elem) {
        this.elem = elem;

        //console.log (urlProject)
        $("#jquery_jplayer").jPlayer({
            ready: function() {
                var mp3musicUrl = window.baseUrl + "/upload/" + self.elem.attr('rel');
                $(this).setFile(mp3musicUrl).play();
            },
            //cssPrefix: "different_prefix_example",
            volume: 50,
            oggSupport: false,
            swfPath: urlProject + "swf"
        })
		.jPlayerId("play", "player_play")
		.jPlayerId("pause", "player_pause")
		.jPlayerId("stop", "player_stop")
		.jPlayerId("loadBar", "player_progress_load_bar")
		.jPlayerId("playBar", "player_progress_play_bar")
		.jPlayerId("volumeMin", "player_volume_min")
		.jPlayerId("volumeMax", "player_volume_max")
		.jPlayerId("volumeBar", "player_volume_bar")
		.jPlayerId("volumeBarValue", "player_volume_bar_value")
		.onProgressChange(function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
		    var myPlayedTime = new Date(playedTime);
		    var ptMin = (myPlayedTime.getUTCMinutes() < 10) ? "0" + myPlayedTime.getUTCMinutes() : myPlayedTime.getUTCMinutes();
		    var ptSec = (myPlayedTime.getUTCSeconds() < 10) ? "0" + myPlayedTime.getUTCSeconds() : myPlayedTime.getUTCSeconds();
		    $("#play_time").text(ptMin + ":" + ptSec);

		    var myTotalTime = new Date(totalTime);
		    var ttMin = (myTotalTime.getUTCMinutes() < 10) ? "0" + myTotalTime.getUTCMinutes() : myTotalTime.getUTCMinutes();
		    var ttSec = (myTotalTime.getUTCSeconds() < 10) ? "0" + myTotalTime.getUTCSeconds() : myTotalTime.getUTCSeconds();
		    $("#total_time").text(ttMin + ":" + ttSec);
		})
		.onSoundComplete(function() {
		    $(this).stop();
		});


    },

    prepareUploadFoto: function(interval) {
        with (this) {
            var button = $(".uploadImage"),
            	label = $(".uploadImage label"),
            	textReference = label.text(),
            	i;

            new AjaxUpload(button,
			{
			    action: "../servico/upload.ashx",
			    name: 'myfile',
			    onSubmit: function(file, ext) {
			        label.text('Enviando...');

			        interval = window.setInterval(function() {
			            var text = label.text();

			            label.text(text.length < 13 ? text + "." : 'Enviando...');

			        }, 200);
			    },
			    onComplete: function(file, response) {
			        clearInterval(interval);

			        this.enable();
			        label.text(textReference);

			        if (response.toString().indexOf('Error:') >= 0) {
			            alert(response.toString().split(':')[1].replace(/<(\/)?pre>/gi, ""));
			            return;
			        }
			        else {
			            var photo = response.replace(/<(\/)?pre>/gi, ""),
							img = $(".theImg img");

			            $(button).find("input.upload").val(photo);

			            img
			            	.attr('src', "../Thumb.aspx?w=100&h=100&imagem=" + photo)
			            	.show()
			            	.siblings("span").hide();
			        }
			    }
			});
        }
    },

    prepareUploadMusica: function(interval) {
        with (this) {
            var button = $(".musicaSend"),
            	label = $(".musicaSend label"),
            	textReference = label.text(),
            	i;

            new AjaxUpload(button,
			{
			    action: "../servico/upload.ashx?tipo=musica",
			    name: 'myfile',
			    onSubmit: function(file, ext) {
			        label.text('Enviando...');

			        button
			            .closest("div.box").find(".bt_save").attr("disable", true);

			        /*
			        interval = window.setInterval(function() {
			        var text = label.text();

			            button.text(text.length < 13 ? text + "." : 'Enviando...');

			        }, 200);
			        */
			    },
			    onComplete: function(file, response) {
			        clearInterval(interval);

			        this.enable();
			        label.text(textReference);

			        if (response.toString().indexOf('Error:') >= 0) {
			            alert(response.toString().split(':')[1].replace(/<(\/)?pre>/gi, ""));
			            return;
			        }
			        else {
			            var musica = response.replace(/<(\/)?pre>/gi, "");

			            button
			            	.find("input.uploadMusica").val(musica).end()
			            	.closest("div.box").find(".bt_save").attr("disable", false);
			        }
			    }
			});
        }
    }
});

$(function() {
    mens = new Message();
    actions = new Actions();
});

( function()
{
	Cufon.set( 'fontFamily', 'DIN-Bold' )
	Cufon.replace( 'h2', { color: '-linear-gradient(#433191, #1845bc)' } );
	Cufon.replace( 'button.bt_back, span.btLogout a, .cufon-default' );
	
	Cufon.set( 'fontFamily', 'DIN-Regular' )
	Cufon.replace( 'div.menu a' );
})();

// Digitar somente números
$.fn.onlyNumber = function(settings) {
    var defaults = {
        except: "-.A"
    },
		settings = $.extend({}, defaults, settings || {}),
		except = [];

    for (var i = 0; i < settings.except.length; i++) {
        except.push(settings.except.charCodeAt(i));
    }

    return this.each(function() {
        $(this).keypress(function(e) {
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && $.inArray(e.which, except) == -1)
                return false;
        });
    });
};

(function() {
    var $ = jQuery,
		htmlRef = null,
		self = null;

    Message = function() {
        self = this;
    }

    Message.fn = Message.prototype;
    Message.fn.extend = jQuery.extend;
    Message.fn.extend(
	{
	    init: function() {
	        htmlRef = $("<div class='message'></div>").appendTo('body');
	        htmlRef = $(".message");
	    },
	    show: function(message, type) {
	        self.init();
	        type = type == null ? "" : type;
	        htmlRef = $(".message");
	        htmlRef.fadeIn('slow');
	        htmlRef.attr("class", "message " + type);
	        htmlRef.html(message);
	        htmlRef.css('top', $(window).scrollTop() + 300);
	        $('body').mousemove(self.startHide);
	    },
	    startHide: function() {
	        self.init();
	        $('body').unbind('mousemove', self.startHide);
	        var htmlRef = htmlRef;
	        setTimeout(self.hide, 2000);
	    },
	    hide: function() {
	        self.init();
	        htmlRef.fadeOut('slow');
	    }
	});
})();

function MessageBox(message) {
    var msg = new Message;

    setTimeout(function() {
        msg.show(message, '');
    }, 1000);

}

