(function($) {

	Ideia3 = {

		boot: function() {

			var $html = $("html");

			// Invoca o despachador de interceptadores
			this.interceptors.dispatch.call(this, $html);

			// Invoca o despachador de lógicas de tela
			this.logics.dispatch.call(this, $html);

		},

		interceptors: {

			dispatch: function($html) {

				this.interceptors.common.call(this, $html);
				this.interceptors.ajusts.call(this, $html);

			},

			common: function($html) {
				var $emailFields = $html.find(".email");
				
				$emailFields.each(function() {
					var
						$this = $(this),
						who = $this.attr("who"),
						where = $this.attr("where");

						$this
							.attr("href", ["mailto:", who, "@", where].join(""))
							.text([who, "@", where].join(""));
				});
				var
					$formEmail = $html.find("#emailForm"),
					$emailFormUser = $formEmail.find("#emailFormUser"),
					$emailFormPassword = $formEmail.find("#emailFormPassword"),
					$emailFormAction = $formEmail.find("#emailFormAction"),

					exclusiveHandler = function() {
						$emailFormAction.attr("name", "passo_logar");
						$emailFormUser.attr("name", "f_login");
						$emailFormPassword.attr("name", "f_senha");
					},

					boticarioHandler = function() {
						$formEmail.attr("action", "http://www.axishome.com.br/ideia3/nova_versao/index.cfm");
						exclusiveHandler();
					},

					abradifHandler = function() {
						$formEmail.attr("action", "http://www.axishome.com.br/ideia3/abradif/index.cfm");
						exclusiveHandler();
					},

					outrosHandler = function() {
						$formEmail.attr("action", "http://www.axishome.com.br/ideia3/aol/index.php");
						$emailFormAction.attr("name", "");
						$emailFormUser.attr("name", "frmlogin");
						$emailFormPassword.attr("name", "frmpasswd2");
					};

				$formEmail
					.find("input:radio")
						.each(function(i) {
							switch(i) {
								case 0: $(this).bind("click", boticarioHandler); break;
								case 1: $(this).bind("click", abradifHandler); break;
								case 2: $(this).bind("click", outrosHandler); break;
							}
						});

				$html
					.find("#signupButton")
						.bind("click", function(e) {
							e.preventDefault();
							$formEmail.submit();
						});
			
			},

			ajusts: function($html) {
				if (navigator.appVersion.indexOf("Mac") !== -1) {
					if (navigator.userAgent.indexOf("Safari") !== -1) {
						$("#emailArea #emailLogin .label").css("padding", "3px 0");
					}
				}
			}

		},

		logics: {

			dispatch: function($html) {
				if ($html.hasClass("home")) {
					return this.logics.home.call(this, $html);
				} else if ($html.hasClass("contatos")) {
					return this.logics.contacts.call(this, $html);
				} else if ($html.hasClass("portfolio")) {
					return this.logics.portfolio.call(this, $html);
				} else if ($html.hasClass("portfolio_detalhes")) {
					return this.logics.portfolioDetails.call(this, $html);
				} else if ($html.hasClass("clientes")) {
					return this.logics.customers.call(this, $html);
				} else if ($html.hasClass("noticias")) {
					return this.logics.news.call(this, $html);
				}
			},

			home: function($html) {
				$html
					.find("#introductionText")
						.flash({
							src: "flash/textoHome.swf",
							width: 350,
							height: 200,
							wmode: "transparent",
							flashvars: {
								texto: $.trim($("#introductionTranscription").html())
							}
						},{
							version: 8,
							expressInstall: true
						})
					.end()
					.find("#campaignBackground")
						.flash({
							src: "flash/campanhaBg.swf",
							width: 236,
							height: 290,
							wmode: "transparent",
							flashvars: {
								bg: $("#campaignBackground").attr("class")
							}
						});

				},

			portfolio: function($html) {
				$html
					.find("#gallery")
						.flash({
							src: "flash/galeriaPortfolio.swf",
							width: 980,
							height: 272,
							wmode: "transparent"
						},{
							version: 9,
							expressInstall: true
						})
					.end()
					.find("#portfolioGroupList >.portfolioList > .campaign")
						.hover(function() {
							$(this).addClass("marked");
						}, function() {
							$(this).removeClass("marked");
						});
			},

			portfolioDetails: function($html) {
				var
					$mediaList = $html.find("#mediaList"),
					mediaListWidth = $mediaList.width();

				$mediaList
					.css({
						"left": $html.find("#stage").width() / 2 - mediaListWidth / 2,
						"visibility": "visible"
					})
					.filter(".firstRun")
						.css({
							"bottom": "30px"
						})
						.animate({
							"bottom": 0
						}, 1500, "easeOutSine")

				$html
					.find("#audio")
						.each(function() {
							var
								$this = $(this),
								titulo = $this.attr("title"),
								arquivo = $this.attr("href");

							$this.removeAttr("href");

							$this
								.flash({
									src: "flash/audioplayer.swf",
									width: 420,
									height: 30,
									wmode: "opaque",
									flashvars: {
										titulo: titulo,
										artista: "Ideia 3",
										arquivo: arquivo
									}
								},{
									version: 8,
									expressInstall: true
								})
						})
					.end()
					.find("#video")
						.each(function() {
							$(this)
								.flash({
									src: "flash/videoplayerGrande.swf",
									width: 640,
									height: 390,
									wmode: "opaque",
									flashvars: {
										filme: $(this).attr("href")
									}
								},{
									version: 8,
									expressInstall: true
								})
								.removeAttr("href");
						})

				$(window).bind("load", function() {
					var
						$tableMediaWrap = $html.find("#tableMediaWrap"),
						mediaColumnWidth = $tableMediaWrap.find("#mediaColumn").width(),
						mediaWidth = $("#media").width();
					
					$("#mediaClose")
						.css({
							visibility: "visible",
							top: $tableMediaWrap.position().top - 12,
							left: 44 + mediaWidth + ((mediaColumnWidth - mediaWidth) / 2) - 12
						});

					if ($html.find("#audio").size() > 0) {
						$("#mediaClose").css("left", "700px");
					} else if ($html.find("#video").size() > 0) {
						$("#mediaClose").css("left", "797px");
					}else if ($html.find("#banner").size() > 0) {
						$("#mediaClose").css("left", "712px");
					}
				});
			},

			customers: function($html) {
				var
					oldBalloon,
					$customerTooltip,
					customersListWidth = $html.find("#customersList").width(),
					customersHeight = $html.find("#customersList").height(),
					quadrantes = [
						{horizontal: [0, 450],	    vertical: [0, customersHeight / 2],					offset: [50, 50]},
						{horizontal: [450, 900],	vertical: [0, customersHeight / 2],					offset: [-250, 50]},
						{horizontal: [0, 450],	    vertical: [customersHeight / 2,	customersHeight],   offset: [50, -320]},
						{horizontal: [450, 900],    vertical: [customersHeight / 2,	customersHeight],   offset: [-250, -320]}
					],
					$customerTooltipBg,
					$customerTooltipBackground;

				$([
					'<div id="customerTooltipBg">',
						'<div id="customerInnerWrapper">',
							'<div id="customerTooltipBackground">',
								'<div id="q1" class="imageBackground"></div>',
								'<div id="q2" class="imageBackground"></div>',
								'<div id="q3" class="imageBackground"></div>',
								'<div id="q4" class="imageBackground"></div>',
							'</div>',
						'</div>',
					'</div>',
					'<div id="customerTooltip">',
						'<a id="fecharTooltip" href="#">Fechar</a>',
						'<div id="textoTooltip">',
							'<h3 id="tooltipTitle"></h3>',
							'<a id="tooltipSite"></a>',
							'<span id="tooltipText"></span>',
						'</div>',
					'</div>',
					'customersHeight'
				].join("")).appendTo("#page")
					.find("#fecharTooltip")
						.bind("click", function(e) {
							e.preventDefault();
							oldBalloon = null;
							$(this)
								.parent()
								.stop()
								.hide();
								
							$("#customerTooltipBg")
								.stop()
								.animate({
									opacity: 0,
									top: "-=30px"
								}, "slow", function() {
									$(this).hide();
								});
						});
						
				$customerTooltip = $html.find("#customerTooltip");
				$customerTooltipBg = $html.find("#customerTooltipBg").show();
				$customerTooltipBackground = $customerTooltipBg.find("#customerTooltipBackground");
                
                setTimeout(function(){$customerTooltipBg.hide();},10);

				$(".customer")
					.append('<div class="media"></div>')
					.each(function() {
						var
							$this = $(this),
							file = $this.find(".customerImage > img").attr("src"),
							id = $this.attr("id").split("-")[1];

						$this
							.children(".media")
								.flash({
									src: "flash/clientesMarcas.swf",
									width: 120,
									height: 60,
									wmode: "transparent",
									flashvars: {
										"file": file,
										"id": id
									}
								},{
									version: 8,
									expressInstall: true
								});
					});

				window.openBalloon = function(id) {
					var
						$customerBox,
						customerAbsolutePosition,
						pLeft, pTop, quadrante, i;
						
					if (id !== oldBalloon) {
						oldBalloon = id;
						$customerBox = $html.find("#customer-" + id);
						customerAbsolutePosition = $customerBox.offset();
						customerRelativePosition = $customerBox.position();

						for (i in quadrantes) {
						    if (customerRelativePosition.left >= quadrantes[i].horizontal[0] &&
									customerRelativePosition.left <= quadrantes[i].horizontal[1] &&
									customerRelativePosition.top >= quadrantes[i].vertical[0] && 
									customerRelativePosition.top <= quadrantes[i].vertical[1]) {

								pLeft = customerAbsolutePosition.left + quadrantes[i].offset[0];
								pTop = customerAbsolutePosition.top + quadrantes[i].offset[1];
								quadrante = quadrantes[i];
								break;
							}
						}
						
						$customerTooltipBg
							.stop()
							.animate({
								opacity: 0
							}, 150, function() {
								$customerTooltipBackground.children().hide()
									.filter("#q" + (1 + parseInt(i, 10))).show();

								$customerTooltip
									.find("#tooltipTitle")
										.text($customerBox.find(".title").text())
									.end()
									.find("#tooltipSite")
										.text($customerBox.find(".link").attr("href").replace("http://",""))
										.attr("href", $customerBox.find(".link").attr("href"))
									.end()
									.find("#tooltipText")
										.text($customerBox.find(".text").text())
										.css("font-size", $customerBox.find(".text").attr("size"))
									.end()
									.show()
									.css({
										top: pTop + 30,
										left: pLeft
									})
									.stop()
									.animate({
										top: pTop
									}, 500);

								$(this)
									.show()
									.css({
										top: pTop + 30,
										left: pLeft
									})
									.animate({
										opacity: 1,
										top: pTop
									}, 500);
							});

						$customerTooltip.find("#tooltipSite").css("display", ($.trim($customerBox.find(".link").attr("href")) !== '' ? 'block' : 'none'));
					} else {
						$customerTooltip.children("#fecharTooltip").triggerHandler("click");
					}
				};

			},

			news: function($html) {
				var
					$galeria = $html.find("#noticiasDetalheConteudoMedia > .media"),
					arquivo = $galeria.attr("href"),
					$esquerda = $html.find("#esquerda"),
					$direita = $html.find("#direita"),
					esquerdaHeight,
					direitaHeight;

					$html
						.find("#galeria")
							.flash({
								src: "flash/galeriaNoticia.swf",
								width: 590,
								height: 275,
								wmode: "transparent",
								flashvars: {
									"arquivos": $html.find("#galeria").attr("arquivos")
								}
							},{
								version: 8,
								expressInstall: true
							});

					setInterval(function() {
						esquerdaHeight = $esquerda.height();
						direitaHeight = $direita.height();
						
						if (esquerdaHeight > direitaHeight) {
							$direita.css("min-height", esquerdaHeight);
							$direita.children("#noticiasListMiddle").css("min-height", esquerdaHeight - 100);
						} else {
							$esquerda.css("min-height", direitaHeight);
							$esquerda.children("#noticiasDetalheConteudo").css("min-height", direitaHeight - 25);
						}
					}, 1000);

					$("#videoButton")
						.attr("opened", "0")
						.bind("click", function() {
							if ($(this).attr("opened") == "0") {
								$(this)
									.attr("opened", "1");

								$galeria
									.filter(".video")
										.flash({
											src: "flash/videoplayerPequeno.swf",
											width: 340,
											height: 221,
											wmode: "opaque",
											flashvars: {
												"filme": arquivo
											}
										},{
											version: 8,
											expressInstall: true
										})
										.removeAttr("href");

								$galeria
									.filter(".video")
										.show();

								$galeria
									.filter(".audio")
										.hide()
										.empty();

								$("#audioButton")
									.attr("opened", "0");
							} else {
								$(this)
									.attr("opened", "0");

								$galeria
									.filter(".video")
										.hide()
										.empty();
							}
						});

					$("#audioButton")
						.attr("opened", "0")
						.bind("click", function() {
							if ($(this).attr("opened") == "0") {
								$(this)
									.attr("opened", "1");

									$galeria
										.filter(".audio")
											.flash({
												src: "flash/audioplayer.swf",
												width: 420,
												height: 30,
												wmode: "opaque",
												flashvars: {
													flashvars: {
														titulo: "Faixa",
														artista: "Ideia 3",
														arquivo: arquivo
													}
												}
											},{
												version: 8,
												expressInstall: true
											})
											.removeAttr("href");

								$galeria
									.filter(".audio")
										.show();

								$galeria
									.filter(".video")
										.hide()
										.empty();

								$("#videoButton")
									.attr("opened", "0");
							} else {
								$(this)
									.attr("opened", "0");

								$galeria
									.filter(".audio")
										.hide()
										.empty();
							}
					});
			},

			contacts: function($html) {
				var
					$form = $html.find("#contactForm"),
					messages = [];

				$("#contactTooltip")
					.filter(function() {
						return $.trim($(this).children("#textoTooltip").html()) !== "";
					})
					.show();

				$("#contactTooltip #fecharTooltip").bind("click", function(e) {
					e.preventDefault();
					$(this).parent().hide();
				});

				$(window)
					.bind("load", StartMap)
					.bind("unload", GUnload);

				$html
					.find("#resetContact")
						.bind("click", function(event) {
							event.preventDefault();
							$form.get(0).reset();
						})
					.end()
					.find("#submitContact")
						.bind("click", function(event) {
							event.preventDefault();
							$html.find("#contactForm").submit();
						});

				$(document).trule({
					messages: window.messages,
					firstErro: function(r) {
						r.oRef.focus();
					},
					error: function(r, msg) {

						/*
						 * Se esta mensagem é de campo obrigatório, verificamos
						 * se já existe uma mensagem desse mesmo tipo no vetor
						 * de erros. Caso isso se confirme, não precisamos
						 * inserir mais nenhuma mensagem e a execução para.
						 */
						if (msg.indexOf("campo obrigatório") > -1) {
							for (message in messages) {
								if (message.indexOf("campo obrigatório") > -1) {
									return;
								}
							}

							// Se chegou até aqui é porquê não achou nenhuma
							msg = "Preencha todos campos obrigatórios";
						}

						messages.push(msg);
					},
					lastErro: function() {
						/*
						 * Mostrarei só a primeira mensagem pois o balão de
						 * mensagens é muito pequeno
						 */
						$("#textoTooltip")
							.html(messages[0])
							.parent()
								.show();
						messages = [];
					}
				});

				$html
					.find("#contactForm")
						.bind("submit", function(event) {
							if (!$(this).trule().validateAll()) {
								event.preventDefault();
							}
						});


			}

		}

	};

	$(document).bind("ready", function() {
		Ideia3.boot.call(Ideia3);
	});

})(jQuery);