(function($) {

	$(document).bind("ready", function() {

		var
			logics = Caramelo.logics,
			interceptors = Caramelo.interceptors,
			$page = $("#page"); // Contexto do site
		
		// Faz as chamadas dos interceptors
		Caramelo.interceptors.Common.call($page);

		if ($page.hasClass("form")) { interceptors.Forms.call($page); }
		if ($page.hasClass("frames")) { interceptors.Frames.call($page); }
		if ($page.hasClass("slideable")) { interceptors.Slideable.call($page); }

		// Faz a chamada dos logics
		if ($page.hasClass("home")) { return logics.Home.call($page); }
		if ($page.hasClass("portfolio")) {
			logics.Portfolio.call($page);
			
			if ($page.hasClass("customers")) {
				logics.Customers.call($page);
			}
			
			return null;
		}
		if ($page.hasClass("services")) { return logics.Services.call($page); }
		if ($page.hasClass("partners")) { return logics.Partners.call($page); }
		if ($page.hasClass("register")) { return logics.Register.call($page); }      
        
	});
    

})(jQuery);

Caramelo = {
	interceptors : {
		Common: function() {
			$("#main-menu > li:has(a:first-child.haveChildren)")
				.each(function() {
					var
						$this = $(this),
						$children = $this.children(".children"),
						childrenHeight = $children.show().height();

					$children.css("height", 0);

					$this
						.bind("mouseover", function() {
							$children
								.stop()
								.animate({height: childrenHeight},{
									queue: false,
									duration: 600
								});
						})
						.bind("mouseout", function() {
							$children
								.stop()
								.animate({height: 0},{
									queue: false,
									duration: 600
								});
						});
				});


			$("#orange-menu #orange-menu-itens")
				.each(function() {
					var
						listHeight = $(this).height(),
						areaHeight = $("#orange-menu-padding").height(),
						listHeightDisc = (listHeight - areaHeight),
						$menuItens = $("#orange-menu-itens"),
						$scrollTrack = $("#scroll-track"),
						trackTopOffset,
						dragging;

					if (listHeight > areaHeight) {
						$scrollTrack
							.css("display", "inline")
							.children("#scroller")
								.draggable({
									axis: "y",
									containment: $("#scroll-track"),
									start: function() {
										dragging = true;
									},
									drag: function(event, ui) {
										event.stopPropagation();
										var
											percScroll = Math.floor(ui.position.top * 100 / (areaHeight - 30))
											newTop = Math.floor(listHeightDisc * percScroll / 100) * -1;
										$menuItens.css({top: newTop});
									},
									stop: function() {
										setTimeout(function() {
											dragging = false;
										}, 10);
									}
								})
							.end()
								.bind("click", function(event) {
									if (!dragging) {
										if (trackTopOffset === undefined) {
											trackTopOffset = $scrollTrack.offset()["top"];
										}

										var
											clickTop = (event.clientY - trackTopOffset > areaHeight - 30 ? areaHeight - 30 : event.clientY - trackTopOffset);
											percScroll = Math.floor(clickTop * 100 / (areaHeight - 30))
											newTop = Math.floor(listHeightDisc * percScroll / 100) * -1;

											$scrollTrack
												.children("#scroller")
													.css("top", clickTop);

										$menuItens.css({top: newTop});
									}
								});
					}
				});

			window.systemMessages = function() {
				$("#systemMessages > .inner > .list").each(function() {
					var
						$this = $(this),
						$list = $this.children("ul"),
						height = $list.height();

						$this.animate({
							"top": 350 - height / 2,
							"height": height
						}, 1000);

						$this.bind("click", function() {
							$("#systemMessages").fadeOut("slow");
						});
				});
			};
			window.systemMessages();
		},

		Forms: function() {
			var
				$page = this;
				$controls = $page.find("input, select, textarea, button"),
				$inputs = $controls.filter("input"),
				$selects = $controls.filter("select"),
				$textareas = $controls.filter("textarea"),
				$buttons = $controls.filter("button"),
				$toValidate = $controls.filter(".validate"),
				$innerLabeled = $controls.filter(".innerlabel"),
				systemMessagesTemplate = [
					'<div id="systemMessages">',
						'<div class="inner">',
							'<div class="overlay"></div>',
							'<div class="list"><span style="width:100%"><img src="data/site/page/images/xis.jpg" style="float:right"/></span>',
								'<ul></ul>',
							'</div>',
						'</div>',
					'</div>'];

				// Aplica contador nos textarea marcados
				$textareas.filter("[counter]").each(function() {
					var
						$this = $(this),
						maxlength = $this.attr("t:maxlength"),
						$counter = $this.siblings($this.attr("counter")).children(".counter");

					$this
						.bind("keydown", function(e) {
							var length = $this.val().length;
							if (length >= maxlength) {
								switch(e.keyCode) {
									case 8:
									case 46:
										break;
									default:
										return (!!e.preventDefault());
								}
							}
						})
						.bind("keyup", function() {
							$counter.text(maxlength - $this.val().length);
						})
						.bind("blur", function() {
							$this.val($this.val().slice(0,maxlength));
							$counter.text(maxlength - $this.val().length);
						})
						.trigger("blur");
				});

			// Aplica label interno
			$innerLabeled.each(function() {
				var
					$this = $(this),
					label = $this.attr("label");

				if ($.trim($this.val()) == "") {
					$this.val(label);
					$this.labeled = true;
				}

				$this
					.bind("focus", function() {
						if ($this.labeled === true) {
							$this.val("");
						}
					})
					.bind("blur", function() {
						if ($.trim($this.val()) == "") {
							$this.val(label);
							$this.labeled = true;
						} else {
							$this.labeled = false;
						}
					})
					.bind("submit", function() {
						if ($this.labeled == true) {
							$this.val("");
							setTimout(function() {
								$this.val(label);
							}, 100);
						}
					});
			});

			$inputs
				.filter(function() {
					return this.className.match(/labeled-/) !== null;
				})
				.each(function() {
					var
						$this = $(this),
						label = $this.attr("label"),
						_r = $.fn.trule.validators.rules,
						rule = _r[this.className.match(/labeled-([^\s]*)/)[1]];

						$this
							.bind("focus", function() {
								if ($this.labeled === true) {
									$this.val("");
								}
							})
							.bind("submit", function() {
								if ($this.labeled == true) {
									$this.val("");
									setTimout(function() {
										$this.val(label);
									}, 100);
								}
							})
							.trule().addRule(rule)
							.bind("blur", function() {
								if ($.trim($this.val()) == "") {
									$this.val(label);
									$this.labeled = true;
								} else {
									$this.labeled = false;
								}
							});

						if ($.trim($this.val()) == "") {
							$this.val(label);
							$this.labeled = true;
						}
				});

			(function() {
				var
					$systemMessages = $("#systemMessages"),
					messages = [];

				// Define configurações globais
				$(document).trule({
					messages: window.messages,
					firstErro: function() {
						
						if ($systemMessages.size() == 0) {
							$systemMessages = $(systemMessagesTemplate.join(""));
							$("#main").prepend($systemMessages);
							
						} else {
							$systemMessages.find(".list > ul").empty();
						}
					},
					error: function(r, msg) {
						messages.push('<li class="error">'+msg+'</li>');
					},
					lastErro: function() {
						
						$systemMessages.show().children(".inner").children(".list").height(0).css("top","350px").children("ul").append(messages.join(""));
						messages = [];
						window.systemMessages();
					}
				});
			})();
		
			
			//Exibe e esconde o formulario de grupos
			if($('#form_newsletter').attr('checked')){
					$('.imgEnviar').show();
					$('.hideEnviar').hide();
			}else{
					$('.imgEnviar').hide();
					$('.hideEnviar').show();
			}
			$('#form_newsletter').click(function(){
				if($('#form_newsletter').attr('checked')){
					$('.imgEnviar').show();
					$('.hideEnviar').hide();
				}else{
					$('.imgEnviar').hide();
					$('.hideEnviar').show();
				}
			});
			$('#groupLinkVoltar').click(function(){
				$('#mascara').hide();
			});

			$('.imgEnviar').click(function(){
				if($('#form_newsletter').attr('checked')){
					$('#mascara').fadeIn(1000);
					
				}
				
			});
			
			$("form").bind("submit", function(event) {
				$('#mascara').hide();
				$textables = $(this)
					.find("input, textarea")
						.filter(function() {
							return this.className.match(/labeled|innerlabel/) != null;
						})
							.each(function() {
								if ($(this).val() == $(this).attr("label")) {
									$(this).val("");
								}
							});

				if (!$(this).trule().validateAll()) {
					event.preventDefault();
				}

				$textables.each(function() {
					if ($(this).val() == "") {
						$(this).val($(this).attr("label"));
					}
				});
			});

		},

		Frames: function() {
			var
				totalWidth      = 0,

				$orangeMenu     = this.find("#orange-menu"),
				$center         = this.find("#center"),
				$frames         = this.find("#frames"),
				$previousButton = this.find("#backward"),
				$nextButton     = this.find("#forward"),
				$allAnchors     = $frames.find("a[name]"),

				oldHash         = "",
				applyHash = function() {
					if (location.hash != oldHash) {
						var hash = location.hash.slice(3, location.hash.length);
						$allAnchors.each(function() {
							var $this = $(this);
							if ($this.attr("name") == hash) {
								$this.trigger("click");
								return true;
							}
						});
						oldHash = location.hash;
					}
				},
				setWidth = function() {
					$frames
						.children("div")
							.each(function() {
								totalWidth += $(this).outerWidth(true);
							})
						.end()
							.width(totalWidth);

					totalWidth = 0;
				};               

			// Tem que calcular duas vezes =/
			setWidth();
			setWidth();

			$allAnchors
				.bind("click", function() {

					var name = $(this).attr("name");

					location.hash = "#m-" + name;

					if (window["entries"] !== undefined) {
						Portfolio.chooseRegion(name);
					}

					$frames
						.stop()
						.animate({
							"left": $(this).parent().parent().position()["left"] * -1
						},{
							queue: false,
							duration: 1000,
							easing: "swing",
							complete: function() {
								if ($frames.position()["left"] >= 0) {
									$previousButton.addClass("disabled");
									
									if ($frames.width() - $center.width() > 0) {
										$nextButton.removeClass("disabled");
									} else {
										$nextButton.addClass("disabled");
									}
								} else {
									if ($frames.position()["left"] * -1 > $frames.width() - $center.width()) {
										$nextButton.addClass("disabled");
										$previousButton.removeClass("disabled");
									} else {
										$nextButton.removeClass("disabled");
										$previousButton.removeClass("disabled");
									}
								}
							}
						});
				});

			if (window["entries"] === undefined && this.hasClass("customers") === false) {
				$center
					.SlideScroll({
						buttons: {
							previous: "#backward",
							next: "#forward"
						},
						dataSource: "stageLength",
						container: $frames
					});
			}

			setInterval(applyHash, 100);
		},

		Slideable: function() {
			if (window["entries"] !== undefined) {
				var
					$center = this.find("#center")
						.SlideScroll({
							buttons: {
								previous: "#backward",
								next: "#forward"
							},
							transition: "slide",
							dataSource: entries
						}),
					$frames         = this.find("#frames"),
					$previousButton = this.find("#backward"),
					$nextButton     = this.find("#forward"),
					$allAnchors     = this.find("#orange-menu-itens.activeSlider > li > a"),

					oldHash         = "",
					applyHash = function() {						
						if (location.hash != oldHash) {
							var hash = location.hash.slice(3, location.hash.length);
							$allAnchors.each(function() {
								var
									$this = $(this),
									id = $this.attr("id").split("-")[2];

								if (id == hash) {
									$this.trigger("click");
									return true;
								}
							});
							oldHash = location.hash;
						}
					};

				$allAnchors
					.bind("click", function(e) {
						e.preventDefault();
						var
							$this = $(this),
							id = $this.attr("id").split("-")[2];

						location.hash = "#m-" + id;

						$center.SlideScroll("goTo", id);
					});

				setInterval(applyHash, 100);
			}
		}
	},

	logics: {
		Home: function() {
			if (window["entries"] !== undefined) {
				var
					timer,
					current = 0,
					$forward,
					$center = this
						.find("#center")
							.SlideScroll({
								buttons: {},
								transition: "fade",
								dataSource: entries,
								container: "#background-banner",
								onShow: function() {
									clearInterval(timer);
									timer = setTimeout(function() {
										$forward.trigger("click");
									}, 7500);
								}
							}),
					entrieslength = entries.length - 1,
					lock = 0;

				$("#backward")
					.removeClass("disabled")
					.bind("click", function() {
						if (lock === 0) {
							if (current > 0) {
								$center
									.SlideScroll("goTo", entries[--current].id);
							} else {
								current = entrieslength + 1;
								$center
									.SlideScroll("goTo", entries[--current].id);
							}
							lock = 1;
							setTimeout(function() {
								lock = 0;
							}, 1000);
						}
					});

				$forward = $("#forward")
					.removeClass("disabled")
					.bind("click", function() {
						if (lock === 0) {
							if (current < entrieslength) {
								$center
									.SlideScroll("goTo", entries[++current].id);
							} else {
								current = -1;
								$center
									.SlideScroll("goTo", entries[++current].id);
							}
							lock = 1;
							setTimeout(function() {
								lock = 0;
							}, 1000);
						}
					});
			}
		},

		Portfolio: function() {

			var
				lang = "br",
				$orangeMenu = this.find("#orange-menu");

			if ($orangeMenu.hasClass("sp")) {
				lang = "sp";
			} else if ($orangeMenu.hasClass("en")) {
				lang = "en";
			}

			this.find("#west-mini-map")
				.flash({
					src: "data/site/page/swf/region.swf",
					width: 208,
					height: 212,
					flashvars: { "lang": lang }
				},{
					version: "6.0.65",
					expressInstall: true
				});

			this.find("#regionChooser")
				.flash({
					src: "data/site/page/swf/region.swf",
					width: 430,
					height: 437,
					flashvars: { "lang": lang },
					wmode: "opaque"
				},{
					version: "6.0.65",
					expressInstall: true
				});

			window.Portfolio = {
				chooseRegion: function(regiao) {
					var href = location.href.replace(/#.+/,"");
					href = href.replace("&list=1","").concat("&list=1");
					switch (regiao) {
						case "norte":
						case "north":
							location.href = href.concat("#m-north");
						break;

						case "nordeste":
						case "northeast":
							location.href = href.concat("#m-northeast");
						break;

						case "centro":
						case "center":
							location.href = href.concat("#m-center");
						break;

						case "sudeste":
						case "southeast":
							location.href = href.concat("#m-southeast");
						break;

						case "sul":
						case "south":
							location.href = href.concat("#m-south");
						break;
					}

				}
			};

		},

		Customers: function() {  
            
            var $frames         = this.find("#frames"),
            $center         = this.find("#center");
            if (window["entries"] === undefined) {
				$center
					.SlideScroll({
						buttons: {
							previous: "#backward",
							next: "#forward"
						},
						dataSource: "customers",
						container: $frames
					});
			}
            
			$("#frames .customerProjects")
				.each(function() {
					var
						$this = $(this),
						$toLeft = $this.children(".toLeft"),
						$toRight = $this.children(".toRight");

						$this
							.children(".gallery")
								.children(".galleryFrames")
									.each(function() {
										var
											$this = $(this),
											$images = $this.children(".image"),
											containerWidth = $this.parent().width(),
											totalWidth = $images.size() * 79,
											move = function(signal) {
												$this
													.animate({
														"left": signal + "=79px"
													}, {
														queue: false,
														duration: 500,
														complete: checkControls
													});
											},
											checkControls = function() {
												$toLeft.removeClass("disabled");
												$toRight.removeClass("disabled");
												if (totalWidth < containerWidth) {
													$toLeft.addClass("disabled");
													$toRight.addClass("disabled");
												} else {
													if ((totalWidth - 79) + $this.position()['left'] <= containerWidth) {
														$toLeft.addClass("disabled");
													} else if ($this.position()['left'] >= 0) {
														$toRight.addClass("disabled");
													}
												}
											};

											checkControls();

											$this.width(totalWidth);
											
											$toLeft
												.bind("click", function(e) {
													e.preventDefault();
													if ((totalWidth - 79) + $this.position()['left'] > containerWidth) {
														move("-");
													}
												});

											$toRight
												.bind("click", function(e) {
													e.preventDefault();
													if ($this.position()['left'] < 0) {
														move("+");
													}
												});
									});
				});
                
		},

		Services: function() {
			var $previousService, lock = false;

			this.find(".servicesList a").bind("click", function(e) {
				if ($(e.target).is("label") && lock === false) {
					var $this = $(this).children(".description");
					if ($previousService !== undefined) {
						lock = true;
						$previousService.fadeOut("fast", function() {
							$this.fadeIn("slow");
							lock = false;
							$previousService = $this;
						});
					} else {
						$this.fadeIn("slow");
						$previousService = $this;
					}
				}
			});
		},

		Partners: function() {
			var
				current,
				$display = $(".display"),
				currentHash;

			this
				.find("a.company")
					.bind("click", function(e, data) {
						var $card = $(this).addClass("selected").next().clone();
						$display.empty().append($card);
						if (current !== undefined && current !== this) {
							$(current).removeClass("selected");
						}
						current = this;
					})
					.each(function(i) {
						$(this).attr({
							"href": "#partner" + i,
							"id": "partner" + i
						});
					});

			setInterval(function() {
				if (location.hash !== currentHash) {
					currentHash = location.hash;
					$(currentHash).trigger("click", {usingHash: true});
				}
			}, 100);
		},

		Register: function() {
			var $this = this;
			
			$this
				.find("#form_trabalho")
					.bind("click", function() {
						if (this.checked) {
							$this.find("#info").stop().slideDown();
						} else {
							$this.find("#info").stop().slideUp();
						}
					})
					.filter(":checked")
						.triggerHandler("click");
		}

	}
}


function closeFriend()
{
    $('#goFriend').hide();
}
function sendToFriend (){ 

    var url = $('#iframeFriend').attr('url');
    $('#iframeFriend').attr('src',url);
    $('#goFriend').show();
};

function showConfMensagem(){
	$('#confMensagem').show();
}