/**
 * Arquivo responsável pelo JS do Site EFC 2011
 *
 * @author: Monumenta
 * @date: 2011/01/05
 *
 * Copyright(c) Todos os direitos reservados a EFC
 */

if (window.console == null) window.console = { log: function (p) { } };

var _self;

var Functions = function () {
    _self = this;
    _self.init();
}

Functions.fn = Functions.prototype;
Functions.fn.extend = jQuery.extend;
Functions.fn.extend({
    init: function () {
        var flashvars = {
            trasparente: "true",
            urlDepoimento: "http://" + window.location.host + "/AjaxService/Depoimentos?quantidade=5&t=" + new Date().getMilliseconds(),
            urlMain: "http://" + window.location.host
        },
			params = {
			    quality: "high",
			    wmode: "transparent",
			    scale: "noscale"
			},
			attributes = {},
			callbackFlash = function () { };

        this.header = $("div.header");
        this.content = $("div.content");

        $.browser.msie
			&& $.browser.version == 6
			&& DD_belatedPNG.fix(".pngfix");

        _self.menu();
        _self.actions();
        _self.fontReplace();
        _self.listComents();
        _self.inscricaoOficina();
        _self.viewCalendar($("div.calendar", _self.header));
        _self.wait();

        $(window).resize(function () {
            _self.listComents();
        });

        swfobject.embedSWF("http://" + window.location.host + "/_global/swf/main_new.swf", "flash", "1384", "396", "7.0.0", "", flashvars, params, attributes, callbackFlash());

        $("div.multimedia", _self.content).length
			&& _self.multimedia.init($("div.multimedia", _self.content));

        $("div.resultSearch", _self.content).length
			&& _self.adjustLi();

        $("div.seeImages", _self.content).length
			&& _self.seeImage();

        $("div.formComments", _self.content).length
			&& _self.comments($("div.formComments"));

        $("#clipping", _self.content).length
			&& _self.clipping($("#clipping", _self.content));
    },

    clicked: 0,

    adjustLi: function () {
        var lis = $("ul.listing li");

        lis.each(function (i) {
            (i + 1) % 4 == 0
				&& $(this).css("padding-right", 0);
        });

        $("ul.listing li:last").css("padding-right", 0);
    },

    wait: function () {
        $("div.menu li a.semanaCultural").click(function () {
            if ($(this).siblings("div.subMenu").length)
                return false;
            else {
                _self.modalShadowBox("iframe", "", "/semanacultural/ModalEmBreve", 189, 468, 189, 468, "");
                return false;
            }
        });
        $("#modal a.btClose").live("click", function () {
            window.parent.Shadowbox.close();
        });
    },

    seeImage: function () {
        var numberLi = $(".contentImage div.image ul li").length,
			tamUl = numberLi * 270;

        $(".contentImage div.image ul").css("width", tamUl);

        _self.clicked = 0;

        $("ul.navigation li a").click(function () {
            var index = $(this).parent().index();

            if (_self.clicked)
                return false;

            _self.clicked++;

            $(this).parent().addClass("active")
					.siblings("li").removeClass("active");

            if (index == 0) {
                $(".contentImage div.image ul").animate({
                    left: 0
                }, 800, function () {
                    _self.clicked--;
                });
            }
            else {
                $(".contentImage div.image ul").animate({
                    left: -(index * 270)
                }, 800, function () {
                    _self.clicked--;
                });
            }
            return false;
        });

        $("div.contentImage a.btPrev").click(function () {
            var leftUl = parseInt($(".contentImage div.image ul").css("left").split("px")),
				currentNavigation = $("ul.navigation li.active");

            if (_self.clicked)
                return false;

            _self.clicked++;

            if (leftUl == 0) {
                _self.clicked--;
                return false;
            }
            else {
                $(".contentImage div.image ul").animate({
                    left: leftUl + 270
                }, 800, function () {
                    _self.clicked--;
                });
                currentNavigation.removeClass("active").prev().addClass("active");
                return false;
            }
        });
        $("div.contentImage a.btNext").click(function () {
            var leftUl = parseInt($(".contentImage div.image ul").css("left").split("px")),
				rigthUl = 270 - tamUl,
				currentNavigation = $("ul.navigation li.active"),
				currentLeft = leftUl - 270;

            if (_self.clicked)
                return false;

            _self.clicked++;

            if (leftUl == rigthUl) {
                _self.clicked--;
                return false;
            }
            else {
                $(".contentImage div.image ul").animate({
                    left: currentLeft
                }, 800, function () {
                    _self.clicked--;
                });
                currentNavigation.removeClass("active").next().addClass("active");
                return false;
            }
        });
    },

    comments: function (forms) {
        $(".bt_send", forms).unbind().click(function () {
            var name = $("input#Nome"),
					IdConteudo = $("input#IdConteudo"),
					email = $("input#E-mail"),
					url = $("input#Url"),
					text = $("textarea#Texto");

            name.val() == ""
					&& name.addClass("error");
            email.val() == ""
					&& email.addClass("error");
            text.val() == ""
					&& text.addClass("error");

            $("input.error, textarea.error", forms).focus(function () {
                $(this).removeClass("error");
            });

            if ($("input.error, textarea.error", forms).length)
                return false;

            //$( this ).hide();

            $.ajax(
				{
				    url: "/AjaxService/SalvarComentario",
				    data: "comentario=" + $.toJSON({ "Nome": name.val(), "IdConteudo": IdConteudo.val(), "Email": email.val(), "Url": url.val(), "Texto": text.val() }),
				    error: function () {

				    },
				    success: function (response) {
				        if (response.ok) {
				            $("<p>Comentário enviado com sucesso.</p>").hide().prependTo(forms).fadeIn();

				            $("input#Nome, input#E-mail, input#Url, textarea#Texto", forms).val("");

				            setTimeout(function () {
				                $("p", forms).fadeOut();
				            }, 4000);
				        }
				        else
				            console.log("Nossa occoreu um erro!");
				    }
				});

            return false;
        });
    },

    multimedia:
	{
	    init: function (div) {
	        var oThis = this,
				divSearch = $("div.search", div),
				hash;

	        if ($("div.gallery").hasClass("details")) {
	            oThis.details(div.find("div.gallery"));
	        } else if (!window.location.hash.length) {
	            _self.multimedia.requestMedia.call(div, {
	                filtro: divSearch.find("input#letter").val(),
	                cidade: divSearch.find("select.change").val(),
	                tipoEvento: divSearch.find("li.typeEvent input:checked").length === 1
						? divSearch.find("li.typeEvent input:checked").val()
						: 0
	            });
	        } else {
	            hash = window.location.hash.replace('#', '');

	            _self.multimedia.requestAlbum.call(div, hash);
	        }

	        oThis.menuType(div);
	        oThis.searchMultimedia(div);
	    },

	    details: function (div) {
	        var photoDetails = $("div.scroll ul.photoDetails", div),
				lis = $("li", photoDetails),
				btNext = $(".bt_next", div),
				btPrev = $(".bt_prev", div),
				comments = $("div.comments", div),
                photoIndex = 1;

	        if (window.location.hash.length) {
	            photoIndex = $("li" + window.location.hash)
                    .addClass("active")
                    .index() + 1;
	        } else {
	            $("li:first", photoDetails).addClass("active");
	        }

	        $("div.scroll ul li:lt(4)", comments).addClass("visible");

	        if ($("div.listComments div.scroll li", comments).length >= 5) {
	            $("div.pagination", comments).show();
	            $("li:eq(3)", comments).addClass("visible").prevAll("li").addClass("visible");
	        }

	        if (lis.length >= 2) {
	            $("p.index", div).html("<span class='now'>" + photoIndex + "</span> de " + lis.length);
	            btNext.show();
	            btPrev.show();
	        }

	        btNext.unbind().click(function () {
	            var active = $("li.active", photoDetails),
                    paginationCount = $("p.index span.now", div),
                    paginationIndex = Number(paginationCount.text());

	            active.stop(true, true).fadeOut(function () {
	                if (++paginationIndex > lis.length) {
	                    paginationIndex = 1;
	                }

	                if (!active.next().length) {
	                    paginationIndex = 1;
	                }

	                paginationCount.text(paginationIndex);

	                active.removeClass('active');

	                lis.filter(':eq(' + (paginationIndex - 1) + ')')
                        .stop(true, true)
                        .fadeIn()
                        .addClass('active');
	            });

	            return false;
	        });

	        btPrev.unbind().click(function () {
	            var active = $("li.active", photoDetails),
                    paginationCount = $("p.index span.now", div),
                    paginationIndex = Number(paginationCount.text());

	            active.stop(true, true).fadeOut(function () {
	                if (--paginationIndex < 1) {
	                    paginationIndex = lis.length;
	                }

	                if (!active.prev().length) {
	                    paginationIndex = lis.length;
	                }

	                paginationCount.text(paginationIndex);

	                active.removeClass('active');

	                lis.filter(':eq(' + (paginationIndex - 1) + ')')
                        .stop(true, true)
                        .fadeIn()
                        .addClass('active');
	            });

	            return false;
	        });

	        $(".btNext", comments).unbind().click(function () {
	            var $this = $(this),
					ul = $("div.listComments ul", comments),
					nexts = $("li.visible:last").nextAll(":lt(4)");

	            if (nexts.length) {
	                $("li.visible", ul).fadeOut().removeClass("visible");
	                nexts.addClass("visible").show();
	            }

	            return false;
	        });

	        $(".btPrev", comments).unbind().click(function () {
	            var $this = $(this),
					ul = $("div.listComments ul", comments),
					nexts = $("li.visible:first").prevAll(":lt(4)");

	            if (nexts.length) {
	                $("li.visible", ul).fadeOut().removeClass("visible");
	                nexts.addClass("visible").show();
	            }

	            return false;
	        });

	        $(".bt_comments", comments).unbind().click(function () {
	            var scrolls = $("div.scroll", comments),
					forms = $("div.formComments", comments);

	            scrolls.is(":visible")
					? scrolls.slideUp(function () {
					    forms.slideDown();
					    $("div.pagination", div).hide();
					})
					: forms.slideUp(function () {
					    scrolls.slideDown();
					    $("div.listComments div.scroll li", comments).length >= 5
							&& $("div.pagination", div).show();
					});

	            $(".bt_send", forms).unbind().click(function () {
	                var name = $("input#Nome", comments),
						IdConteudo = $("input#IdConteudo"),
						email = $("input#E-mail", comments),
						url = $("input#Url", comments),
						text = $("textarea#Texto", comments);

	                name.val() == ""
						&& name.addClass("error");
	                email.val() == ""
						&& email.addClass("error");
	                text.val() == ""
						&& text.addClass("error");

	                $("input.error, textarea.error", forms).focus(function () {
	                    $(this).removeClass("error");
	                });

	                if ($("input.error, textarea.error", forms).length)
	                    return false;

	                $(this).hide();

	                $.ajax(
					{
					    url: "/AjaxService/SalvarComentario",
					    data: "comentario=" + $.toJSON({ "Nome": name.val(), "IdConteudo": IdConteudo.val(), "Email": email.val(), "Url": url.val(), "Texto": text.val() }),
					    error: function () {

					    },
					    success: function (response) {
					        if (response.ok) {
					            $("<p>Comentário enviado com sucesso.</p>").hide().prependTo(forms).fadeIn();

					            $("input, textarea", forms).val("");

					            setTimeout(function () {
					                $(".bt_send", forms).show();
					                forms.slideUp(function () {
					                    scrolls.slideDown();
					                    $("div.pagination", div).show();
					                });
					            }, 4000);
					        }
					        else
					            console.log("Nossa occoreu um erro!");
					    }
					});

	                return false;
	            });

	            return false;
	        });
	    },

	    searchMultimedia: function (div) {
	        var divSearch = $("div.search", div);

	        $(".bt_search", divSearch).not('.normalSearch').unbind().click(function () {
	            _self.multimedia.requestMedia.call(div, {
	                filtro: divSearch.find("input#letter").val(),
	                cidade: divSearch.find("select.change").val(),
	                tipoEvento: divSearch.find("li.typeEvent input:checked").length === 1
									? divSearch.find("li.typeEvent input:checked").val()
									: 0
	            });

	            return false;
	        });
	    },

	    menuType: function (div) {
	        var menu = $("div.menu", div);

	        $("a", menu).unbind().click(function () {
	            var typeMulti = $(this).attr("id");

	            menu.find("a").removeClass("active");

	            _self.multimedia.requestMedia.call(div, {
	                tipoMultimedia: typeMulti
	            });

	            $(this).addClass("active");

	            return false;
	        });
	    },

	    requestMedia: function (settings) {
	        var defaults = {
	            filtro: "",
	            tipoMultimedia: "",
	            cidade: "",
	            tipoEvento: 0
	        },
				params;

	        $.extend(defaults, settings);

	        params = $.param(defaults);

	        $(this).find("div.loading").show();
	        $(this).find(".bt_prev, .bt_next").hide();
	        $(this).find("div.menu a").removeClass("active");
	        $(this).find("div.titleAlbum").hide();

	        /*$(this).find("div.menu a.active").length
	        ? $(this).find("div.menu a.active").attr("rel", params)
	        : $(this).find("div.menu a:first").attr("rel", params);*/

	        _self.multimedia.getMedia(
				"/AjaxService/Multimedias",
				defaults,
				$(this).find("div.gallery"),
				_self.multimedia.updates
			);

	        $(this).find(".bt_prev, .bt_next").attr({
	            href: "/AjaxService/Multimedias",
	            rel: "page=1&tipoMultimidia=" + defaults.tipoMultimedia
	        });
	    },

	    getMedia: function (url, data, div, callback, prev) {
	        $.ajax(
			{
			    url: url,
			    data: data,
			    type: "GET",
			    error: function (response) {
			        console.log("ERROR: ", response);
			    },
			    success: function (response) {
			        $("div.loading", div).fadeOut();

			        if (response.ok)
			            callback && callback(response, div, prev);
			        else
			            console.log("Nossa ocorreu um erro!!");
			    }
			});
	    },

	    buildTemplates: function (json, gallery, callback, prev) {
	        var listing = $("div.listing ul", gallery).empty();

	        $(json.multimidias).each(function () {
	            var html = $('<li><p class="date"></p><div class=""><img src="" alt="" /><span class="numberImages"></span><a href="#" class="bt_play" title="Play">Play</a></div><p class="description"></p></li>').hide(),
					jThis = this,
					date = new Date(Number(jThis.Data.replace("/Date(", "").replace(")/", "")));

	            jThis.Data = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();

	            if (jThis.IdMultimediaTipo == 1) {
	                var linkA = $("<a href='#' title='' class='bt_seeAlbum'></a>");

	                $("div", html).appendTo(linkA.attr(
					{
					    title: jThis.Nome
					}));

	                html.data("json", jThis);
	                html.attr("id", jThis.IdConteudo);

	                linkA.insertAfter($("p.date", html));

	                $(".bt_play", html).remove();
	                $("span.numberImages", html).text(jThis.QtdeMultimediaItem > 1 ? jThis.QtdeMultimediaItem + " Fotos" : jThis.QtdeMultimediaItem + " Foto");
	            }
	            else {
	                $("span.numberImages", html).remove();
	                $(".bt_play", html).attr("href", jThis.Url);
	            }

	            html
					.find("p.date").text(jThis.Data).end()
					.find("div").attr("class", jThis.IdMultimediaTipo == 1 ? "album" : "movie")
						.find("img").attr(
						{
						    src: jThis.ImagemCapa,
						    alt: jThis.Nome
						}).end()
					.end()
					.find("p.description").text(jThis.Titulo).end()
					.appendTo(listing).fadeIn();
	        });

	        callback
				&& callback(json, gallery, prev);

	        $(".bt_seeAlbum", gallery).unbind().bind("click", function (e) {
	            _self.multimedia.albumClick.call($(this));

	            e.preventDefault();
	        });
	    },

	    actionsView: function (json, gallery) {
	        var lis = json.length,
				loading = $("div.loading", gallery),
				btNext = $(".bt_next", gallery),
				btPrev = $(".bt_prev", gallery);

	        $("p.index", gallery).html("<span class='now'>1</span> de " + json.totalPaginas).css("display", "inline");

	        btNext.attr("rel", "page=" + $("p.index span.now", gallery).text());
	        btPrev.attr("rel", "page=" + (Number($("p.index span.now", gallery).text()) - 1));

	        if (json.totalPaginas >= 2) {
	            btNext.show().unbind().click(function () {
	                var url = btNext.attr("href"),
						data = btNext.attr("rel");

	                loading.fadeIn();

	                _self.multimedia.getMedia(url, data, gallery, _self.multimedia.changePage);

	                return false;
	            });

	            btPrev.unbind().click(function () {
	                var url = btPrev.attr("href"),
						data = btPrev.attr("rel");

	                loading.fadeIn();

	                data.length
						? _self.multimedia.getMedia(url, data, gallery, _self.multimedia.changePage, true)
						: _self.multimedia.slidePage(gallery, true);

	                return false;
	            });
	        }

	        $(".bt_seeAlbum", gallery).unbind().bind("click", function (e) {
	            _self.multimedia.albumClick.call($(this));

	            e.preventDefault();
	        });
	    },

	    albumClick: function () {
	        var $this = $(this),
				parent = $this.parent(),
                gallery = $this.parents('div.gallery'),
                loading = $("div.loading", gallery),
				btNext = $(".bt_next", gallery),
				btPrev = $(".bt_prev", gallery),
				oJson = parent.data("json"),
				ul = $("div.scroll ul", gallery);

	        loading.fadeIn();
	        ul.hide();
	        ul.empty();
	        btPrev.hide();
	        btNext.hide();

	        $.ajax({
	            url: "/AjaxService/MultimediaItem",
	            data: "IdConteudo=" + oJson.IdConteudo + "&page=0",
	            type: "GET",
	            error: function () {

	            },
	            success: function (response) {
	                var rJson = response.itens;

	                if (response.ok) {
	                    var photos = rJson.length + 1;

	                    if (response.qtdePaginas >= 2) {
	                        btNext.show().attr(
							{
							    href: "/AjaxService/MultimediaItem",
							    rel: "IdConteudo=" + oJson.IdConteudo + "&page=" + $("p.index span.now", gallery).text()
							});

	                        btPrev.attr(
							{
							    href: "/AjaxService/MultimediaItem",
							    rel: "IdConteudo=" + oJson.IdConteudo + "&page=" + (Number($("p.index span.now", gallery).text()) - 1)
							});
	                    }

	                    $("p.index", gallery).html("<span class='now'>1</span> de " + response.qtdePaginas);
	                    _self.oJson = oJson;
	                    $("div.titleAlbum", gallery).find("p").text(oJson.Data + " - " + oJson.Titulo).end().show()
	                    _self.multimedia.buildAlbum(response, _self.oJson, ul);
	                }
	                else
	                    console.log("Nossa ocorreu um erro!");
	            }
	        });
	    },

	    requestAlbum: function (id) {
	        var prev = $(this).find(".bt_prev"),
				next = $(this).find(".bt_next"),
				div = $("div.content div.multimedia"),
				$this = $(this);

	        $(this).find("div.loading").fadeIn();
	        prev.hide();
	        next.hide();

	        $.ajax({
	            url: "/AjaxService/MultimediaItem",
	            data: "IdConteudo=" + id + "&page=0",
	            type: "GET",
	            success: function (response) {
	                if (response && response.ok) {
	                    var secs = response.album.Data.replace('/Date(', '').replace(')/', ''),
							dateObj = new Date(Number(secs)),
							formatedDate = dateObj.format('dd/MM/yyyy'),
							album = {
							    Data: formatedDate
							},
							gallery = div.find("div.gallery");

	                    $.extend(response.album, album);

	                    $this.find("p.index").show().html("<span class='now'>1</span> de " + response.qtdePaginas);
	                    $this.find("div.titleAlbum p").text(formatedDate + " - " + response.album.Titulo).parent().show();

	                    if (response.qtdePaginas >= 2) {
	                        next.show().attr({
	                            href: "/AjaxService/MultimediaItem",
	                            rel: "IdConteudo=" + id + "&page=" + $this.find("p.index span.now").text()
	                        }).unbind().bind("click", function () {
	                            var url = next.attr("href"),
									data = next.attr("rel");

	                            $("div.loading").fadeIn();

	                            _self.oJson = response.album;

	                            _self.multimedia.getMedia(url, data, gallery, _self.multimedia.changePage);

	                            return false;
	                        });

	                        prev.attr({
	                            href: "/AjaxService/MultimediaItem",
	                            rel: "IdConteudo=" + id + "&page=" + (Number($this.find("p.index span.now").text()) - 1)
	                        }).unbind().bind("click", function () {
	                            var url = prev.attr("href"),
									data = prev.attr("rel");

	                            $("div.loading").fadeIn();

	                            _self.oJson = response.album;

	                            data.length
									? _self.multimedia.getMedia(url, data, gallery, _self.multimedia.changePage, true)
									: _self.multimedia.slidePage(gallery, true);

	                            return false;
	                        });
	                    }

	                    _self.multimedia.buildAlbum(response, response.album, div.find("div.scroll ul"));
	                } else {
	                    console.log("Nossa ocorreu um erro!");

	                    _self.multimedia.requestMedia.call(div);
	                }
	            }
	        });
	    },

	    changePage: function (json, gallery, prev) {
	        json.qtdePaginas != undefined
				? _self.multimedia.buildAlbum(json, _self.oJson, $("div.scroll ul", gallery), prev, _self.multimedia.showPage)
				: _self.multimedia.buildTemplates(json, gallery, _self.multimedia.showPage, prev);
	    },

	    buildAlbum: function (rJson, oJson, ul, prev, callback) {
	        var json = rJson.itens;
	        ul.empty();

	        $(json).each(function () {
	            var html = $('<li><p class="date"></p><div class="album"><a href="#"><img src="" alt="" /></a></div><p class="description"></p></li>'),
					jThis = this;

	            html
					.find("p.date").text(oJson.Data).end()
					.find("div")
						.find("a").attr(
						{
						    href: "/Multimidia/Detalhes/" + oJson.IdConteudo + "/" + oJson.TituloPermaLink + "#" + jThis.IdMultimidiaItem,
						    title: jThis.Titulo
						}).end()
						.find("img").attr(
						{
						    src: jThis.Imagem,
						    alt: jThis.Titulo
						}).end()
					.end()
					.find("p.description").text(jThis.Titulo).end()
				.appendTo(ul);
	        });

	        ul.fadeIn(function () {
	            $("div.loading", _self.content).fadeOut();
	        });

	        callback
				&& callback(rJson, $("div.gallery", _self.content), prev);
	    },

	    slidePage: function (gallery, verification) {
	        var ul = $("div.scroll ul", gallery),
				leftValue = ul.css("left").split("px")[0];

	        ul.fadeOut(function () {
	            verification
					? ul.css("left", leftValue + 738)
					: ul.css("left", -(leftValue + 738));

	            ul.fadeIn(function () {
	                $("div.loading", gallery).fadeOut();
	            });
	        });
	    },

	    showPage: function (json, gallery, prev) {
	        var ul = $("div.listing ul", gallery),

				nextPage = Number($("p.index span.now", gallery).text()) + 1,

				prevPage = Number($("p.index span.now", gallery).text()) - 1,

				IdConteudo = json.album
							  ? json.album.IdConteudo
							  : false,

				pages = json.totalPaginas
						 ? json.totalPaginas
						 : json.qtdePaginas,

				page = prev == undefined
						? nextPage
						: prevPage;

	        $("p.index span.now", gallery).text(page);


	        if (nextPage + 1 <= pages) {
	            $(".bt_next", gallery).attr(
					'rel',
					IdConteudo
						? 'IdConteudo=' + IdConteudo + '&page=' + (nextPage + 1)
						: 'page=' + (nextPage + 1)
				);
	        }

	        if (prevPage - 1 >= 0) {
	            $(".bt_prev", gallery).attr(
					'rel',
					IdConteudo
						? 'IdConteudo=' + IdConteudo + '&page=' + (prevPage - 1)
						: 'page=' + (prevPage - 1)
				);
	        }


	        page == pages
				? $(".bt_next", gallery).hide() && $(".bt_prev", gallery).show()
				: page > 1
					? $(".bt_prev", gallery).show()
					: $(".bt_prev", gallery).hide() && $(".bt_next", gallery).show();
	    },

	    updates: function (json, gallery) {
	        _self.multimedia.buildTemplates(json, gallery, _self.multimedia.actionsView);
	    }
	},

    // Funções para mostrar os Tooltips
    tooltips: function (h) {
        h.hover(function () {
            $("div.tooltip", $(this)).stop(true, true).fadeIn("fast");
        }, function () {
            $("div.tooltip", $(this)).stop(true, true).fadeOut("fast");
        });
    },

    viewCalendar: function (div) {
        var getEvents = function (m, y) {
            $.ajax(
			{
			    url: "/AjaxService/Eventos",
			    data: "mes=" + m + "&ano=" + y,
			    type: "GET",
			    error: function (response) {
			        console.log("ERROR: ", response);
			    },
			    success: function (response) {
			        var json = response;

			        if (json.ok) {
			            var tableBody = $("table tbody", calendar);

			            $(json.evento).each(function () {
			                var oThis = this,
								day = $("tr td a:contains(" + oThis.Dia + "):first", tableBody),
								parent = day.parents("td"),
								html = $("div.infoEvent", parent).length
										? $("<img class='hidden' src='' alt='' />")
										: $("<div class='infoEvent'><img src='' alt='' /> <div class='tooltip'><span><a href='#'></a></span></div></div>");

			                html.find("img").length
								? html.find("img").attr(
									{
									    src: oThis.ImagemDestaque,
									    alt: oThis.Titulo
									}).end()
									.find("div.tooltip span a").attr("href", oThis.Link).text(oThis.Titulo).end()
								.appendTo(parent)
								: html.attr(
									{
									    src: oThis.ImagemDestaque,
									    alt: oThis.Titulo
									}).insertAfter($("div.infoEvent img:first", parent.addClass("turnOn"))) && $("<span><a href='#'></a></span>").find("a").attr("href", oThis.Link).text(oThis.Titulo).end().appendTo($("div:first div.tooltip", parent));

			                day.addClass("event");

			                day.appendTo($("div:first", parent));

			                _self.tooltips(parent)
			            });

			            $("a.ui-state-default", tableBody).unbind().click(function () {
			                return false;
			            });

			            $("td", tableBody).removeAttr("onclick");

			            var turnOn = $("td.turnOn", tableBody);

			            setInterval(function () {
			                $("img", turnOn).siblings("img").length
								&& $("img", turnOn).fadeOut(function () {
								    $(this).addClass("hidden").siblings("img.hidden").fadeIn().removeClass("hidden");
								});
			            }, 5000);

			        }
			        else
			            console.log("Ocorreu um erro!!");
			    }
			});
        },
		calendar = $('#datepicker', div);

        $(".btCalendar", _self.header).unbind().click(function () {
            // Datepicker
            calendar.datepicker({
                dateFormat: 'dd/mm/yy',
                dayNames: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado', 'Domingo'],
                dayNamesMin: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado', 'Domingo'],
                dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb', 'Dom'],
                monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
                monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
                nextText: 'Próximo',
                prevText: 'Anterior',
                inline: true,
                onSelect: function (dateText, inst) {
                    console.log("onSelect", dateText, inst);
                },
                onChangeMonthYear: function (year, month, inst) {
                    getEvents(month, year);
                }
            });

            div.fadeIn();

            getEvents(Number(calendar.datepicker("getDate").getMonth()) + 1, calendar.datepicker("getDate").getFullYear());

            $(".bt_search", div).unbind().click(function () {
                var divSearch = $("div.search", div);

                divSearch.fadeIn(function () {
                    $(".bt_search2", divSearch).unbind().click(function () {
                        var letter = $("li.letter input", divSearch).val(),
							city = $("select", divSearch).val(),
							typeEvent = $("li input:checked", divSearch).attr("class") != undefined
											? $("li input:checked", divSearch).attr("class")
											: "",
							url = "http://" + window.location.host + "/AgendaCultural?palavraChave=" + letter + "&cidade=" + city + "&tipoEvento=" + typeEvent;

                        window.location.href = url;

                        return false;
                    });

                    $(".bt_close_search", divSearch).unbind().click(function () {
                        divSearch.fadeOut();

                        return false;
                    });
                });

                $("input[type=checkbox]", divSearch).click(function () {
                    var $this = $(this);

                    $this.attr("class") == "1"
						? $("input[name=shows]", divSearch).removeAttr("checked")
						: $("input[name=workshops]", divSearch).removeAttr("checked")
                });


                return false;
            });

            $(".bt_close", div).unbind().click(function () {
                div.fadeOut();
                calendar.datepicker("destroy");

                return false;
            });

            return false;
        });
    },

    actions: function () {
        $.fn.corner.defaults.useNative = false;
        $(".cantosArredondado, .cantosArredondados").corner("6px");

        if ($('#boxComoFoi')[0]) {
            $('#boxComoFoi').codaSlider();
        }

        $('div.seeHow span.lastBg .lastShow').click(function () {
            $('div.content.contentInterna div.internas div.sidebar div.seeHow span.lastBg').animate({ backgroundPosition: '0 0' });
        });

        $('div.seeHow span.lastBg .lastOficina').click(function () {
            $('div.content.contentInterna div.internas div.sidebar div.seeHow span.lastBg').animate({ backgroundPosition: '0 -23px' });
        });

        $('div.content.contentInterna div.internas div.whoCulture ul.listComents li:odd').addClass('comentOne');
        $('div.content.contentInterna div.internas div.whoCulture ul.listComents li:even').addClass('comentThwo');

        if ($('.page_navigation')[0]) {
            $('#paging_container1').pajinate({
                num_page_links_to_display: 3,
                items_per_page: 4
            });
        }

        $('div.nextEvents .btOk').click(function () {
            var url = $('div.nextEvents select#ProximosEventos').val();
            window.location.href = url;
            return false;
        });
    },

    inscricaoOficina: function () {
        var incricao = $('div.inscricaoEvento'),
			btContinuar = $('div.btContinuarInscricao a', incricao),
			btVoltar = $('a.btVoltar', incricao),
			boxIncricao = $('div.boxIncricao', incricao),
			step1 = $('div.step1', incricao),
			step2 = $('div.step2', incricao),
			entryCompleted = $('#entryCompleted', incricao),
			entryErro = $('#entryErro', incricao),
			btConcluir = $('.btConcluir', incricao),
			formInscricao = $('form', incricao),
			formCadastro = $('ul.formCadastro', incricao),
			statusEnviar = $('#statusEnviar', incricao),
			btVoltarInscricao = $('.btVoltarInscricao a', incricao),
			idOficina = $('#idOficina', incricao),
			aceite = $('#agree', incricao),
			workshopDescription = $('div.workshopDescription', incricao),
			btRegister = $('a.btRegister');

        $("#telefone_fixo").mask("(99)9999-9999");
        $("#telefone_celular").mask("(99)9999-9999");

        // Desabilita submit do formulario
        $.validator.setDefaults({
            submitHandler: function () { }
        });

        formInscricao.validate({
            rules: {
                email_confirmacao: {
                    required: true,
                    equalTo: "#email"
                },
                agree: "required"
            },
            messages: {
                email_confirmacao: {
                    equalTo: "Email não confere."
                },
                agree: "Aceita o regulamento?"
            }

        });

        btRegister.click(function () {
            workshopDescription.fadeOut('fast', function () {
                step1.fadeIn('slow');
            });
            return false;
        });

        aceite.click(function () {
            if ($(this + ":checked")) {
                statusEnviar.val('true');
            } else {
                statusEnviar.val('false');
            }
        });

        btContinuar.click(function () {
            formCadastro.find("label.error").remove();
            formInscricao.submit();

            if (formCadastro.find(".error").length == 0) {
                step1.fadeOut('fast', function () {
                    step2.fadeIn('slow');
                });
            }

            return false;
        });

        btVoltarInscricao.click(function () {
            step2.fadeOut('fast', function () {
                $('.entryCompleted', incricao).fadeOut('fast', function () {
                    formInscricao[0].reset();
                    workshopDescription.fadeIn('slow');
                    statusEnviar.val('false');
                });
            });
            return false;
        });

        btVoltar.click(function () {
            step2.fadeOut('fast', function () {
                entryCompleted.fadeOut('fast', function () {
                    step1.fadeIn('slow');
                });
            });
            return false;
        });

        btConcluir.click(function () {
            if ((formCadastro.find(".error").length == 0) && (statusEnviar.val() == 'true')) {
                step2.fadeOut('fast', function () {
                    var vars = {
                        "Nome": $("#nome", incricao).val(),
                        "RG": $("#rg", incricao).val(),
                        "TelefoneCelular": $("#telefone_celular", incricao).val(),
                        "TelefoneResidencial": $("#telefone_fixo", incricao).val(),
                        "Cidade": $("#cidade", incricao).val(),
                        "UF": $("#estados", incricao).val(),
                        "Email": $("#email", incricao).val()
                    };

                    var json = $.toJSON(vars),
							ajaxLoader = $("span.ajaxLoader", _self.content);
                    ajaxLoader.fadeIn("fast");

                    $.ajax({
                        url: '/AjaxService/SalvarParticipanteOficina',
                        type: 'GET',
                        dataType: 'json',
                        data: "participante=" + json + "&IdConteudo=" + idOficina.val(),
                        contentType: 'application/json; charset=utf-8',
                        timeout: 20000,
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            ajaxLoader.fadeOut("fast");
                            Message.show("Ocorreu um erro em sua solicitação. Por favor, tente novamente em alguns minutos. Obrigado. (Time Out)", "");
                        },
                        success: function (response) {
                            var json = $(response);

                            if (json[0].ok == false) {
                                entryErro.fadeIn('slow');
                            } else {
                                entryCompleted.fadeIn('slow');
                            }

                            ajaxLoader.fadeOut("fast");
                        }
                    });
                });
            }
        });

    },

    menu: function () {
        $('div.header div.subMenu ul li:last, div.header div.menuProjeto ul li:last').addClass('removeBorda');

        $("div.header ul li.ativaMenu").hover(function () {
            $('div.subMenu', $(this)).stop(true, true).fadeIn("fast");
        }, function () {
            $('div.subMenu', $(this)).stop(true, true).fadeOut("fast");
        });
    },

    listComents: function () {

    },

    fontReplace: function () {
        Cufon.replace($("h3.titleType, div.content.contentInterna div.internas div.titlePage h2, div.content.contentInterna div.internas div.sidebar div.partGroup h3, div.content div.boxInformation h3, div.content div.boxInformation h4, div.efcDestaque h4, div.subDestaque h5, div.content h5.tituloAbertura, div.inscricaoEvento div.tituloPasso h4, div.content.contentInterna div.multimedia div.search form fieldset legend, ul.listagem_noticias li h3 , div.searchNews h3, div.detalsNews h3, div.otherNews h3, div.sidebar div.seeImages h5, .cufonReplaceLight, div.sidebar div.nextShow h5, div.sidebar div.nextWorkshop h5, #modal h3, div.contacUs div.error p, div.contacUs div.success p"), { fontFamily: 'Helvetica-Light', hover: true });
        Cufon.replace($("h4.subTitleType, div.calendar div.form h4, .cufonReplaceMedium, div.menuClipping ul li a"), { fontFamily: 'Helvetica65-Medium', hover: true });
        Cufon.replace($("span.btLearnMore a"), { fontFamily: 'DIN 6776' });
        Cufon.replace($("div.header div.menu ul li a, div.sidebar div.searchClipping h3, div.sidebar div.seeToo h3"), { fontFamily: 'Helvetica Neue' });
    },

    modalShadowBox: function ($type, $title, $url, $ifHeight, $ifWidth, $height, $width, $caminho) {
        var isIE6 = ((navigator.userAgent.indexOf("MSIE 6.") != -1) && (navigator.userAgent.indexOf("Opera") == -1));

        if (isIE6)
            $ifHeight = $ifHeight + 20;

        Shadowbox.iframeHeight = $ifHeight;
        Shadowbox.iframeWidth = $ifWidth;
        Shadowbox.caminho = $caminho;

        Shadowbox.init({ skipSetup: true, iframeHeight: $ifHeight, iframeWidth: $ifWidth, animate: false });
        Shadowbox.open({ player: $type, title: $title, content: $url, width: $width, height: $height });
    },

    // Função responsável pela area de Clipping [ Mateus Moura ]
    clipping: function (div) {
        var menu = $("div.menuClipping", _self.content);

        $("div.sidebar div.searchClipping ul li.input input").resetDefaultValue();

        $("a", menu).unbind().click(function (eventObject) {
            //debugger;
            var $bt = $(this),
				cl = $bt.attr("class").split("bt_")[1];

            if ($bt.is(".active"))
                return false;

            //            $("p.result", div).is(".view") && cl == "updates"
            //                ? $("p.result", div).show()
            //                : $("p.result", div).hide();
            $("p.result", div).hide();

            $bt.parent().addClass("active").siblings(".active").removeClass("active");

            Cufon.refresh();

            $("div.active", div).fadeOut(function () {
                $(this).removeClass("active");
                $("div." + cl, div).fadeIn(function () {
                    $(this).addClass("active");
                });
            });

            return false;
        });

        $(".bt_updates", menu).click(function (eventObject) {
            if (eventObject.originalEvent != undefined) {
                //debugger;

                //window.location = '/ProjetoNaMidia';

                $.ajax({
                    url: '/ProjetoNaMidia/Paginar',
                    type: 'GET',
                    dataType: 'html',
                    data: "tipo=0&pageIndex=0&tag=&limparFiltro=true",
                    cache: false,
                    success: function (response) {
                        $('#divListaAtualizacoes').html(response);
                    }
                });
            }
        });
    }
});

// Mensageria
(function()
{
    var $ = jQuery;
    window.Message =
	{
	    show: show,
	    init: init
	};

    var htmlRef = null;

    function init()
    {
        htmlRef = jQuery("<div class='message' style='background-color:#ffffff; border:5px solid #FFA214; display:none; left:50%; margin-left:-245px; padding:20px; position:absolute; top:50%; width:450px; z-index:10000;'><p style='color:#535353; display:block; font-size:14px; line-height:1.3em; text-align:center;'></p></div>").appendTo('body');
    };

    function show(message, type)
    {
        type = type == null ? "" : type;
        htmlRef.fadeIn('slow');
        htmlRef.attr("class", "message " + type);
        htmlRef.find( "p" ).html(message);
		
		if( jQuery.browser.msie && jQuery.browser.version == "6.0" )
			htmlRef.css('top', jQuery(window).scrollTop() + 100);
        
		jQuery('body').mousemove(startHide);

    };

    function startHide()
    {
        jQuery('body').unbind('mousemove', startHide);
        var htmlRef = htmlRef;
        setTimeout(hide, 3500);
    };

    function hide()
    {
        htmlRef.fadeOut('slow');
    };
})();

jQuery( Message.init );

jQuery(function()
{
    jQuery.fn.resetDefaultValue = function()
    {
        function _clearDefaultValue()
        {
            var _$ = jQuery(this);
            if (_$.val() == this.defaultValue) { _$.val(''); }
        };
        function _resetDefaultValue()
        {
            var _$ = jQuery(this);
            if (_$.val() == '') { _$.val(this.defaultValue); }
        };
        return this.click(_clearDefaultValue).focus(_clearDefaultValue).blur(_resetDefaultValue);
    }
});

$( function()
{
	var functions = new Functions();
});

