//Hide site
function hide_site() {
	$('#header, #footer').delay(1500).fadeTo(500, 0);

	setTimeout(function () {
		start = true;
		$('#button').fadeTo(500, 0, function () {
			$(this).html('PAUSE');
		});
	}, 2500);
}

function show_site() {
	$('#header, #footer').fadeTo(500, 1);
}



//Sob medida
function institucional() {
	$('#content .previous').removeClass('deactive').trigger('click');
}



//Faux select
$('select').each(function () {
	$(this).fadeTo(0,0);

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

	$(this).before('<span class="arrow"><span class="ir back">&nbsp;</span><span class="ir front">&nbsp;</span></span>');

	$(this).find('option:eq(0)').attr({ disabled: 'disabled' });
});

$('select').change(function() {
	var select = $(this);

	select.find(':selected').each(function () {
//	alert($(this).prop('disabled'));
//	alert($(this).attr('disabled'));

		tes = $(this).attr('disabled');
		if( tes != 'disabled') {
			catched = $(this).text();
			select.parent().siblings('strong').text(catched);
		}
	});
}).change();



//Detect Form
$('.page-template-contato-php .wpcf7').each(function () {

	$('.wpcf7-submit').bind('mouseup', function () {
		setTimeout(function () {
			$('.wpcf7-not-valid-tip').each(function () {
				$(this).parent().parent().parent().addClass('error');
			});

			$('.wpcf7-validates-as-required.error:eq(0)').focus();
		}, 500);

		setTimeout(function () {
			$('.wpcf7-not-valid-tip').each(function () {
				$(this).parent().parent().parent().addClass('error');
			});

			$('.wpcf7-validates-as-required.error:eq(0)').focus();
		}, 1500);
	});

	$('.error .wpcf7-validates-as-required').live('blur', function () {
		if($(this).val() != '') {
			$(this).parent().parent().parent().removeClass('error');
		}
	});
});



//Share FB
$('a.fb').live('click', function () {
	window.open($(this).attr('href'),'sharer','toolbar=0,status=0,width=626,height=436');

	return false;
});



//Twitter
$('a.tw').live('click', function () {
	window.open($(this).attr('href'),'twitter','toolbar=0,status=0,width=550,height=350');

	return false;
});



//Product thumb auto click
function thumb(id, pos) {
	$('#' + id + ' .pics a:eq(' + pos + ')').trigger('click');
}



//Collection
$('.page-template-onde-encontrar-php').each(function () {

	var initialLocation;
	var brazil = new google.maps.LatLng(0,0);
//	var brazil = new google.maps.LatLng(-18, -50);
	var browserSupportFlag = new Boolean();
	var info = [];
	var map;


	function InfoBox(opts) {
		google.maps.OverlayView.call(this);
		this.latlng_ = opts.latlng;
		this.map_ = opts.map;
		this.content_ = opts.content || "Hello World";
		this.offsetVertical_ = opts.offsetVertical || -165;
		this.offsetHorizontal_ = opts.offsetHorizontal || -150;
		this.height_ = opts.height || 120;
		this.width_ = opts.width || 300;

		var me = this;
		this.boundsChangedListener_ = google.maps.event.addListener(this.map_, "bounds_changed", function() {
			return me.panMap.apply(me);
		});

		this.setMap(this.map_);
	}

	InfoBox.prototype = new google.maps.OverlayView();

	InfoBox.prototype.remove = function() {
		if (this.div_) {
			this.div_.parentNode.removeChild(this.div_);
			this.div_ = null;
		}
	};

	InfoBox.prototype.draw = function() {
		this.createElement();
		if (!this.div_) return;

		var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
		if (!pixPosition) return;

		this.div_.style.width = this.width_ + "px";
		this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px";
		this.div_.style.height = this.height_ + "px";
		this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px";
		this.div_.style.display = 'block';
	};

	InfoBox.prototype.createElement = function() {
		var panes = this.getPanes();
		var div = this.div_;
		if (!div) {
			// This does not handle changing panes. You can set the map to be null and then reset the map to move the div.
			div = this.div_ = document.createElement("div");
			div.style.border = "0px none";
			div.style.position = "absolute";
			div.style.background = "url(http://alexandrebirman.com.br/wp-content/themes/birman2012/assets/images/background-opacity.png)";
			div.style.overflow = "hidden";
			div.style.borderRadius = "3px";
			div.style.opacity = ".95";
			div.style.borderShadow = "0 0 5px rgba(0, 0, 0, .5)";
			div.style.width = this.width_ + "px";
			div.style.height = this.height_ + "px";
			var contentDiv = document.createElement("div");
			contentDiv.style.padding = "10px"
			contentDiv.style.overflow = "hidden"
			contentDiv.innerHTML = this.content_;

			var topDiv = document.createElement("div");
			topDiv.style.position = "absolute";
			topDiv.style.right = "10px";
			topDiv.style.top = "10px";
			topDiv.style.width = "14px";
			topDiv.style.height = "14px";
			topDiv.style.textAlign = "center";
			topDiv.style.lineHeight = "12px";
			topDiv.style.background = "#000";
			topDiv.style.borderRadius = "3px";
			topDiv.style.border = "1px solid #666";
			var closeImg = document.createElement("img");
			closeImg.style.width = "8px";
			closeImg.style.height = "8px";
			closeImg.style.cursor = "pointer";
			closeImg.src = "http://alexandrebirman.com.br/wp-content/themes/birman2012/assets/images/icon-close-white.png";
			topDiv.appendChild(closeImg);

			function removeInfoBox(ib) {
				return function() {
					ib.setMap(null);
				};
			}

			google.maps.event.addDomListener(closeImg, 'click', removeInfoBox(this));

			div.appendChild(topDiv);
			div.appendChild(contentDiv);
			div.style.display = 'none';
			panes.floatPane.appendChild(div);
			this.panMap();

		} else if (div.parentNode != panes.floatPane) {

		// The panes have changed.  Move the div.
		div.parentNode.removeChild(div);
		panes.floatPane.appendChild(div);

		} else {
		// The panes have not changed, so no need to create or move the div.
		}
	}

	InfoBox.prototype.panMap = function() {
	// if we go beyond map, pan map
	var map = this.map_;
	var bounds = map.getBounds();
	if (!bounds) return;

	// The position of the infowindow
	var position = this.latlng_;

	// The dimension of the infowindow
	var iwWidth = this.width_;
	var iwHeight = this.height_;

	// The offset position of the infowindow
	var iwOffsetX = this.offsetHorizontal_;
	var iwOffsetY = this.offsetVertical_;

	// Padding on the infowindow
	var padX = 40;
	var padY = 40;

	// The degrees per pixel
	var mapDiv = map.getDiv();
	var mapWidth = mapDiv.offsetWidth;
	var mapHeight = mapDiv.offsetHeight;
	var boundsSpan = bounds.toSpan();
	var longSpan = boundsSpan.lng();
	var latSpan = boundsSpan.lat();
	var degPixelX = longSpan / mapWidth;
	var degPixelY = latSpan / mapHeight;

	// The bounds of the map
	var mapWestLng = bounds.getSouthWest().lng();
	var mapEastLng = bounds.getNorthEast().lng();
	var mapNorthLat = bounds.getNorthEast().lat();
	var mapSouthLat = bounds.getSouthWest().lat();

	// The bounds of the infowindow
	var iwWestLng = position.lng() + (iwOffsetX - padX) * degPixelX;
	var iwEastLng = position.lng() + (iwOffsetX + iwWidth + padX) * degPixelX;
	var iwNorthLat = position.lat() - (iwOffsetY - padY) * degPixelY;
	var iwSouthLat = position.lat() - (iwOffsetY + iwHeight + padY) * degPixelY;

	// calculate center shift
	var shiftLng =
	(iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) +
	(iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
	var shiftLat =
	(iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) +
	(iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);

	// The center of the map
	var center = map.getCenter();

	// The new map center
	var centerX = center.lng() - shiftLng;
	var centerY = center.lat() - shiftLat;

	// center the map to the new shifted center
	map.setCenter(new google.maps.LatLng(centerY, centerX));

	// Remove the listener after panning is complete.
	google.maps.event.removeListener(this.boundsChangedListener_);
	this.boundsChangedListener_ = null;
	};

	function initialize() {
		var myOptions = {
			zoom: 3,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		}

		map = new google.maps.Map(document.getElementById('content'), myOptions);
		map.setCenter(brazil);

		// User Geolocation
		if ( navigator.geolocation ) {
			navigator.geolocation.getCurrentPosition(handlePosition, handleError, { timeout: 10000 });
		}

		//Ajax
		$.ajax({
			url: 'http://alexandrebirman.com.br/?lojas=alexandre-birman',
			dataType: 'json',
			success: function(data) {

				for (var i = 0; i < data.length; i++) {

					var image = new google.maps.MarkerImage('http://alexandrebirman.com.br/wp-content/themes/birman2012/assets/images/pin_' + data[i].popup + '.png',
						new google.maps.Size(34, 40),
						new google.maps.Point(0,0),
						new google.maps.Point(16, 40));

					info[i] = {
						nome:			data[i].nome,
						endereco:		data[i].endereco,
						cidade:			data[i].cidade,
						uf:				data[i].uf,
						telefone:		data[i].telefone,
						site:			data[i].site,
						lat:			data[i].lat,
						long:			data[i].long,
						imagem:			data[i].imagem
					};

					var latLong = new google.maps.LatLng(data[i].lat, data[i].long);

					var marker = new google.maps.Marker({
						position: latLong,
						map: map,
						icon: image,
						title: data[i].nome,
						animation: google.maps.Animation.DROP,
						zIndex: (data[i].popup == 'true') ? data[i].id * 100 : data[i].id
					});

					attach_message(marker, i);
				}
			}

/*
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(-34, 150),
        map: map
    });

    google.maps.event.addListener(marker, "click", function(e) {
		var infoBox = new InfoBox({
			latlng: marker.getPosition(),
			map: map,
			content: '1'
		});
    });
    google.maps.event.trigger(marker, "click");
*/
		});
	}

	function handleError(error) {

		switch (error.code) {
			case error.PERMISSION_DENIED:
				// User denied access to location. Perhaps redirect to alternate content?
				console.log('Permission was denied');
				break;
			case error.POSITION_UNAVAILABLE:
				console.log('Position is currently unavailable.');
				break;
			case error.PERMISSION_DENIED_TIMEOUT:
				console.log('User took to long to grant/deny permission.');
				break;
			case error.UNKNOWN_ERROR:
				console.log('An unknown error occurred.')
				break;
		}
	}

	function handlePosition() {
		var userLocationMarker,
			userLocationCircle;

		browserSupportFlag = true;

		navigator.geolocation.getCurrentPosition(function(position){

			initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
			map.setZoom(12);
			map.setCenter(initialLocation);

			var user_icon = new google.maps.MarkerImage('http://alexandrebirman.com.br/wp-content/themes/birman2012/assets/images/pin_user.png',
				new google.maps.Size(10, 10),
				new google.maps.Point(0, 0),
				new google.maps.Point(5, 5)
			);

			var userLocationMarker = new google.maps.Marker({
				icon: user_icon
			});

			userLocationMarker.setPosition(initialLocation);
			userLocationMarker.setMap(map);

			var circle = new google.maps.Circle({
				fillColor: '#000000',
				fillOpacity: 0.05,
				strokeColor: '#000000',
				strokeOpacity: 0.3,
				strokeWeight: 1
			});

			circle.bindTo('center', userLocationMarker, 'position');
			circle.setRadius(position.coords.accuracy);
			circle.setMap(map);
		});
	}

	function attach_message(marker, i) {

		google.maps.event.addListener(marker, "click", function(e) {

			var infoBox = new InfoBox({
				latlng: marker.getPosition(),
				map: map,
				content: '<p style="font-size: 13px; color: #FCFCFC; text-align: left; width: 170px; float: left;"><strong style="font-family: Yanone Kaffeesatz, sans-serif; font-weight: normal; font-size: 20px; padding-bottom: 5px; display: block;">' + info[i].nome + '</strong>' + info[i].endereco + '<br />' + info[i].cidade + ( (info[i].uf) ? ' / ' + info[i].uf : '' ) + '<br />' + ( (info[i].telefone) ? info[i].telefone + '<br />' : '' ) + ( (info[i].site) ? '<a href="' + info[i].site + '" target="_blank">' + info[i].site + '</a>' : '' ) + '</p>' + ( (info[i].imagem) ? '<img style="float: right; margin: -5px -5px 0 0;" src="' + info[i].imagem + '" />' : '' )
			});
		});
	}

	initialize();





	//GMaps
/*
	var initialLocation;
	var brazil = new google.maps.LatLng(-18, -50);
	var browserSupportFlag = new Boolean();
	var info = [];
	var map;

	var grayscale = [{
		featureType: "all",
		elementType: "geometry",
		stylers: [
			{ lightness: 86 },
			{ gamma: 0.42 },
			{ saturation: -100 },
			{ visibility: "simplified" }
		]},{
			featureType: "road",
			elementType: "geometry",
			stylers: [
				{ gamma: 0.31 },
				{ lightness: 12 },
				{ visibility: "on" }
		]},{
			featureType: "road",
			elementType: "labels",
			stylers: [
				{ saturation: -97 },
				{ gamma: 9.5 },
				{ lightness: -2 },
				{ visibility: "on" }
		]},{
			featureType: "landscape",
			elementType: "geometry",
			stylers: [
				{ lightness: 58 }
		]},{
			featureType: "water",
			elementType: "all",
			stylers: [
				{ lightness: -10 }
		]},{
			featureType: "administrative.land_parcel",
			elementType: "all",
			stylers: [
				{ visibility: "simplified" },
				{ gamma: 0.32 },
				{ lightness: 89 }
		]}];

	function initialize() {
		var myOptions = {
			zoom: 5,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		//	styles: grayscale
		}

		map = new google.maps.Map(document.getElementById('content'), myOptions);
		map.setCenter(brazil);

		// User Geolocation
		if ( navigator.geolocation ) {
			navigator.geolocation.getCurrentPosition(handlePosition, handleError, { timeout: 10000 });
		}

		//Ajax
		$.ajax({
			url: 'http://birman/?lojas=alexandre-birman',
			dataType: 'json',
			success: function(data) {

				for (var i = 0; i < data.length; i++) {

					var image = new google.maps.MarkerImage('http://alexandrebirman.com.br/wp-content/themes/birman2012/assets/images/pin_' + data[i].popup + '.png',
						new google.maps.Size(34, 40),
						new google.maps.Point(0,0),
						new google.maps.Point(16, 40));

					info[i] = {
						nome:			data[i].nome,
						endereco:		data[i].endereco,
						cidade:			data[i].cidade,
						uf:				data[i].uf,
						telefone:		data[i].telefone,
						site:			data[i].site,
						lat:			data[i].lat,
						long:			data[i].long
					};

					var latLong = new google.maps.LatLng(data[i].lat, data[i].long);

					var marker = new google.maps.Marker({
						position: latLong,
						map: map,
						icon: image,
						title: data[i].nome,
						animation: google.maps.Animation.DROP,
						zIndex: (data[i].popup == 'true') ? data[i].id * 100 : data[i].id
					});

					attach_message(marker, i);
				}
			}
		});
	}

	function handleError(error) {

		switch (error.code) {
			case error.PERMISSION_DENIED:
				// User denied access to location. Perhaps redirect to alternate content?
				console.log('Permission was denied');
				break;
			case error.POSITION_UNAVAILABLE:
				console.log('Position is currently unavailable.');
				break;
			case error.PERMISSION_DENIED_TIMEOUT:
				console.log('User took to long to grant/deny permission.');
				break;
			case error.UNKNOWN_ERROR:
				console.log('An unknown error occurred.')
				break;
		}
	}

	function handlePosition() {
		var userLocationMarker,
			userLocationCircle;

		browserSupportFlag = true;

		navigator.geolocation.getCurrentPosition(function(position){

			initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
			map.setZoom(12);
			map.setCenter(initialLocation);

			var user_icon = new google.maps.MarkerImage('http://alexandrebirman.com.br/wp-content/themes/birman2012/assets/images/pin_user.png',
				new google.maps.Size(10, 10),
				new google.maps.Point(0, 0),
				new google.maps.Point(5, 5)
			);

			var userLocationMarker = new google.maps.Marker({
				icon: user_icon
			});

			userLocationMarker.setPosition(initialLocation);
			userLocationMarker.setMap(map);

			var circle = new google.maps.Circle({
				fillColor: '#000000',
				fillOpacity: 0.05,
				strokeColor: '#000000',
				strokeOpacity: 0.3,
				strokeWeight: 1
			});

			circle.bindTo('center', userLocationMarker, 'position');
			circle.setRadius(position.coords.accuracy);
			circle.setMap(map);
		});
	}

	function attach_message(marker, i) {

		google.maps.event.addListener(marker, "click", function(e) {
			var infoBox = new InfoBox({
				latlng: marker.getPosition(),
				map: map
			});
		});

		google.maps.event.trigger(marker, "click");
	}

	initialize();
*/
});







//Doc. Ready
$(document).ready(function() {



	//Collection
	$('.page-template-colecao-php').each(function () {
		//List mount
		var qtd = $(this).find('article').length,
			pag = Math.ceil(qtd/18),
			ind = 0,
			ani = false,
			typ = 'mosaic';

		//create grid
		$('#main .container').append('<div id="mosaic"></div>');
		$('#main').append('<div id="train"><div></div></div>');

		$('#content article .thumb').appendTo('#train div');

		for ( i = 0; i < 18; i++ ) {
			$('#mosaic').append('<div class="box b' + i + '"><span></span></div>');

			$('#train .thumb:nth-child(18n + ' + (i + 1) + ')').clone().appendTo('#mosaic .b' + i + ' span');
		}



		//Fade Cascade
		$('#mosaic').each(function () {
			var i = 0;

			timer = setInterval(function() {
				if(i < qtd) {
					$('#mosaic .box:eq(' + i + ')').fadeTo(500, 1);

					i += 1;
				} else {
					clearInterval(timer);
				}
			}, 250);
		});



		//Improve with key
		$(document).keydown(function(e){
			if (e.keyCode == 39) {
				$('.control.next').trigger('click');
			} if (e.keyCode == 37) {
				$('.control.prev').trigger('click');
			}
		});

		if (qtd < 18) {
			$('.control').remove();
		} else {
			setTimeout(function () {
				$('.control').delay(500).fadeTo(500, 1).delay(2000).fadeTo(500, .25);
			}, 4500)
		}

		$('.control').bind('mouseenter', function () {
			$(this).stop(true).fadeTo(500, 1);
		}).bind('mouseleave', function () {
			$(this).stop(true).fadeTo(500, 0);
		}).bind('click', function () { //move
			var size = 250;

			$(this).stop(true).fadeTo(500, 1).delay(1000).fadeTo(500, 0);

			if ( $(this).is('.next') ) {

				if ( typ == 'mosaic' ) {
					//Flip cascade
					if ( ind < (pag - 1) && !ani ) {

						var l = 0;

						ani = true;

						if ( ind == -1 ) {
							ind = 0;
							ani = false;
						} else {
							ind += 1;

							lefts = setInterval(function() {
								if(l < 18) {
									$('#mosaic .box:eq(' + l + ') span').stop().animate({
										left: ind * -160
									}, 750, 'easeOutExpo');

								l += 1;

								} else {
									clearInterval(lefts);
									ani = false;
								}
							}, 75);
						}
					}
				} else {
					h = location.hash;
					hh = $('#train a[href="' + h + '"]').next().attr('href');
					window.location.hash = hh;
				}

			} else { // .prev

				if ( typ == 'mosaic' ) {
					//Flip cascade
					if ( ind >= 0 && !ani ) {

						var r = 18;

						ani = true;
						ind -= 1;

						if ( ind == -1 ) {
							ind = 0;
							ani = false;
						} else {
							rights = setInterval(function() {
								if(r >= 0) {
									$('#mosaic .box:eq(' + r + ') span').stop().animate({
										left: ind * -160
									}, 750, 'easeOutExpo');

								r -= 1;

								} else {
									clearInterval(rights);
									ani = false;
								}
							}, 75);
						}
					}
				} else {
					h = location.hash;
					hh = $('#train a:last-child').attr('href');
					window.location.hash = hh;
				}
			}
		});



		//Infinite carousel
		$("#train div").carouFredSel({
			width: "variable",
			height: 75,
			scroll: {
				mousewheel: true
			},
			items: {
				visible: "variable",
				height: 75,
				width: 100
			},
			scroll: "easeOutExpo",
			auto: false
		});

		$('#train a').bind('mouseenter', function () {
			$(this).stop(true).fadeTo(500, 1);
		}).bind('mouseleave', function () {
			$(this).stop(true).fadeTo(500, 0.5);
		});

		//Hash change
		$(window).bind('hashchange load', function () {
			var hash = location.hash;
				hash = hash.replace('#','');
console.log(hash)
			if ( hash == '' ) {
				typ = 'mosaic';
				$('#mosaic').fadeIn(500);
				$('#content article').hide();
			} else {
				$('#mosaic').fadeOut(500);
				$('#train').fadeIn(500);

				typ = 'train';
				t = $('#content h2:contains(' + hash + ')').parents('article').attr('id');

				x = $('#train a[href="#' + hash + '"]');
				$('#train div').trigger('slideTo', x, 0, true);

				$('#content article').hide();

				$('#' + t).fadeIn(500, function () {
					$('#' + t + ' .pics a:eq(0)').trigger('click');
				});
			}
		});

		//Fancybox
		$('.zoom').fancybox({
			'hideOnContentClick':	true,
			'margin'			:	20,
			'overlayColor'		:	'#FFF',
			'overlayOpacity'	:	1,
			'overlayShow'		:	true,
			'padding'			:	10,
			'transitionIn'		:	'elastic',
			'transitionOut'		:	'elastic',
			'titleShow'			:	false,
			'onComplete'		:	function () {
				$('#fancybox-close').appendTo('#fancybox-overlay');
			}
		});



		//Mouse track
		$('#content .holder a').live('mousemove', function(e) {
			mx = e.pageX;
			my = e.pageY;
			$('.glass').css({left: ( mx + 10 ) + 'px', top: ( my + 10 ) + 'px'});
		}).live('mouseenter', function(e) {
			$('.glass').show();
		}).live('mouseleave', function(e) {
			$('.glass').hide();
		});



		//Trigger
		$('.pics a').live('click', function () {
			i = '#' + $(this).parents('article').attr('id');
			p = $(this).prop('href'),
			l = $('<img src="' + p + '" />');

			$(i + ' .pics a').stop(true).fadeTo(500, 1);
			$(this).stop(true).fadeTo(500, 0.5);

			//load img
			$(l).load(function (e) {

				//Change src image
				$(l).fadeTo(0, 0);
				$(i + ' .holder a').append(l);

				$(i + ' .holder a').attr({href: p.replace('-325x325','') });

				$(l).fadeTo(500, 1, function () {

					$(i + ' .holder img:lt(' + ( $(i + ' .holder img').length - 1 ) + ')').remove();
				});
			});

			return false;
		});
	});






	//Press
	$('#menu-item-1352, #menu-item-1402').click(function () {
		var ul = $(this).find('ul').attr({id: 'option'});

		$('#main').before(ul);

		$('#option').wrap('<div id="over"></div>');

		return false;
	});

	$('body.category-press').each(function () {

		//Fade Cascade
		$('#content').each(function () {
			var q = 4, //$('#content img').length,
				i = 0;

			timer = setInterval(function() {
				if(i < q) {
					$('#content article:eq(' + i + ')').fadeTo(750, 1);

					i += 1;
				} else {
					clearInterval(timer);
					$('#content article').css({opacity: 1});
				}
			}, 250);
		});



		//Fancybox
		$('.zoom').fancybox({
			'margin'		:	20,
			'overlayColor'	:	'#FFF',
			'overlayOpacity':	1,
			'overlayShow'	:	true,
			'padding'		:	10,
//			'transitionIn'	:	'fade',
			'titleShow'		:	false,
			'onComplete'	:	function () {
				$('#fancybox-close').appendTo('#fancybox-overlay');
			}
		});

		//Improve with key
		$(document).keydown(function(e){
			if (e.keyCode == 39) {
				$('.control.next').trigger('click');
			} if (e.keyCode == 37) {
				$('.control.prev').trigger('click');
			}
		});


		var qtd = $(this).find('article').length;

		if (qtd < 5) {
			$('.control').remove();
		} else {
			$('#content').width(qtd * $('#content article:eq(1)').outerWidth(true));

			$('.control').delay(500).fadeTo(500, 1).delay(2000).fadeTo(500, .25);
		}

		$('.control').bind('mouseenter', function () {
			$(this).stop(true).fadeTo(500, 1);
		}).bind('mouseleave', function () {
			$(this).stop(true).fadeTo(500, 0);
		}).bind('click', function () { //move
			var size = 250;

			$(this).stop(true).fadeTo(500, 1).delay(1000).fadeTo(500, 0);

			if ($(this).is('.next') ) {
				//catch last one
				$('#content article:last-child').prependTo('#content');
				$('#content').css({ left: parseInt($('#content').css('left'), 10) - 250 })


				$('#content').stop().animate({
					left: -20
				}, 450, 'easeOutExpo');
			} else {
				$('#content').animate({
					left: -270
				}, 450, 'easeOutExpo', function () {

					//catch first one
					$('#content article:first-child').appendTo('#content');
					$('#content').css({ left: -20 })
				});
			}
		});

	});






	//Home
	$('.page-template-video-php').each(function () {


//VIMEO
var start = false;
// Listen for the ready event for any vimeo video players on the page
var vimeoPlayers = document.querySelectorAll('iframe'),
	player;

for (var i = 0, length = vimeoPlayers.length; i < length; i++) {
	player = vimeoPlayers[i];
	$f(player).addEvent('ready', ready);
}

/**
* Utility function for adding an event. Handles the inconsistencies
* between the W3C method for adding events (addEventListener) and
* IE's (attachEvent).
*/
function addEvent(element, eventName, callback) {
	if (element.addEventListener) {
		element.addEventListener(eventName, callback, false);
	} else {
		element.attachEvent(eventName, callback, false);
	}
}

/**
* Called once a vimeo player is loaded and ready to receive
* commands. You can add events and make api calls only after this
* function has been called.
*/
function ready(player_id) {
	// Keep a reference to Froogaloop for this player
	var container = document.getElementById(player_id).parentNode.parentNode;
		froogaloop = $f(player_id);

	froogaloop.api('play');

	froogaloop.addEvent('loadProgress', function(data) {
		if (data.percent < 0.1) {
			console.log('loadProgress event : ' + data.percent + ' : ' + data.bytesLoaded + ' : ' + data.bytesTotal + ' : ' + data.duration);
			froogaloop.api('seekTo', 0);
			froogaloop.api('pause');
		} else if ( data.percent > 0.1 && start == false ) {
			$('#lens, #content img').fadeTo(500, 0);

			froogaloop.api('play');

			hide_site();
		}

//		console.log('loadProgress event : ' + data.percent + ' : ' + data.bytesLoaded + ' : ' + data.bytesTotal + ' : ' + data.duration);
	});

	froogaloop.addEvent('play', function(data) {
		console.log('play event');
	});

	froogaloop.addEvent('finish', function(data) {
		start = false;
		show_site();

		$('#content img, #button').fadeTo(500, 1);
		$('#lens').fadeTo(500, 0.6);
		$('#button').html('REPLAY');
	});
}



		$('#main').prepend('<div id="lens"><span>&nbsp;</span></div><div id="button"><img src="wp-content/themes/birman2012/assets/images/load.gif" /></div>');

		$('#button').live('click', function () {
			if ( $(this).text() == 'PAUSE' ) {
				froogaloop.api('pause');

				$('#button').html('PLAY');

				show_site();

			} else if ( $(this).text() == 'PLAY' ) {
				hide_site();

				froogaloop.api('play');

			} else if ( $(this).text() == 'REPLAY' ) {
				froogaloop.api('seekTo', 0);
				froogaloop.api('play');
			}
		});

		$('#lens span, #button').live('mouseenter', function () {

			if (start) {
				$('#button').stop().fadeTo(750, 1);

				if ( $('#button').text() != 'PLAY' ) {
					$('#lens').stop().fadeTo(500, 0.6);
				}
			}
		}).live('mouseleave', function () {

			if (start) {
				$('#button').stop().fadeTo(250, 0);
				$('#lens').stop().fadeTo(500, 0);
			}
		});

		$('#header, #footer').live('mouseenter', function () {

			if (start) {
				$(this).stop(true).fadeTo(500, 1);
			} else {
				$(this).stop(true).fadeTo(500, 1);
			}

		}).live('mouseleave', function () {

			if (start) {
				$(this).stop(true).fadeTo(500, 0);
			}
		});
	});






	//Institucional
	$('.page-template-institucional-php').each(function () {
		var s = 1;

		//Fade Cascade
		$('#slider').each(function () {
			var q = $('#slider img').length,
				i = 0;

			timer = setInterval(function() {
				if(i < q) {
					$('#slider img:eq(' + i + ')').fadeTo(750, 1);

					i += 1;
				} else {
					clearInterval(timer);
				}
			}, 250);
		});

		//Slider
		$('#content menu').delegate('li:not(.deactive)', 'click', function (e) {
			var t = $(e.currentTarget).prop('class').replace('arrow ',''),
				i = $('#slider img:eq(0)').width(),
				c = $('#content').offset().left,
				q = $('#slider img').length - 1
				x = 0;

			if ( ( c - Math.abs(i) ) < 0 ) {
				x = ( c - Math.abs(i) );
			}

			if( s > 0 && s <= q ) {
				if(t == 'previous') {
					s -= 1;
				}

				$('#slider').stop().animate({
					left: ( s * i * -1 ) + ( c - Math.abs(i) ) - x
				}, 500, 'easeOutExpo');


				if(s == 0) {
					$('#content .previous').addClass('deactive');
					s = 1;
				} else if (s == q) {
					$('#content .next').addClass('deactive');
					s = q - 1;
				} else {
					$('#content menu li').removeClass('deactive');
				}

				if(t == 'next') {
					s += 1;
				}
			}
		});

		institucional();
		$(window).bind('resize', institucional);

	});
});
