/**
* Arquivo responsavel pela chamada de todas as funcionalidades do site Victoria
*
* @author: Mateus Moura chagas[dot]mateus[at]gmail[dot]com
* @date: 06/07/2011
*
* Copyright(c) Todos os direitos reservados a
*/

if (window.console == null) window.console = { log: function (p) { }, error: function (p) { } };

var oThis;

var Actions = function () {
    oThis = this;

    this.init();
}

Actions.fn = Actions.prototype;
Actions.fn.extend = jQuery.extend;
Actions.fn.extend(
{
    init: function ()
	{
		this.content = $( "#content" );
        this.header = $( "#header" );
		this.footer = $( "#footer" );

		/*$( "#map_canvas", oThis.content ).length
			&& reloadMap();*/

		$( "div.lastNews div.scroll, #gallery div.navigation div.scroll, div.newDecoration div.scroll", oThis.content ).jScrollPane(
		{
			autoReinitialise: true
		});

		$( "div.lastNews div.scroll ul li:last, div.newDecoration div.scroll ul li:last", oThis.content ).addClass( "last" );

		$( "div.acompanhe select.droplist" ).droplist(
		{
			customScroll: true,
			month: true,
			height: 200
		});

		$( "div.work select.droplist, div.solicitation select.droplist" ).droplist(
		{
			customScroll: true,
			height: 200
		});

		setTimeout( function()
		{
			$( "div.jspDrag" ).each( function()
			{
				var hJ = $( this ).height();

				$( this ).height( hJ - 7 );
			});

		}, 1000 );

		$( "#featured", oThis.content ).length
			&& oThis.featured( $( "#featured", oThis.content ) );

		$( "#ventures div.list, #realty div.list", oThis.content ).length
			&& oThis.featured( $( "#ventures div.list, #realty div.list", oThis.content ) );

		$( "#realty, #ventures, #constructions, #blog.category, #blog.single, #channel, #privacy, #terms", oThis.content ).length
			&& $( "body" ).addClass( "internal" );

		oThis.menu();
		oThis.openBox( $( "div.contacts", oThis.header ) );
		oThis.openBox( $( "#channel", oThis.content ) );

		$( "div.item", oThis.content ).length
			&& oThis.itemPage( $( "div.item", oThis.content ) );

		//$( "#progressbar", oThis.content ).length
		//	&& oThis.progressBar( 30 );

		$( "#progressbar[rel=advance]", oThis.content ).length
			&& oThis.progressBar( 90 );

		$( "#progressbar[rel=advance-2nd]", oThis.content ).length
			&& oThis.progressBar( 32 );

		$( "#progressbar[rel=victoria-medical-center]", oThis.content ).length
			&& oThis.progressBar( 100 );

		$( "#progressbar[rel=essencial-by-victoria]", oThis.content ).length
			&& oThis.progressBar( 46 );

		$( "#progressbar[rel=le-paysage]", oThis.content ).length
			&& oThis.progressBar( 13 );

		oThis.validate( $( "div.call form", oThis.header ) );
		oThis.validate( $( "div.work form", oThis.header ) );
		oThis.validate( $( "div.treatment form", oThis.header ) );
		oThis.validate( $( "div.container div.sendEmail form", oThis.content ) );
		oThis.validate( $( "div.sidebar div.registration form", oThis.content ) );
		oThis.validate( $( "div.sidebar div.solicitation form", oThis.content ) );
		oThis.validate( $( "#channel div.suggestion form", oThis.content ) );
		oThis.mask();

		$( "#realty #gallery", oThis.content ).length
			&& oThis.gallery( $( "#realty #gallery", oThis.content ) );

		if( $( "ul.slider", oThis.content ).length )
		{
			setTimeout( function()
			{
				$( "div.acompanhe div.droplist div.droplist-list li a", oThis.content ).click( function()
				{
					var i = $(this).attr('rel'),
						$hi = $( "div.acompanhe ul.active", oThis.content ).parents( "div.anythingSlider" ),
						$btSelect = $( this );
					
					if( $btSelect.is( ".noClick" ) )
						return false;
						
					$btSelect.addClass( "noClick" );
					
					$hi.fadeOut( "fast", function()
					{
						var $ul = $( "div.acompanhe ul[rel=" + i + "]" );
						$hi.removeClass( "active" ).addClass( "hide" );

						if( $ul.parents( "div.anythingSlider" ).length )
						{
							console.log( $ul.parents( "div.anythingSlider" ) )
							$ul.parents( "div.anythingSlider" ).fadeIn( function()
							{
								$btSelect.removeClass( "noClick" );
							});
						}
						else
						{
							setTimeout( function()
							{
								$ul.show( function()
								{
									$ul.addClass( "active" ).removeClass( "hide" );
									oThis.imageSlider( $ul );
									$btSelect.removeClass( "noClick" );
								});
							}, 200 );
						}
					});


				});
			}, 2000 );

			oThis.imageSlider( $( "ul.slider:first", oThis.content ) );
		}
	},

	mask: function()
	{
		$('input.numero').onlyNumber();
		$( "input.telefone" ).setMask("(99)9999-9999");
		$( "input.cpf" ).setMask("999.999.999-99");
	},

	validate: function( forms )
	{
		// only for demo purposes
		$.validator.setDefaults({
			submitHandler: function() {
				//forms.submit();
			}
		});

		/*$.metadata.setType("attr", "validate");*/

		
		$( ".bt_send, div.error, .bt_sendEmail", forms ).click( function()
		{
			//setTimeout
			$( this ).is( ".error" )
				? $( "div.error", forms ).fadeOut()
				: setTimeout( function()
				{
					$( "div.error", forms ).addClass( "hide" );
				}, 5000 );
		});
		
		$( "textarea", forms ).focus( function()
		{
			$( this ).val() == "Escreva sua mensagem"
				&& $( this ).val( "" );
		}).blur( function()
		{
			$( this ).val() == ""
				&& $( this ).val( "Escreva sua mensagem" );
		});
		
		$( ".solicitation textarea").focus( function()
		{
			$( this ).val() == "Use este campo casa haja necessidade de especificar sua solicitação."
				&& $( this ).val( "" );
		}).blur( function()
		{
			$( this ).val() == ""
				&& $( this ).val( "Use este campo casa haja necessidade de especificar sua solicitação." );
		});
	},

	openBox: function( div )
	{
		$( ".bt_openBox", div ).unbind().click( function()
		{
			var $bt = $( this ),
				box = $( "div." + $bt.attr( "rel" ), div );

			box.siblings( "div.box" ).fadeOut( function()
			{
				$( this ).removeClass( "active" );
			});

			box.is( ".active" )
				? box.fadeOut( function()
				{
					box.removeClass( "active" );
				})
				: box.fadeIn( function()
				{
					box.addClass( "active" );
				});
		});

		$( "body" ).click( function( i )
		{
			var t = $( i.target );

			if( t.is( ".bt_openBox, div.sidebar div.plan div.plantas img" ) )
				return false;

			if( t.parents( "div.box" ).length == 0 )
			{
				$( "div.sidebar div.plan div.plantas img" ).removeClass( "hover");
				!t.is( ".box" )
					&& $( "div.box" ).fadeOut( function()
					{
						$( this ).removeClass( "active" );
					});
			}
		});
	},

	// Slider das imagens
	imageSlider: function( div )
	{
		div.anythingSlider({
			width           : 620,
			theme           : 'minimalist-round',
			easing          : 'easeInOutBack',
			buildArrows     : true,
			resizeContents  : true,
			autoPlay        : false,
			stopAtEnd       : true,
			startPanel      : 1,
			autoPlayLocked  : true,  // If true, user changing slides will not stop the slideshow
			//resumeDelay     : 10000, // Resume slideshow after user interaction, only if autoplayLocked is true (in milliseconds).
			onInitialized   : function(slider){
				$( "span.back" ).hide();
			},
			onSlideComplete : function(slider){
				
				var totalOfSlides = div.data('AnythingSlider').pages; // returns page 
				var currentSlide = div.data('AnythingSlider').currentPage; // returns page #
				
				if (currentSlide == 1) {
					$( "span.back" ).hide();
				} else {
					$( "span.back" ).show();
				}
				
				if (currentSlide == totalOfSlides) {
					$( "span.forward" ).hide();
				} else {
					$( "span.forward" ).show();
				}
				
			}
		});
	},

	// Função para a barra de progresso
	progressBar: function( val )
	{
		$( "#progressbar" ).progressbar({
			value: val
		});

		$( "#progressbar .indice p" ).html(val);
		$( "#progressbar .indice" ).css({'left':val+'%'});

		var hoverPlan = $( "div.hoverPlan", oThis.content );

		//$( "div.indice", oThis.content ).css( "left", ( val ) + "%" );
		
		/*
		$( "div.sidebar div.plan div.plantas img, div.hoverPlan", oThis.content ).hover( function( i )
		{
			var $hv = $( this );

			i.currentTarget.className == "hoverPlan"
				? hoverPlan.show()
				: hoverPlan.show();

			if( $hv.is( "img" ) )
			{
				$( "img", hoverPlan ).attr({
					src: $hv.attr( "src" ).replace("small", "medium"),
					alt: $hv.attr( "alt" )
				});
				$( "a", hoverPlan ).attr( "href", $hv.attr( "src" ).replace("small", "large").replace(".png", ".jpg") );
				$( "p", hoverPlan ).text( $hv.attr( "alt" ) );
			}
		}, function( i )
		{
			hoverPlan.hide();
		});
		*/
		
		$( "div.sidebar div.plan div.plantas img, div.hoverPlan", oThis.content ).click( function( i )
		{
			$( "div.sidebar div.plan div.plantas img" ).removeClass( "hover");
			
			var $hv = $( this );
			
			$hv.addClass("hover");

			i.currentTarget.className == "hoverPlan"
				? hoverPlan.show()
				: hoverPlan.show();

			if( $hv.is( "img" ) )
			{
				$( "img", hoverPlan ).attr({
					src: $hv.attr( "src" ).replace("small", "medium"),
					alt: $hv.attr( "alt" )
				});
				$( "a", hoverPlan ).attr( "href", $hv.attr( "src" ).replace("small", "large").replace(".png", ".jpg") );
				$( "p", hoverPlan ).text( $hv.attr( "alt" ) );
			}
		});


		var scrollPane = $( ".scroll-pane" ),
			scrollContent = $( ".scroll-content" );

		scrollContent.width( 267 * $( "img", scrollContent ).length );

		//build slider
		var scrollbar = $( ".scroll-bar" ).slider({
			min: 0,
			max: 267 * ( $( "img", scrollContent ).length - 1 ),
			step: 267,
			slide: function( event, ui ) {
				if ( scrollContent.width() > scrollPane.width() ) {

					scrollContent.css( "margin-left", "-" + Math.round(
						ui.value
					) + "px" );
				} else {
					scrollContent.css( "margin-left", 0 );
				}
			}
		});

		//append icon to handle
		var handleHelper = scrollbar.find( ".ui-slider-handle" )
		.mousedown(function() {
			scrollbar.width( handleHelper.width() );
		})
		.mouseup(function() {
			scrollbar.width( "100%" );
		})
		.append( "<span class='ui-icon ui-icon-grip-dotted-vertical'></span>" )
		.wrap( "<div class='ui-handle-helper-parent'></div>" ).parent();

		//change overflow to hidden now that slider handles the scrolling
		scrollPane.css( "overflow", "hidden" );

		//size scrollbar and handle proportionally to scroll distance
		function sizeScrollbar() {
			var remainder = scrollContent.width() - scrollPane.width();
			var proportion = remainder / scrollContent.width();
			var handleSize = scrollPane.width() - ( proportion * scrollPane.width() );
			scrollbar.find( ".ui-slider-handle" ).css({
				width: handleSize,
				"margin-left": -handleSize / 2
			});
			handleHelper.width( "" ).width( scrollbar.width() - handleSize );
		}

		//reset slider value based on scroll content position
		function resetValue() {
			var remainder = scrollPane.width() - scrollContent.width();
			var leftVal = scrollContent.css( "margin-left" ) === "auto" ? 0 :
				parseInt( scrollContent.css( "margin-left" ) );
			var percentage = Math.round( leftVal / remainder * 100 );
			scrollbar.slider( "value", percentage );
		}

		//if the slider is 100% and window gets larger, reveal content
		function reflowContent() {
				var showing = scrollContent.width() + parseInt( scrollContent.css( "margin-left" ), 10 );
				var gap = scrollPane.width() - showing;
				if ( gap > 0 ) {
					scrollContent.css( "margin-left", parseInt( scrollContent.css( "margin-left" ), 10 ) + gap );
				}
		}

		//change handle position on window resize
		$( window ).resize(function() {
			resetValue();
			sizeScrollbar();
			reflowContent();
		});
		//init scrollbar size
		setTimeout( sizeScrollbar, 10 );//safari wants a timeou
	},

	// Funcionalidades da paginas internas
	itemPage: function( div )
	{
		var sidebar = $( "div.sidebar", div ),
			registration = $( "div.registration", sidebar );

		$( "#coverflow", div ).length
			&& div.css( "padding-top", 472 );

		if( registration.length || $( "div.sendEmail", div ).length )
		{
			$( "input", div ).focus( function()
			{
				$( "label", $( this ).parent() ).hide();
			}).blur( function()
			{
				var $input = $( this );

				$input.val() == ""
					&& $( "label", $input.parent() ).show();
			}).each( function()
			{
				var $input = $( this );

				$input.val() != ""
					&& $( "label", $input.parent() ).hide();
			});
		}
		
		oThis.openBox( div );
	},

	// Funcionalidades do menu
	menu: function()
	{
		var nav = $( "#menu", oThis.header );

		$( "li", nav ).hover( function()
		{
			var $bt = $( this ),
				subnav = $( "ul", $bt );

			if( !$bt.is( ".active" ) )
				subnav.length && subnav.show();

		}, function()
		{
			var $bt = $( this ),
				subnav = $( "ul", $bt );

			if( !$bt.is( ".active" ) )
				subnav.length && subnav.hide();
		});

		$( ".bt_noClick", nav ).unbind().click( function()
		{
			return false;
		});


		$( "#institutional", oThis.content ).length
			&& $( "a:contains('Institucional')", nav ).parent().addClass( "active" );

		if( $( "#ventures", oThis.content ).length || $( "#constructions", oThis.content ).length || $( "#realty", oThis.content ).length )
		{
			$( "a:contains('Empreendimentos')", nav ).css( "color", "#D74B40" );
		}

		/*$( "#realty", oThis.content ).length
			&& $( "a:contains('Imóveis para Aluguel')", nav ).parents("li").addClass( "active" );*/

		$( "#channel", oThis.content ).length
			&& $( "a:contains('Canal do Cliente')", nav ).parents("li").addClass( "active" );
	},

	// Galeria de imagens em alugueis
	gallery: function( div )
	{
		var view = $( "div.view", div );

		$( "div.navigation ul li a", div ).unbind().click( function()
		{
			var $bt = $( this );

			$( "img.view", view ).fadeOut( function()
			{
				$( this ).attr(
				{
					src: $( "img", $bt ).attr( "src" ).replace( "small", "big" )
				}).fadeIn();
			})

			return false;
		});
	},

	// Função para Destaque opacidade
	featured: function( div )
	{
		$( "ul.opacity > li", div ).hover( function()
		{
			$( this ).siblings( "li" ).dequeue();
			$( this ).siblings( "li" ).stop().fadeTo( "fast", "0.4" );

		}, function( i )
		{
			$( this ).siblings( "li" ).dequeue();
			$( this ).siblings( "li" ).stop().delay(150).fadeTo( "fast", "1.0" );
		});
	}
});

$( function()
{
	var actions = new Actions();
});
