//submenu
var submenu  = {
	
	timeout: new Array(),
	
	init: function(){
		$('li.sub').bind('mouseenter', this.abrir).bind('mouseleave', this.fechar);
		$('li.submenu').bind('mouseenter',this.manter).bind('mouseleave', this.fecharsub);
	},
	
	abrir: function(){
		var i = $(this).attr('name');
		clearInterval(submenu.timeout[i]);
		$(this).addClass('active').next().show();
	},
	
	fechar: function(){
		var este = $(this);
		var i = $(this).attr('name');
		submenu.timeout[i] = setTimeout(function(){
			$(este).removeClass('active').next().hide();
		},400);
	},
	
	manter: function(){
		var i = $(this).prev().attr('name');
		clearInterval(submenu.timeout[i]);
	},
	
	fecharsub: function(){
		var este = $(this);
		var i = $(this).prev().attr('name');
		submenu.timeout[i] = setTimeout(function(){
			$(este).hide().prev().removeClass('active');
		},400);
	}
};

//mousehold
jQuery.fn.mousehold = function(timeout, f) {
	if (timeout && typeof timeout == 'function') {
		f = timeout;
		timeout = 100;
	}
	if (f && typeof f == 'function') {
		var timer = 0;
		var fireStep = 0;
		return this.each(function() {
			jQuery(this).mousedown(function() {
				fireStep = 1;
				var ctr = 0;
				var t = this;
				timer = setInterval(function() {
					ctr++;
					f.call(t, ctr);
					fireStep = 2;
				}, timeout);
			});

			clearMousehold = function() {
				clearInterval(timer);
				if (fireStep == 1) f.call(this, 1);
				fireStep = 0;
			};
			
			jQuery(this).mouseout(clearMousehold);
			jQuery(this).mouseup(clearMousehold);
		});
	}
};

// gadget
var barra = {

	offset: 0,
	seta_up: null,
	seta_down: null,
	scroller: null,
	scroll_limit: null,
	dados: null,
	i_clima: 0,
	projeto: null,
	i_projeto: 0,
	hotsite: null,
	i_hotsite: 0,
	timeout: null,

	iniciar: function(){
		if ($('#gadget').length < 1) return false;
		this.seta_up = $('#gadget img.up');
		this.seta_down = $('#gadget img.down');
		this.scroller = $('#gadget .scroller');
		this.montar_projetos();
		this.montar_hotsites();
		this.calc_limit();
		
		$(this.seta_up).mousehold(function(){
			barra.scrolldown();
			return false;
		});
		$(this.seta_down).mousehold(function(){
			barra.scrollup();
			return false;
		});
		$('#gadget .closer a.close').bind('click',function(){
			barra.fechar();
			return false;
		});
		$('#gadget .opener a').bind('click',function(){
			barra.abrir();
			return false;
		});
		$('.content .title-big a').bind('click',function(){
			$('#city_name, #weather, #weather_info, .content form').toggle();
			return false;
		});
		$('#escolher_cidade').bind('click',function(){
			barra.select_cidade();
			return false;
		}).trigger('click');
		$('#gadget td.dia a.left').bind('click',function(){
			barra.prev_clima();
			return false;
		});
		$('#gadget td.dia a.right').bind('click',function(){
			barra.next_clima();
			return false;
		});
		$('#gadget .projeto a.right').bind('click',function(){
			barra.next_projeto();
			return false;
		});
		$('#gadget .projeto a.left').bind('click',function(){
			barra.prev_projeto();
			return false;
		});
		$('#gadget .hotsite a.right').bind('click',function(){
			barra.next_hotsite();
			return false;
		});
		$('#gadget .hotsite a.left').bind('click',function(){
			barra.prev_hotsite();
			return false;
		});
		
		this.timeout = setTimeout(function(){
			$.post('ajax/gadget.php', { act: 'verifica' }, function(response){
				if (response != 1) {
					$('#gadget').addClass('closed');
				}
			});
		}, 10000);
	},
	
	calc_limit: function(){
		var i = setTimeout(function(){
			if (barra.offset < 0) {
				$(barra.seta_up).removeClass('disabled');
			} else {
				$(barra.seta_up).addClass('disabled');
			}
			if (barra.offset >= barra.scroll_limit) {
				$(barra.seta_down).removeClass('disabled');
			} else {
				$(barra.seta_down).addClass('disabled');
			}
			barra.scroll_limit = ($(barra.scroller).height() - $('#gadget .container').height() + 60) * (-1);
		},800);
	},
	
	abrir: function(){
		$('#gadget').removeClass('closed');
		$.post('ajax/gadget.php', { act: 'abrir-gadget' });
	},
	
	fechar: function(){
		$('#gadget').addClass('closed');
		$.post('ajax/gadget.php', { act: 'fechar-gadget' });
	},
	
	scrolldown: function(){
		if (this.offset < 0) {
			$(this.seta_down).removeClass('disabled');
			this.offset = this.offset + 20;
			$(this.scroller).css('margin-top',this.offset + 'px');
		} else {
			$(this.seta_up).addClass('disabled');
		}
	},
	
	scrollup: function(){
		if (this.offset >= this.scroll_limit) {
			$(this.seta_up).removeClass('disabled');
			this.offset = this.offset - 20;
			$(this.scroller).css('margin-top',this.offset + 'px');
		} else {
			$(this.seta_down).addClass('disabled');
		}
	},
	
	// Clima - Tempo Agora
	select_cidade: function(){
		var estado = $('#gadget #estado').val();
		var cidade = $('#gadget #cidade').val();
		if (cidade != '' && estado != '') {
			$.post('ajax/gadget.php', { act: 'select_cidade', cidade: cidade, estado: estado }, function(response){
				if (response[0].data == null || response[0].data == '' || response[0].data == 'undefined') {
					alert('A cidade informada não foi encontrada. Por favor verifique o estado selecionado e se digitou o nome da cidade corretamente.');
				} else {
					barra.dados = response;
					barra.atualiza_clima(0);
					$('#city_name').html(cidade+' - '+estado);
				}
			},'json');
		} else {
			alert('Por favor selecione o estado e preencha o nome de sua cidade.');
		}
		return false;
	},
	
	atualiza_clima: function(){
		
		$('#gadget span.dia').html(this.dados[this.i_clima].dia);
		$('#gadget td.tempo').html(this.dados[this.i_clima].tempo);
		$('#gadget td.max').html(this.dados[this.i_clima].max);
		$('#gadget td.min').html(this.dados[this.i_clima].min);
		$('#gadget td.prec').html(this.dados[this.i_clima].prec);
		$('#gadget td.iuv').html(this.dados[this.i_clima].iuv);
		$('#gadget #weather img').attr({
			src: 'images/climas/' + this.dados[this.i_clima].imagem + '.png',
			alt: this.dados[this.i_clima].tempo,
			title: this.dados[this.i_clima].tempo
		});
		$('.content form').hide();
		$('#city_name, #weather, #weather_info').show();
		this.calc_limit();
	},
	
	next_clima: function(){
		if (this.i_clima < 4) {
			this.i_clima++;
			this.atualiza_clima();
		}
	},
	
	prev_clima: function(){
		if (this.i_clima > 0) {
			this.i_clima--;
			this.atualiza_clima();
		}
	},
	
	zerofill: function(string, fill, fillchar){
		string = String(string);
		var complete = '';
		if (string.length < fill) {
			for (var i = 1; i <= (fill - string.length); i++) {
				complete += fillchar;
			}
		}
		return complete + string;
	},
	
	// IHARA em Ação
	montar_projetos: function(){
		$.post('ajax/gadget.php', { act: 'montar_projetos' }, function(response){
			barra.projeto = response;
			barra.set_projeto();
		},'json');
	},
	
	set_projeto: function(){
		$('#gadget .thumb_projeto a').attr('href',this.projeto[this.i_projeto].url);
		$('#gadget .thumb_projeto img').attr({
			src: 'upload/projetos/logo/thumb/' + this.projeto[this.i_projeto].logo,
			alt: this.projeto[this.i_projeto].nome
		});
		$('#gadget td.nome_projeto').html(this.projeto[this.i_projeto].nome);
		var n = this.zerofill(this.i_projeto + 1, 2, '0');
		$('#gadget span.projeto_count').html(n + '/' + this.zerofill(this.projeto.length, 2, '0'));
		this.calc_limit();
	},
	
	prev_projeto: function(){
		if (this.i_projeto > 0) {
			this.i_projeto--;
			this.set_projeto();
		}
	},
	
	next_projeto: function(){
		if (this.i_projeto < this.projeto.length - 1) {
			this.i_projeto++;
			this.set_projeto();
		}
	},
	
	// Hotsites IHARA
	montar_hotsites: function(){
		$.post('ajax/gadget.php', { act: 'montar_hotsites' }, function(response){
			barra.hotsite = response;
			barra.set_hotsite();
		},'json');
	},
	
	set_hotsite: function(){
		$('#gadget .thumb_hotsite a').attr('href',this.hotsite[this.i_hotsite].url);
		$('#gadget .thumb_hotsite img').attr({
			src: 'upload/hotsites/' + this.hotsite[this.i_hotsite].logo,
			alt: this.hotsite[this.i_hotsite].nome
		});
		$('#gadget td.nome_hotsite').html(this.hotsite[this.i_hotsite].nome);
		var n = this.zerofill(this.i_hotsite + 1, 2, '0');
		$('#gadget span.hotsite_count').html(n + '/' + this.zerofill(this.hotsite.length, 2, '0'));
		this.calc_limit();
	},
	
	prev_hotsite: function(){
		if (this.i_hotsite > 0) {
			this.i_hotsite--;
			this.set_hotsite();
		}
	},
	
	next_hotsite: function(){
		if (this.i_hotsite < this.hotsite.length - 1) {
			this.i_hotsite++;
			this.set_hotsite();
		}
	}
	
};
//banner
var banner = {
	
	offset: 0,
	size: null,
	i: 0,
	interval: null,
	tipos: new Array(),
	timeout: null,
	flashs: new Array(),
	
	start: function(){
		if ($('#banner').length < 1) return false;
		$('#banner a.left').bind('click',this.move_right);
		$('#banner a.right').bind('click',this.move_left);
		$('#banner .balls a').bind('click',function(){
			return banner.move_to($(this).attr('name'));
		});
		this.size = $('#banner .slice').length;
		var x = 0;
		$('#banner .slice').each(function(){
			if ($(this).hasClass('flash')) banner.tipos[x] = 'flash'; else banner.tipos[x] = 'image';
			banner.flashs[x] = $(this).find('object').attr('id') ? $(this).find('object').attr('id') : 0;
			x++;
		});
		setTimeout(function(){
			if (banner.tipos[banner.i] != 'flash') {
				banner.timer();
			} else {
				banner.playmovie(banner.flashs[banner.i]);
			}
		},2000);
	},
	
	thisMovie: function(movieName){
		if (navigator.appName.indexOf("Microsoft") != -1) {
			return window.document[movieName];
		} else {
			return document[movieName];
		}
	},
	
	playmovie: function(obj){
		if (obj != '' && obj != null) {
			if (document.getElementById(obj).tagName == 'OBJECT') {
				try {
					this.thisMovie(obj).start_animation();
				} catch(e) {
					setTimeout(function(){
						banner.playmovie(obj);
					},1000);
				}
			}
		}
	},
	
	stopmovie: function(obj){
		if (obj != '' && obj != null) {
			if (document.getElementById(obj).tagName == 'OBJECT') {
				try {
					this.thisMovie(obj).stop_animation();
				} catch(e) {
					setTimeout(function(){
						banner.stopmovie(obj);
					},1000);
				}
			}
		}
	},
	
	timer: function(){
		this.interval = setInterval(this.move_left, 4000);
	},
	
	move_banner: function(){
		$('#banner .balls a').removeClass('selected');
		$($('#banner .balls a')[banner.i]).addClass('selected');
		$('#banner .scroller').animate({ 'left': banner.offset + 'px' }, 400, function(){
			clearInterval(banner.interval);
			if (banner.tipos[banner.i] != 'flash') {
				banner.timer();
			} else {
				banner.playmovie(banner.flashs[banner.i]);
			}
		});
	},
	
	move_left: function(){
		clearInterval(this.timeout);
		banner.stopmovie(banner.flashs[banner.i]);
		if (banner.i < banner.size - 1) {
			banner.offset -= 960;
			banner.i++;
		} else {
			banner.offset = 0;
			banner.i = 0;
		}
		banner.move_banner();
		return false;
	},
	
	move_right: function(){
		clearInterval(this.timeout);
		if (banner.i > 0) {
			banner.stopmovie(banner.flashs[banner.i]);
			banner.offset += 960;
			banner.i--;
			banner.move_banner();
		}
		return false;
	},
	
	move_to: function(i){
		clearInterval(this.timeout);
		banner.stopmovie(banner.flashs[banner.i]);
		banner.i = i - 1;
		banner.offset = banner.i * 960 * (-1);
		banner.move_banner();
		return false;
	},
	
	finish: function(){
		this.timeout = setTimeout(function(){
			banner.move_left();
		},2000);
	}

};
// carregar
$(function(){
	$('.bt_produto').click(function(){
		$('#cul').toggle();
		$('#prod').toggle();
		return false;
	});
	$('.bt_cultura').click(function(){
		$('#prod').toggle();
		$('#cul').toggle();
		return false;
	});

	// box do vídeo; editar cultura
	$('.bt-editar, .vid').bind('click',function(){
		var url = $(this).attr('name');
		$('body').append("<div id='mask'></div><div id='janela'></div>");
		
		var documento = { x: $(document).width(), y: $(document).height() };
		var janela = { x: $(window).width(), y: $(window).height() };
		$('#mask').bind('click',function(){
			$('#janela').remove();
			$(this).remove();
		}).css({ width: documento.x, height: documento.y }).show().fadeTo(400,0.8,function(){
			$.post(url,null,function(data){
				$('#janela').html(data);
				$('.fechar').bind('click',function(){
					$('#janela, #mask').remove();
					return false;
				});
				var offset = parseInt($(document).scrollTop());
				$('#janela').css({
					top: parseInt(janela.y/2-$('#janela').height()/2+offset)+'px',
					left: parseInt(documento.x/2-$('#janela').width()/2)+'px'
				}).fadeIn(200);
			});
			
		});
		return false;
	});

	$('.bt-voltar').bind("click",function(){
		history.back();	
		return false;
	});
	$('.imprimir, .bts-imprensa').bind("click",function(){
		window.print();
		return false;
	});
	$('.mostra_prod').click(function(){
		$(this).parent().parent().next().find('div').toggle();
		return false;
	});
	
	submenu.init();
	barra.iniciar();
	banner.start();
});
