var front = {};
$(function(){

    front = {
    
        init: function(){
        
            var body = $('body');
            
//            SWFAddress.onChange = function(){
//            
//                var baseURL = window.location.protocol + "//" + window.location.hostname;
//                
//                if (window.location.pathname != "/") {
//                
//                    window.location.href = baseURL + "/#" + window.location.pathname;
//                    
//                }
//                else {
//                
//                    var content = $("#content");
//                    var loadingEl = $("body");
//                    
//                    loadingEl.showLoading();
//                    
//                    $.get(SWFAddress.getValue(), function(response){
//                    
//                        loadingEl.hideLoading();
//                        content.html(response);
//                        
//                        var bodyWidth = body.width();
//                        if (bodyWidth < 1220) {
//                            var w = (1220 - bodyWidth) / 2;
//	                        $(document).scrollLeft(w);
//                        }
//                        
//                    });
//                    
//                }
//                
//            }
            if (window.location.hash && ('#/' == window.location.hash.substring(0,2))){
            	window.location.href = window.location.hash.substring(1);
            }
            
            this.initSlider();
            
            $( 'nav > ul li' ).hover(		
                function () {
                	var jqThis = $(this);
                	
                	if(!jqThis.hasClass('active')) {		
                		var jqUl = jqThis.parent().find('ul').hide();                		
                		var jqUl1 =  jqThis.find('ul').addClass('hover').show();
                	}
                },
                function () {
                	var jqThis = $(this);
                	if(!jqThis.hasClass('active')) {
	                	jqThis.find('ul').removeClass('hover');
	                	jqThis.parent().find('.active').find('ul').show();
                	}
                	
                }
           );
            
           
              
        },

        getCurrentUrl: function(){
        
            var baseURL = window.location.protocol + "//" + window.location.hostname;
            var currentUrl = baseURL + SWFAddress.getValue();
            
            return currentUrl;
        },
        
        index: function(){
        
            var self = this;
            
            var flashvars = {
                xml: "/xml/vgallery.xml"
            };
            
            //VIDEO PLAYER
            this.videos = function(){
            
                var width = 296;
                var height = 330;
                var params = {
                    menu: "false",
                    allowScriptAccess: "always",
                    scale: "noscale",
                    allowFullScreen: "true"
                };
                var attributes = {};
                
                
                swfobject.embedSWF("/swf/video_gallery.swf", "videos", width, height, "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);
                SWFID = "videos"
                
            }
            
            //AUDIO PLAYER
            this.audios = function(){
            
                var awidth = 296;
                var aheight = 330;
                var aparams = {
                    menu: "false",
                    allowScriptAccess: "always",
                    scale: "noscale",
                    allowFullScreen: "true"
                };
                var aattributes = {};
                
                swfobject.embedSWF("/swf/audio_player.swf", "audios", awidth, aheight, "9.0.0", "/swf/expressInstall.swf", flashvars, aparams, aattributes);
                SWFID = "audios";
                
            }
            
            var width = 720;
            var height = 90;
            var flashvars = {};
            var params = {
                menu: "false",
                allowScriptAccess: "always",
                scale: "noscale",
                allowFullScreen: "true"
            };
            var attributes = {};

            front.bannerCounter = window.parseInt($('#footerBannerContainer').data('bannercounter'),10);
            front.changeFooterBanner();
            
            //INICIALIZA WIDGET DO TWITTER
            
            if (SWFAddress.getValue() == "/") {
            
                $.getScript("http://widgets.twimg.com/j/2/widget.js", function(){
                
                    new TWTR.Widget({
                        id: 'twitterContent',
                        version: 2,
                        type: 'profile',
                        rpp: 4,
                        interval: 6000,
                        width: 'auto',
                        height: 300,
                        theme: {
                            shell: {
                                background: '#333333',
                                color: '#ffffff'
                            },
                            tweets: {
                                background: '#000000',
                                color: '#ffffff',
                                links: '#4aed05'
                            }
                        },
                        features: {
                            scrollbar: false,
                            loop: false,
                            live: false,
                            hashtags: true,
                            timestamp: true,
                            avatars: false,
                            behavior: 'all'
                        }
                    }).render().setUser('figueirensefc').start();
                    
                });
                
            }
            
            
            $(".desaturate img").pixastic("desaturate");
           
            
            
            $('.scroll-pane').jScrollPane();
         
         
            
            $(".tabs").delegate(".tabLinks", "click", function(){
            
                $(this).parents('#tabs').find(".tabLinks").not(this).each(function(n, v){
                    $(v).html('<a style="cursor: pointer;">' + $(v).text() + '</a>');
                });
                
                $(this).html($(this).text());
                
                $(this).parents('#tabs').find(".tabContent, object").hide();
                
                //ID REFERENTE A DIV DE CONTEUDO CORRESPONDENTE
                var idTabTarget = $(this).attr("id").replace('tab', '');
                
                idTabTarget = idTabTarget.toLowerCase();
                
                //EXECUTA SOMENTE SE FOR ALGUNS DOS LINK RELACIONADOS A MULTIMIDIA
                if ($(this).parents('.tabs').hasClass('tabsMultimidia')) {
                
                    $("#videos").replaceWith('<div id="videos" class="tabContent">');
                    $("#audios").replaceWith('<div id="audios" class="tabContent">');
                    
                }
                
                //INICIALIZA O PLAYER DE VIDEO OU AUDIO
                if (idTabTarget == "videos" || idTabTarget == "audios") {
                
                    self[idTabTarget]();
                    
                }
                
                $("#" + idTabTarget).show();
                
            });
            
            //INICIALIZA TAB NOTICIA
            $(".tabLinks").eq(0).click();
            
            //INICIALIZA TAB FOTOS
            $(".tabLinks").eq(3).click();
            
            
            
            //INICIALIZA ENQUETE
            
            $.getJSON("/enquete", function(response){
            
                if (response) {
                
                    if (response.respostas) {
                    
                        var config = {
                            ajaxOpts: {
                                url: "/enquete/voto"
                            },
                            groupName: "enquete_resposta_id",
                            groupData: response.respostas,
                            pollHeading: response.pergunta,
                            //				  rowClass: "",
                            errors: true || false
                        }
                        
                        $("#pollContent").jPoll(config);
                        
                    }
                    
                }
                
            });
            
        },
        
        multimidia: function(){
            $("#thumbs").delegate('a', 'click', function(){
            
                $("#photo").find('img').showLoading({
                    'addClass': 'loading-overlay-bg'
                });
                
                //CORRIGE POSICAO E TAMANHO DO OVERLAY
                var loadingOverlayBg = $('.loading-overlay-bg');
                var loadingIndicatorOverlay = $('.loading-indicator-overlay');
                
                loadingOverlayBg.width(loadingIndicatorOverlay.outerWidth());
                loadingOverlayBg.height(loadingIndicatorOverlay.outerHeight());
                loadingOverlayBg.css('top', loadingIndicatorOverlay.position().top);
                loadingOverlayBg.css('left', loadingIndicatorOverlay.position().left);
                
                var img = new Image();
                
                // wrap our new image in jQuery, then:
                $(img).load(function(){
                    // set the image hidden by default    
                    $(this).hide();
                    
                    $("#photo").find('img').remove();
                    $("#photo").prepend(this);
                    $("#photo").find('img').hideLoading();
                    
                    // fade our image in to create a nice effect
                    $(this).fadeIn();
                }).error(function(){
                    // notify the user that the image could not be loaded
                }).attr('src', $(this).attr('href'));
                
                $("#legenda_imagem_selecionada").text($(this).attr('title'));
                
                return false;
            });
            
            $("#photoset").change(function(){
            	//SWFAddress.setValue("/multimidia/fotos/photoset/" + $(this).val());
            	 var baseURL = window.location.protocol + "//" + window.location.hostname;
                 window.location.href = baseURL + "/multimidia/fotos/multimidia/fotos/photoset/" + $(this).val();    
            });
        },
        
        initSlider : function () {
        	$(".paging").show();
        	$(".paging a:first").addClass("active");
        		
        	//Get size of images, how many there are, then determin the size of the image reel.
        	var imageWidth = $(".window").width();
        	var imageSum = $(".image_reel img").size();
        	var imageReelWidth = imageWidth * imageSum;
        	
        	//Adjust the image reel to its new size
        	$(".image_reel").css({'width' : imageReelWidth});
        	
        	//Paging + Slider Function
        	rotate = function(){	
        		var triggerID = $active.attr("rel") - 1; //Get number of times to slide
        		var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

        		$(".paging a").removeClass('active'); //Remove all active class
        		$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
        		
        		//Slider Animation
        		$(".image_reel").animate({ 
        			left: -image_reelPosition
        		}, 500 );
        		
        	}; 
        	
        	//Rotation + Timing Event
        	rotateSwitch = function(){		
        		play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
        			$active = $('.paging a.active').next();
        			if ( $active.length === 0) { //If paging reaches the end...
        				$active = $('.paging a:first'); //go back to first
        			}
        			rotate(); //Trigger the paging and slider function
        		}, 7000); //Timer speed in milliseconds (3 seconds)
        	};
        	
        	rotateSwitch(); //Run function on launch
        	
        	//On Hover
        	$(".image_reel a").hover(function() {
        		clearInterval(play); //Stop the rotation
        	}, function() {
        		rotateSwitch(); //Resume rotation
        	});	
        	
        	//On Click
        	$(".paging a").click(function() {	
        		$active = $(this); //Activate the clicked paging
        		//Reset Timer
        		clearInterval(play); //Stop the rotation
        		rotate(); //Trigger rotation immediately
        		rotateSwitch(); // Resume rotation
        		return false; //Prevent browser jump to link anchor
        	});	
        
        },
        
        atletas: function(){
            $(".acContent:not(:first)").hide();
            $(".handler").click(function(){
                $(".acContent").slideUp("slow");
                $(this).parent().next().slideDown("slow");
                return false;
            });
        },
        
        noticia: function(){
        
            $("#data_inicial, #data_final").datepicker({
                showOn: "button",
                buttonImage: "/img/admin/Icons/cal.png",
                buttonImageOnly: true,
                dateFormat: 'dd/mm/yy'
            }).next('img').css({
                'margin-bottom': '-3px',
                cursor: 'pointer'
            });
            
            $("#filtroNoticiaBtn").button({
                text: "Buscar"
            }).click(function(){
                window.location.href = "/noticia" + "?" + $("#filtroNoticia").serialize();
            })
            
        },
        
        devolucaoIngresso : function () {
        	$('#devolverBtn').click(function(){
        		
                $('#mkDevolucao').ajaxSubmit({
                    dataType: "json",
                    iframe: true,
                    success: function(response){
                    
                        if (response.success) {
                        
                            $("#mkDevolucao").each(function(){
                                $('input,textarea', this).clearFields();
                            });          
                            $.prompt('Mensagem enviada com sucesso');
                            
                        }
                        else {
                        
                            $.prompt('Erro ao enviar a mensagem, tente mais tarde.');
                            
                        }
                        
                    },
                    
                    forceSync: true,
                    
                    beforeSubmit: function(){
                    
                        if (!$("#mkDevolucao").valid()) {
                            return false;
                        }
                        
                    }
                });
            }); 	
        },
               
        contato: function(){
        
            $("#btnEnviar").click(function(){
            
                $("#mkContact").ajaxSubmit({
                    dataType: "json",
                    iframe: true,
                    success: function(response){
                    	$('#captcha-msg-error').remove();
                        if (response.success) {
                        	
                            $("#mkContact").each(function(){
                                $('input,select,textarea', this).clearFields();
                            });
                            $("#contentCurriculo").hide();
                            $.prompt('Mensagem enviada com sucesso');
                            
                        }
                        else {
                        	if(response.msg = "incorrect-captcha-sol"){
                        		$('#captcha-container').append('<p id="captcha-msg-error" style="margin-top: 5px;">Código inválido</p>');
                        	}else{
                        		$.prompt('Erro ao enviar a mensagem, tente mais tarde.');
                        	}
                        }
                        
                        Recaptcha.reload();
                        
                    },
                    
                    forceSync: true,
                    
                    beforeSubmit: function(){
                    
                        if (!$("#mkContact").valid()) {
                            return false;
                        }
                        
                    }
                });
                
            });
            
            $("#mkSubject").change(function(){
                if ($(this).val() == '2') {
                    $("#contentCurriculo").show();
                }
                else {
                    $("#contentCurriculo").hide();
                }
            })
            
            
        },
        fotos: function(){
        
            $('input:text').setMask();
            
            $("#btnEnviarFoto").click(function(){
            
                $("#mkFormFoto").ajaxSubmit({
                    dataType: "json",
                    iframe: true,
                    success: function(response){
                    
                        if (response.success) {
                        
                            $("#mkFormFoto").each(function(){
                                $('input,select,textarea', this).clearFields();
                            });
                            
                            $.prompt('Mensagem enviada com sucesso');
                            
                        }
                        else {
                        
                            $.prompt('Erro ao enviar a mensagem, tente mais tarde.');
                            
                        }
                        
                    },
                    
                    forceSync: true,
                    
                    beforeSubmit: function(){
                    
                        if (!$("#mkFormFoto").valid()) {
                            return false;
                        }
                        
                    }
                });
                
            });
            
        },
        
        imprensa: function(){
        
            $('input:text').setMask();
            
            $("#btnEnviarImprensa").click(function(){
            
                $("#pressContact").ajaxSubmit({
                    dataType: "json",
                    //                    iframe: true,
                    success: function(response){
                    
                        if (response.success) {
                        
                            $("#pressContact").each(function(){
                                $('input,select,textarea', this).clearFields();
                            });
                            
                            $.prompt('Mensagem enviada com sucesso');
                            
                        }
                        else {
                        
                            $.prompt('Erro ao enviar a mensagem, tente mais tarde.');
                            
                        }
                        
                    },
                    
                    forceSync: true,
                    
                    beforeSubmit: function(){
                    
                        if (!$("#pressContact").valid()) {
                            return false;
                        }
                        
                    }
                });
                
            });
            
        },
        
        licenciamento: function(){
        
            $("#btnEnviarLicenciamento").click(function(){
            
                $("#mkContact").ajaxSubmit({
                    dataType: "json",
                    success: function(response){
                    
                        if (response.success) {
                        
                            $("#mkContact").each(function(){
                                $('input,select,textarea', this).clearFields();
                            });
                            
                            $.prompt('Mensagem enviada com sucesso');
                            
                        }
                        else {
                        
                            $.prompt('Erro ao enviar a mensagem, tente mais tarde.');
                            
                        }
                        
                    },
                    
                    forceSync: true,
                    
                    beforeSubmit: function(){
                    
                        if (!$("#mkContact").valid()) {
                            return false;
                        }
                        
                    }
                });
                
            });
            
        },
        
        videos: function(){
        
            var flashvars = {
                xml: "/xml/vgallery_int.xml"
            };
            
            var width = 552;
            var height = 620;
            
            var params = {
                menu: "false",
                allowScriptAccess: "always",
                scale: "noscale",
                allowFullScreen: "true"
            };
            var attributes = {};
            
            
            swfobject.embedSWF("/swf/video_gallery.swf", "vGallery", width, height, "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);
            SWFID = "vGallery";
            
        },
        
        audio: function(){
        
            var awidth = 290;
            var aheight = 346;
            var flashvars = {};
            var aparams = {
                menu: "false",
                allowScriptAccess: "always",
                scale: "noscale",
                allowFullScreen: "true"
            };
            var aattributes = {};
            
            swfobject.embedSWF("/swf/audio_player.swf", "aGallery", awidth, aheight, "9.0.0", "/swf/expressInstall.swf", flashvars, aparams, aattributes);
            SWFID = "aGallery";
            
        },
        
        competicoes: function(objParam){
        
            var param = objParam ? objParam : {};
            $.get("/equipe/competicoes-calendario", param, function(response){
            
                $("#eventCal").hideLoading();
                
                $("#eventCal").html(response);
                $(".date_has_event").tipTip({
                    delay: 100
                });
                
                $(".date_has_event").each(function(){
                    var tmpLink = $(this).find("a");
                    var urlJogo = tmpLink.attr("href");
                    $(tmpLink).replaceWith($(tmpLink).text());
                    
                    $(this).click(function(){
                        $("#tiptip_holder").remove();
                        SWFAddress.setValue(urlJogo);
                    });
                });
                
                var mesAnoSelecinado = $(".mesAnoSelecinado").attr("id").split("_");
                
                $("#mesAnterior").click(function(){
                
                    $("#eventCal").showLoading();
                    
                    front.competicoes({
                        mes: mesAnoSelecinado[0],
                        ano: mesAnoSelecinado[1],
                        mes_anterior: true
                    });
                });
                
                $("#mesProximo").click(function(){
                
                    $("#eventCal").showLoading();
                    
                    front.competicoes({
                        mes: mesAnoSelecinado[0],
                        ano: mesAnoSelecinado[1],
                        mes_proximo: true
                    });
                });
                
            })
            
        },
        
        competicoesTeste: function(objParam){
            
            var param = objParam ? objParam : {};
            $.get("/equipe-teste/competicoes-calendario", param, function(response){
            
                $("#eventCal").hideLoading();
                
                $("#eventCal").html(response);
                $(".date_has_event").tipTip({
                    delay: 100
                });
                
                $(".date_has_event").each(function(){
                    var tmpLink = $(this).find("a");
                    var urlJogo = tmpLink.attr("href");
                    $(tmpLink).replaceWith($(tmpLink).text());
                    
                    $(this).click(function(){
                        $("#tiptip_holder").remove();
                        SWFAddress.setValue(urlJogo);
                    });
                });
                
                var mesAnoSelecinado = $(".mesAnoSelecinado").attr("id").split("_");
                
                $("#mesAnterior").click(function(){
                
                    $("#eventCal").showLoading();
                    
                    front.competicoesTeste({
                        mes: mesAnoSelecinado[0],
                        ano: mesAnoSelecinado[1],
                        mes_anterior: true
                    });
                });
                
                $("#mesProximo").click(function(){
                
                    $("#eventCal").showLoading();
                    
                    front.competicoesTeste({
                        mes: mesAnoSelecinado[0],
                        ano: mesAnoSelecinado[1],
                        mes_proximo: true
                    });
                });
                
            })
            
        },
        

        bannerCounter : 0, //generated with PHP
        changeFooterBanner : function() {
        	if ($('#footerBanner').size() === 0) return; //do nothing if banner not found
        	
        	var width = 720;
            var height = 90;
            var flashvars = {};
            var params = {
                menu: "false",
                allowScriptAccess: "always",
                scale: "noscale",
                allowFullScreen: "true"
            };
            var attributes = {};
            var bannerURL = null;
            
        	if ((front.bannerCounter++ % 2) == 0){
        		bannerURL = "/swf/flageletrosul.swf";
        	} else {
        		bannerURL = "/swf/unimed_bottom.swf";
        	}
        	
        	swfobject.embedSWF(bannerURL, "footerBanner", width, height, "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);	
            SWFID = "footerBanner";
            
            setTimeout('front.changeFooterBanner()', 10000);
        } 
        
    };
    
    front.init();
    
});

$(window).load(function(){
	$('#banner-radio').animate({ marginTop: '+=30' }, 500);
	$('.close-banner-link').click(function() {
		$('#banner-radio').animate({ marginTop: '-=30' }, 500);
		return false;
	});	
});



