/*  
    Document    : application.js
    Author      : W3haus - FrontEnd Team
    Summary     :
        | jQuery variables
        | universal variables
        | customFade
        | embedFlash
        | modal
        | playVideo
        | resizePage
        | toggleControls
        | window.ready functions

*/
      
var $nav_head = $('nav#nav .header');
var $nav_head_menu = $('nav#nav .header .menu');
var $nav_head_menu_more = $('nav#nav .header .menu-more');
var $nav_head_menu_less = $('nav#nav .header .menu-less');
var $nav_header = $('nav#nav .content header').hide();
var $nav_section = $('nav#nav .content section').hide({height:0});
$.current_location = '';

(function($,win) {
    
    /* +jQuery variables */
    var $isIE = ($.browser.msie) ? true : false;
    var $html = $('html');
    var $navElement = $('#nav');
    var $logoElement = $('#logo');
    var $bottomElements = $('#info');
    var $modal = $('.modal');
    var $modalOverlay = $('.modal .overlay');
    var $modalClose = $('.modal a.close');
    var $modalWrapper = $('.modal .wrapper');
    var $modalContent = $('.modal .wrapper .content');
    var $modalBack = $('.modal a.back');
    var $box_testimonial = $('nav#nav .content .box');
    var $box_testimonial_img = $('nav#nav .content .box article.testimonial img'); 
    /* end:jQuery variables */
    
    /* +universal variables */
    var imageWidth = 931;
    var imageHeight = 694;
    var imageRatio = (imageHeight/imageWidth).toFixed(2);
    var defaultSpacing = 36;
    var bottomSpacing = 0;
    var logoSpacing = 10;

    var route_actions = [
        '^home',
        '^noticias$',
		'^noticias/.*$',
		'^o-empreendimento$',
		'^o-empreendimento/.*$',
		'^palavra-do-presidente$',
		'^palavra-do-presidente/.*$',
		'^diferenciais$',
		'^diferenciais/.*$',
        '^passeio-virtual$',
        '^galeria$',
		'^galeria/categoria/.*$',
		'^galeria/.*$',
        '^faq$',
        '^imprensa$',
        '^comercial$',
        '^depoimentos$',
		'^depoimentos/.*$',
		'^depoimentos/enviar$',
		'^espaco-do-torcedor$'
    ];
    var routes = new RegExp('('+route_actions.join('|')+')', 'gi');
    /* end:universal variables */
   
   /* +modalApp */
    $.modalApp = {
        
        Class: function(className) {        	
            
            var $this = this;
            
            $this.opts = {className: className};
            
            $this.init = function(options) {
                
                $this.opts = $.extend({}, $this.opts, $.modalApp.defaults);
		        var content = $('.modal .wrapper section:first');
		        var options = {
		            from: {top: '-50%'},
		            to: {top: '0'}
		        };
		        var socialButton = $('.modal .wrapper section article article .social-buttons');
		        
		        var last_faq = null;
		        $('.modal .wrapper ul.news.faq p').hide();
		        $('.modal .wrapper ul.news.faq h1 a').click( function() {
		        	var current_faq = $(this).closest('li');
		        	if (last_faq !== null) {
		        		if (last_faq.index() === current_faq.index()) {
		        			return false;
		        		} else {    			
			        		last_faq.find('p').slideUp();
                            last_faq.find('article').removeClass('open');
		        		};
		        	};
		        	current_faq.find('p').stop(1, 1).slideDown();
                    current_faq.find('article').addClass('open');
		        	last_faq = current_faq;
					return false;
		        });
		        
                if ($('.social-news').size() === 1) {
                    content
                        .css(options.from)
                        .animate(options.to, 1500, 'easeOutExpo', function() {
                            socialButton.animate({right: 0}, 800);
                        });
                    socialButton.css({
                            height: $('.modal .wrapper section article article ul').innerHeight(),
                            right: '50%'
                        });
                };
		        $("#slideshow")
                    .tabs({
                        ajaxOptions: {
                            success: function() {
                                $modalContent.css({'min-height':$(win).height()-68});
                            }
                        },
						select: function() {
							$('p.legend').html('');
						},
						load: function(event, ui) {
							$('p.legend').html($('#' + ui.panel.id + ' .mediaDescription').val());
						},
						show: function(event, ui) {
							if(ui.panel.id == 'current-slide') {
								$('p.legend').html($('#current-slide .mediaDescription').val());
							}
						}
                    });
                $('#slideshow .ui-tabs-panel:last').after($('.carrousel'));
				$( ".tabs-bottom .ui-tabs-nav, .tabs-bottom .ui-tabs-nav > *" )
                    .removeClass( "ui-corner-all ui-corner-top" )
                    .addClass( "ui-corner-bottom" );
                    
                $('.modal a.scrollTo').click( function() {
                    var rel = $(this).attr('rel');
                    $("#modal #wrapper").animate({
                        scrollTop: $(rel).offset().top
                        }, 500);
                    return false;
                });
                
                $('.modalLogo').unbind().click(function(){
                    $modalClose.click();
                    return false;
                });
                
                if (isMobile === true) {
                    $modalContent
                        .css({'height':$(win).height() - 68})
                        .bind('touchmove', function(e) {
                            e.originalEvent.preventDefault();
                        });
                    $modalWrapper.css({
                        'overflow': 'hidden'
                    });
                    myScroll = new iScroll($('.modal .wrapper .content')[0]);
			    } else {
                    $modalContent.css({'min-height':$(win).height()-68});                
                };
                
                return;

            };
            
            return $this;
        },
        
        defaults : {
            className: 'default'
        },
        
        _instances: {},
        
        instance: function(className) {
            if (className === undefined) {
                className = $.modalApp.defaults.className;
            };
            return $.modalApp._instances[className] = $.modalApp._instances[className] || new $.modalApp.Class(className);
        }
        
    };
    /* end:modalApp */
   
    /* +customFade */
    $.customFade = function(element, type, speed, callback) {
		speed = (speed) ? speed : '';
		callback = (callback) ? callback : function(){};
        
		if ($isIE) {
			if (type === 'show') {
				element.show();
			} else {
				element.hide();
			};
		} else {
			if(type === 'show') {
				element.fadeIn(speed);
			} else {
				element.fadeOut(speed);
			};
		}
        
        callback();
	};
    /* end:customFade */
    
    /* +embedFlash */
    $.embedFlash = function() {
        swfobject.embedSWF(rootUrl + "public/swf/cube.swf", "cube", "168", "145", "9.0.0",rootUrl + "public/swf/expressInstall.swf", {arena_url : rootUrl}, {wmode:"transparent"}, {});
    }
    /* end:embedFlash */
    
    /* +modal */
    $.modal = {
        init : function() {
            $modalClose.click(function() {
                $.modal.destroy();
                $modalBack.hide();
				_gaq.push(['_trackPageview']);
                window.location.href = '#!/home';
                return false;
            });
        },
        set : function(html, cssClass, callback) {
            cssClass = (cssClass) ? $modalWrapper.addClass(cssClass) : '';
            callback = ($.isFunction(callback)) ? callback : $.noop;
            
            $modalContent.html(html);
            $.customFade($modal, 'show', 400, function(){
                $.toggleControls(false, function(){
                    callback();
                    var last_url = this.href;
                    $('.modal .modalLink').bind('click.modalClick', function() {
                        $.openModal(this.href);
                        $modalBack.show().unbind('click').bind('click', function() {
                            history.back(-1);
                            return false;
                        });
                        return false;
                    });
                });
            });
        },
        destroy : function(callback) {
            callback = ($.isFunction(callback)) ? callback : $.noop;
            
            $modalWrapper.removeAttr('class').addClass('wrapper');
            
            $modalContent.html('');
            $.customFade($modal, 'hide', 400, function(){
                $.toggleControls(true, function(){
                    callback();
                });
            });
        }
    }
    /* end:modal */
    
    /* +playVideo */
    $.playVideo = function() {
        $('a.play-video').click(function(){
            var $this = $(this);
            var html = '<div id="flashcontent"></div>';
            var videoId = $this.attr('rel');
			_gaq.push(['_trackPageview', '/depoimentos/'+$.trim($this.next().text())]);
            $.modal.set(html, 'video', function(){
                var flashvars = {video_id:videoId};
                var params = {
                    menu: "false",
                    allowScriptAccess: "always",
                    scale: "noscale",
                    wmode: "transparent"
                };
                var attributes = {};

                swfobject.embedSWF(rootUrl + "public/swf/player.swf", "flashcontent", "100%", "100%", "9.0.0", "_assets/swf/expressInstall.swf", flashvars, params, attributes);
                SWFID = "flashcontent";
            });
            return false;
        });
    }
    /* end:playVideo */
    
    /* +resizePage */
    $.resizePage = function() {
        var height = $(win).height();
        $modalOverlay.height(height);
        if (isMobile === true) {
            $modalContent.css({'height':height});
        } else {
            $modalContent.css({'min-height':height-68});
        }
        
        var division = (height/$(win).width()).toFixed(2);
        var options = {width : '100%', height : '100%', margin: '0'};
        if(division < imageRatio) {
        	options.height = 'auto';
        } else if(division > imageRatio) {
            options.width = 'auto';
        };
        $('#content .photo').css(options);
        
        if (height < 650) {
            $box_testimonial.addClass('box-testimonial-hide');          
            if($.browser.msie && $.browser.version == 7) {               
                $box_testimonial_img.css({'margin-left':'-999999px'});
            } else {
                $box_testimonial_img.hide();
            }
        } else {
            if ($box_testimonial.hasClass('box-testimonial-hide')) {
                $box_testimonial.removeClass('box-testimonial-hide');
                $box_testimonial_img.css({'margin-left':'0px'});
				$box_testimonial_img.show();
            };
        }
    }
    /* end:resizePage */
    
    /* +timeLapseTooltip */
    $.timeLapseTooltip = function() {
        $('.tooltip a.close').click(function(){
            $.customFade($(this).closest('.tooltip'), 'hide', 400);
            return false;
        });
    }
    /* end:timeLapseTooltip */
    
    /* +toggleControls */
    $.toggleControls = function(show, callback) {
        callback = (callback) ? callback : function(){};
        
        if(show === true) {
            $navElement.animate({
                'top' : defaultSpacing + 'px'
            }, 500);
            $logoElement.animate({
                'top' : logoSpacing + 'px'
            }, 500);
            $bottomElements.animate({
                'bottom' : bottomSpacing + 'px'
            }, 500, callback);
        } else {
            var navHeight = ($('#nav').height() + defaultSpacing) * (-1);
            var bottomHeight = (144 + defaultSpacing) * (-1);
            
            $navElement.animate({
                'top' : navHeight + 'px'
            }, 300, '');
            $logoElement.animate({
                'top' : navHeight + 'px'
            }, 400, '');
            $bottomElements.animate({
                'bottom' : bottomHeight + 'px'
            }, 500, '', callback);
        }
    }
    /* end:toggleControls */
	
	/* +navHead */
	$.navHead = function() {
		
		var $this = this;
		
		var stage = 0;
		
		$this.showMenu = function() {
			$nav_head
                .stop(1, 1)
				.css({'border-radius': '6px'})
				.animate({
					'width': '250px'
				}, 250);
		};
		
		$this.changeStage = function() {
			switch (stage) {
				case 0:
					$nav_head_menu_less.fadeOut();
					$nav_head_menu_more.fadeOut();
					if ($nav_header.is(':visible')) {
						$nav_section.slideUp(250, 'easeOutCubic', function() {
							$nav_header.slideUp(250, 'easeOutCubic', function() {
								$this.showMenu();
							});
						});
					} else {
						$this.showMenu();
					};
				break;
				case 1:
					$nav_head
                        .stop(1, 1)
                        .css({
							'border-radius': '6px 6px 0 0'
                        })
						.animate({
							'width': '100%'
						}, 250, function() {
							$nav_header.slideDown(500, 'easeInOutExpo', function() {                            
                                $nav_head.width('100%');
                            });
						});
					$nav_head_menu_less.fadeIn();
					$nav_head_menu_more.fadeIn();
					$nav_section.slideDown(500, 'easeInOutExpo', $.noop);
				break;
			};
		};
		
		$nav_head
			.css({
				'border-radius': '12px',
				'width': '250px'
			});
			
		$nav_header.hide();
		$nav_section.hide();
		
		$this.changeStage();
		
        $nav_head_menu
            .bind('click.nav_head_menu', function() {
				switch (stage) {
					case 0:
						stage = 1;
					break;
					case 1:
						stage = 0;
					break;
				};
				$this.changeStage();
				return false;
			});
		
		$nav_head_menu_less
            .bind('click.nav_head_menu_less', function() {
				stage--;
				$this.changeStage();
				return false;
			});
		
		$nav_head_menu_more
            .bind('click.nav_head_menu_more', function() {
				if (stage < 2) {
					stage++;
					$this.changeStage();
				};
				return false;
			});        
	};
	/* end:navHead */
	
	/* ga */
	document.onclick = function (event) {
	
		event = event || window.event;
		var target = event.target || event.srcElement,
		targetElement = target.tagName.toLowerCase();

		if (targetElement == "a") {
            var href = target.getAttribute("href"),
            urlHost = document.domain.replace(/^www\./i, ""),
			urlPattern = "^(?:https?:)?\/\/(?:(?:www)\.)?" + urlHost + "\/?";
			if (href) {
				eventCheck(href, urlPattern);
			};
		};

		function eventCheck(href, urlPattern) {
			if ((href.match(/^https?\:/i)) && (!href.match(urlPattern))) {
				if (href.match(/^.*\.(pdf|jpg|png|gif|zip|mp3|txt|doc|rar|js|py)$/i)) {
					_gaq.push(['_trackEvent', 'Download', 'click', href]);
				} else {
					_gaq.push(['_trackEvent', 'External', 'click', href]);
				}
			} else if (href.match(/^mailto\:/i)) {
					_gaq.push(['_trackEvent', 'Email', 'click', href.substr(7)]);
			} else if (href.match(/^.*\.(pdf|jpg|png|gif|zip|mp3|txt|doc|rar|js|py)$/i)) {
					_gaq.push(['_trackEvent', 'Download', 'click', href]);
			};
		};
	};
	/* end ga */

    
    /* +window.ready and window.load functions */
    $(win).ready(function() {
        
        $html.browser();
      
        $(win).resize(function() {
            $.resizePage();
        });
        
        $.modal.init();
        
        $.playVideo();
        
        $.timeLapseTooltip();
        
        if (isMobile) {	
			$.cubeCanvas.instance().init({
				container: $('#logo')
			});
        } else {    
            $.embedFlash();
        };
        
		$.navHead();
		
		$.openModal = function(href, change_hash) {
            $modalWrapper.scrollTop(0);
            $.ajax({
                url: href,
                success: function(request) {
                    $.modal.set(request, '', function() {
                        var new_location = href.replace(rootUrl, '');
                        window.location.href = '#!/'+new_location;
                        $modalContent.attr('rel', new_location).show();
                        $.modalApp.instance().init();
                    });
                },
                dataType: 'html' 
            });
        };
        $('.modalLink').bind('click.modalClick', function() {
            $.openModal(this.href);
            return false;
        });        

        $.current_location = window.location.href.replace(/.*#!\//, '');
		
		var foto = $.current_location.split('?foto=');
		if (foto[1] !== undefined) {
			$.current_location = foto[0];
			foto = foto[1]*1;
			if (foto > 0) {
				$('#slider').slider({'value': foto});
				foto = '?foto='+foto;
			} else {
				foto = '';
			}
		} else {
			foto = '';
		};
		
        if ($.current_location.match(routes) && $.current_location != 'home') {
            $.openModal($.current_location);
        } else {
            $.current_location = 'home'+foto;
            window.location.href = '#!/home'+foto;
        };
        
        // Navegação
        $(win).bind('hashchange', function() {
            $.current_location = window.location.href.replace(/.*#!\//, '');
			
			var foto = $.current_location.split('?foto=');
			if (foto[1] !== undefined) {
				$.current_location = foto[0];
				foto = foto[1]*1;
				if (foto > 0) {
					$('#slider').slider({'value': foto});
					foto = '?foto='+foto;
				} else {
					foto = '';
				}
			} else {
				foto = '';
			};
			
            if ( ! $.current_location.match(routes)) {
                return;
            };
            if ($modalContent.attr('rel') !== $.current_location) {
                if ($.current_location === 'home') {
                    $modalContent.attr('rel', 'home');
                    $modalClose.click();
                } else {                
                    $.openModal($.current_location, true);
                };
            };
        });
       
        $('.tooltip').fadeIn();

        $(".infoBox a")
            .mouseover(function(){
                $(this).parent().find("div").stop(1,1).show();
            })
            .bind("mouseout",function(){
                $(this).parent().find("div").stop(1,1).hide();
            });
       
       $.resizePage();
       
       $('.ui-slider-handle').focus();
       
       $('.box-tour a').live('click', function(){          
           $('.tour-arena').hide();
           $('.box-tour a').removeClass('active');
           $('#'+$(this).attr('rel')).show();          
           $(this).addClass('active');          
           return false;
       });
       
    })  
    /* end:window.ready */    
    
})(jQuery, window);
