$(function(){
	BrowserDetection.init();
	Address.init();
	Menu.init();
	CustomButtons.init();
	CustomAnimations.init();
	RadioDakota.init();
	Modal.init();
});
//
var Modal = {
	current: '',
	init: function ()
	{
		$('#nav').find('.open-modal').bind('click', Modal.menuClick);
		$('.open-tooltip').hover(function(){
			$('.em-breve').fadeInIE(200);
		}, function(){
			$('.em-breve').fadeOutIE(200);
		});
	},
	menuClick: function (e)
	{
		e.preventDefault();
		e.stopImmediatePropagation();
		var modal_id = $(this).href().replace('#','');
		Modal.open(modal_id);
	},
	open: function (modal_id)
	{
		var $modal = $('#' + modal_id);
		if($modal.length == 1)
		{
			Modal.current = modal_id;
			Menu.mark(modal_id);
			Controller[modal_id].setElement($modal);
			Controller[modal_id].load.complete();
		}
	},
	close: function ()
	{
		Modal.current = '';
		Menu.mark(Pages.current);
	}
}
var CustomAnimations = {
	init: function()
	{
		$('.replacement').find('span').css('opacity', 0);
		CustomAnimations.social();
		if(BrowserDetection.browser == 'ie' && BrowserDetection.version <= 8)
		{
			return false;
		}
		CustomAnimations.logo();
	},
	social: function()
	{
		$('#social').find('a').hover(
			function(){
				$(this).stop(true, true).opacity(.5, 'normal');
			},
			function(){
				$(this).stop(true, true).opacity(1, 'fast');
			}
		);
	},
	logo: function()
	{
		$('#header h1 a').hover(
			function()
			{
				$(this).find('span').stop().opacity(1, 'normal');
			},
			function()
			{
				$(this).find('span').stop().opacity(0, 'fast');
			}
		);
	}
}
//
var CustomButtons = {
	buttons: new Array,
	init: function()
	{
		if(BrowserDetection.browser == 'ie' && BrowserDetection.version < 9)
		{
			$('.button').bind({
				deactive: CustomButtons.deactive,
				active: CustomButtons.active
			});
			return;
		}
		CustomButtons.buttons = $('.button');
		$.each(CustomButtons.buttons, function(){
			var $button = $(this);
			if($button.find('.over, .out').length < 1)
				$button.append('<span class="over transparent" /><span class="out" />');
			$button.bind({
				mouseenter: CustomButtons.overIn,
				mouseleave: CustomButtons.overOut,
				deactive: CustomButtons.deactive,
				active: CustomButtons.active
			});
		});
	},
	overIn: function(e)
	{
		e.preventDefault();
		e.stopImmediatePropagation();
		var $self = $(this);
		if($self.hasClass('active') === false)
		{
			$self.find('.out').stop(true, true).opacity(0, 'fast');
			$self.find('.over').stop(true, true).opacity(1, 'normal');
		}
	},
	overOut: function(e)
	{
		e.preventDefault();
		e.stopImmediatePropagation();
		var $self = $(this);
		if($self.hasClass('active') === false)
		{
			$self.find('.over').stop(true, true).opacity(0, 'fast');
			$self.find('.out').stop(true, true).opacity(1, 'normal');
		}
	},
	deactive: function ()
	{
		$(this).removeClass('active').trigger('mouseleave');
	},
	active: function ()
	{
		$(this).trigger('mouseenter').addClass('active');
	}
}
//
var Pages = {
	last: '',
	current: '',
	sections: ['home', 'camaleometro', 'colecao', 'campanha', 'universo', 'contato', '404'],
	opts: {
		home: {
			hasSub: true
		},
		camaleometro: {
			hasSub: true
		},
		colecao:	{
			hasSub: true
		},
		contato:	{
			hasSub: true
		}
	},
	rewrites: {
		'onde-comprar' : 'ondecomprar'
	}
}
//
var Address = {
	instance: {},
	lastHashes: new Array,
	currentHashes: new Array,
	// inicia o controle de hash
	init: function()
	{
		Address.instance = $.History;
		$.History.bind(Address.change);
		if($.History.getHash() == '')
			$.History.go('/home');
	},
	// monitora a troca de hash na url
	change: function(hashes)
	{
		var h = Address.cleanHash(hashes);
		
		Address.lastHashes = Address.currentHashes;
		Address.currentHashes = h;
		// verifica se a url está no array de páginas
		if(Address.inArray(h[0], Pages.sections))
		{
			Pages.last = Pages.current;
			Pages.current = h[0];
		}
		// verifica se a url atual tem "rewrite"
		else if(Pages.rewrites[h[0]] != undefined)
		{
			Pages.last = Pages.current;
			Pages.current = Pages.rewrites[h[0]];
		}
		// se a página não existir
		else
		{
			//console.log('404');
			return;
		}
		var track_page = h[0];
		// se a página atual for diferente da ultima página, aciona o
		// controle do menu
		if(Pages.current != Pages.last)
			Menu.mark(h[0]);
		// se a última página for igual a atual e essa página tiver
		// subpáginas acessa o método de "hashChange" do Controller
		if(Pages.last == Pages.current && Pages.opts[Pages.current] != undefined && Pages.opts[Pages.current].hasSub != undefined && Controller[Pages.current] != undefined)
		{
			Controller[Pages.current].hashChange(Address.currentHashes.slice(1, Address.currentHashes.length));
			track_page += '/' + h[1];
			if(h[1] == 'video')
				track_page += '/' + h[2];
		}
		// fecha a última página acessada
		else if(Pages.last != '')
			Controller.close()
		// carrega a página atual
		else
			Controller.load();
			
		track_page.replace('undefined', '');
		track_page.replace(undefined, '');
		
		if(track_page == '/colecao/undefined')
			track_page = '/colecao';
		
		// track no analytics
		_gaq.push(['_trackPageview', "/"+track_page]);
		
		// $(document).attr('title', 'Dakota - ' + track_page);
		// document.title = 'Dakota - ' + track_page;
		// console.log('track_page: ' + track_page);
		// console.log('titulo: ' + document.title);
	},
	// tirar as barras repetidas da url
	cleanHash: function(hashes)
	{
		var re = /[\/]{2,9999}/i;
		hashes = hashes.replace(re, '/').split('/');
		hashes = Address.clean(hashes, '');
		return hashes;
	},
	// retira os items que tenham o "value" do array
	clean: function(arr, value)
	{
		for(var i = 0; i < arr.length; i++){
			if(arr[i] == value){
			arr.splice(i, 1);
			i--;
			}
		}
		return arr;
	},
	// verifica se um valor existe em um array
	inArray: function(value, arr)
	{
		for(var i in arr)
		{
			if(arr[i] == value)	return true;
		}
		return false;
	}
}
//
var Menu = {
	hasActive: false,
	currentPage: '',
	items: ['colecao', 'revista', 'novidades', 'campanha', 'universo', 'onde-comprar', 'contato'],
	colors: ['#CCCCCC', '#CE4E63'],
	init: function()
	{
	$('#nav').find('a').bind('mouseenter mouseleave', Menu.over);
	$('#nav').find('a:not(.open-modal)').bind('click', Menu.click);
	},
	click: function(e)
	{
	e.preventDefault();
	var $self = $(this);
	Navigation.go($self.href().replace('#',''));
	},
	mark: function(page)
	{
	if(Menu.hasActive)
		Menu.applyColor($('#nav-' + Menu.currentPage), 'mouseleave', false);
	Menu.hasActive = $.inArray(page, Menu.items) > -1 ? true : false;
	Menu.currentPage = page;
	if(Menu.hasActive)
		Menu.applyColor($('#nav-' + Menu.currentPage), 'mouseenter', true);
	},
	over: function(e)
	{
	e.preventDefault();
	var $self = $(this);
	if($self.data('active') !== true)
		Menu.applyColor($self, e.type);
	},
	applyColor: function ($elm, event, dataActive)
	{
	var color = event == 'mouseenter' ? Menu.colors[0] : Menu.colors[1];
	if(dataActive != undefined)
		$elm.data('active', dataActive);
	$elm.stop().animate({
		color: color
	}, 'normal');
	}
}
//
Navigation = {
	active: true,
	init: function()
	{
	$('a[rel="navigation"]').bind('click', Navigation.go);
	},
	click: function(e)
	{
	if(e != undefined) e.preventDefault();
	Navigation.go($(this).href().replace('#',''));
	},
	go: function(href)
	{
	if(Navigation.active)
	{
		$.History.go(href);
	}
	},
	control: function(active)
	{
	active = active || true;
	Navigation.active = active;
	}
}
//
var RadioDakota = {
	init: function()
	{
		$('#radio-dakota-swf').flash({
			swf: box3document.baseURL + 'assets/site/flash/radio/bin/RadioDakotaVerao.swf',
			id: "radio-dakota-swf-swf",
			width: '100%',
			height: '100%',
			wmode: "transparent",
			flashvars: 'baseURL=' + box3document.baseURL + 'assets/site/flash/radio/bin/',
			allowScriptAccess: "sameDomain",
			allowFullScreen: true,
			hasVersion: 10
		})
	
		if($('#radio-dakota').length == 1)
		{
			//$('#radio-dakota').height(100).children().height(100);
			
			$('#radio-dakota').bind('mouseenter mouseleave', RadioDakota.mouseOver);
			
			setTimeout(function () { $('#radio-dakota, #radio-dakota-swf').trigger('mouseenter').trigger('mouseleave') }, 5000);
			
			//$('#radio-dakota').children().height(100);
		}
		
		
	},
	mouseOver: function(e)
	{
		e.preventDefault();
		e.stopImmediatePropagation();
		var newHeight = e.type == 'mouseenter' ? 450 : 50;
		var newTop = e.type == 'mouseenter' ? 5 : 55;
		var newHeightSWF = e.type == 'mouseenter' ? 450 : 100;
		var newTopSWF = e.type == 'mouseenter' ? 0 : -50;
		var $elm = $(this);
		var $children = $elm.children();
		$elm.css({
			height: newHeight,
			top: newTop
		});
		$children.css({
			height: newHeightSWF,
			top: newTopSWF
		});
	},
	stopSound: function ()
	{
		var radio = box3flash.get('radio-dakota-swf-swf');
		radio.pauseRadio();
	}
};
//
var Popup = {
	open: function (estado, referencia)
	{
		referencia = (referencia == undefined) ? '' : referencia;
		var url = box3document.baseURL + 'site/ondecomprar/popup/' + estado + '/' + referencia;
		var popup_params = 'width=860,height=588,scrollbars=1,resizable=0,menubar=0,toolbar=0,status0=';
		window.open(url, 'buscaLojas', popup_params);
	}
}

