$( window ).ready(
function() {

	$( '.menutitle' ).find( 'a' ).click( function() { $( this ).parent().parent().click(); });
	
	var $width = 0;
	$( '#menuc_0' ).find( 'li' ).each( function( i , el ) {
		$width += parseInt( $( this ).outerWidth( true ) );
	} );
	$( '#menuc_0' ).find( 'ul' ).width( $width + 430 );

	// METODO PARA SELECIONAR OS MENUS E SEUS FILHOS
	var $childInitPos 	   = getChildInitialPosition( $( ':regex( id , [#menu]* )' ) );
	var $childInitPosLeft  = $childInitPos[0];
	var $childInitPosRight = $childInitPos[1];
	
	// chamo a acao do menu
	setMenuActions( $( '#menuc_0' ) );
	
	$( '.imgList div' ).hover(
		function() {
			$( this ).find( 'a' ).fadeIn();
		} ,
		function() {
			$( this ).find( 'a' ).fadeOut();
		}
	);
	resizeHomeImg( $( '.full_image' ) );
	changePhrase( 0 );
	
});

$( window ).resize(
	function(){
		resizeHomeImg( $( '.full_image' ) );
	}
);

// funcao para trocar as frases
function changePhrase( $index )
{
	var $animationSpeed = 1500;
	if ( $index > $( '.phrase' ).length - 1 )
		$index = 0;
		
	if ( $index == 0 )
		$prev = $( '.phrase' ).length - 1;
	else
		$prev = $index-1;
	
	if ( $( '.containerPhrase' ).eq( $prev ).css( 'left' ) != '900px' )
		$( '.containerPhrase' ).eq( $prev ).animate( {left: '-900px'} , $animationSpeed , function() { $( this ).css( 'left' , '900px' ) } );
	$( '.containerPhrase' ).eq( $index ).animate( {left: '0px'} , $animationSpeed );
	
	setTimeout( 'changePhrase( ' + ($index+1) + ' )' , 15000 );
	
}

// funcao recursiva para setar as acoes dos filhos
function setMenuActions( $child )
{

	var $baseurl = $( 'base' ).attr( 'href' );
	$( '.menutitle' ).find( 'a' ).click( function() { return false; });
	
	if ( ! $( $child ).find( '.isMenu' )[0] || $( $child ).find( '.isMenu' ).find( 'li' ).length == 0 ) return false;
	
	var $containerWidth = parseInt( $( $child ).find( '.section_content' ).css( 'width' ).toString().replace( 'px' , '' ) );
	if ( $containerWidth + parseInt( $( $child ).find( '.section_content' ).css( 'left' ).toString().replace( 'px' , '' ) ) > 1290 )
		$( $child ).find( '.btnRight' ).css( 'visibility' , 'visible' ).find( '*' ).fadeIn( $animtionSpeed , function() { $( this ).parent().removeClass( 'hidden' ) } );

	getChildInitialPosition( $( $child ) );
	var $animtionSpeed = 500;
	$( $child ).find( 'h2.menutitle , h2.menutitle a' ).click(
	function() {

		// se o click for na ancora
		if ( $( this ).attr( 'class' ) != 'menutitle' ) {
			$( this ).parent().click();
			return false;
		}

		// configuracoes
		var $maxWidthItemClicked = '428px';
		var $minWidthItemClicked = '84px';
		var $leftOffset 		 = 86;

		// objetos a serem usados
		var $root 			   = $( this ).parent().parent().parent().parent();
		var $rootId 		   = $( $root ).attr( 'id' );
		var $thisEl            = $( this ).parent();
		var $thisElIndex  	   = $( this ).parent().index();
		var $thisElTarget  	   = $( this ).find( 'a' ).attr( 'href' );
		var $idLink 		   = $( this ).parent().attr( 'id' ); // id do link clicado
		var $idLinkNumber      = $( this ).parent().attr( 'id' ).replace( 'link_' , '' ); // numero de identificacao do link clicado
		var $thisParent		   = $( this ).parent().parent();
		var $idContainer 	   = $( this ).parent().parent().attr( 'id' ); // container / ul
		var $idContainerNumber = $( this ).parent().parent().attr( 'id' ).replace( 'menuc_' , '' ); // numero do container / ul
		var $idChild		   = 'menuc_'+$idLinkNumber;
		
		// setando o offset left
		$leftOffset += parseInt( $( $thisEl ).attr( 'posLeft' ) ) * - 1;
		
		// se ja tiver aberto, apenas centraliza junto com seus filhos
		if ( $( this ).parent().hasClass( 'open' ) ) {

			var $este = $( this ).parent().parent().parent().parent().attr( 'id' );
			$( '#'+$este+' .section_content , #'+$este+' ~ .content_box ul' ).each( function() {

				var $leftOffset = ( ( ( parseInt( $( this ).find( '.open' ).attr( 'posLeft' ) ) - 1 ) - 86 ) * -1 ) - 1;
				// se nao tiver open, volta os filhos pra posicao inicial
				if ( ! $( this ).find( '.open' )[0] ) $leftOffset = 87;
				
				var $thisObj = $( this );

				// acertando os filhos
				$( this ).stop( true , true ).animate( { left : $leftOffset } , $animtionSpeed , function() {
					
					// verificando se a seta esquerda deve ser mostrada
					if ( parseInt( $( $thisObj ).css( 'left' ).toString().replace( 'px' , '' ) ) >= -1 )
						$( $thisObj ).parent().parent().find( '.btnLeft' ).fadeOut( $animtionSpeed , function() { $( this ).addClass( 'hidden' ).css( { 'display' : 'block' , 'visibility' : 'hidden' } ).find( '*' ).hide(); } );
					else
						$( $thisObj ).parent().parent().find( '.btnLeft' ).css( 'visibility' , 'visible' ).find( '*' ).fadeIn( $animtionSpeed , function() { $( this ).parent().removeClass( 'hidden' ) } );

					// verificando se a seta direita deve ser mostrada
					var $containerWidth = parseInt( $( $thisObj ).css( 'width' ).toString().replace( 'px' , '' ) );
					if ( $containerWidth + parseInt( $( $thisObj ).css( 'left' ).toString().replace( 'px' , '' ) ) > 950 )
						$( $thisObj ).parent().parent().find( '.btnRight' ).css( 'visibility' , 'visible' ).find( '*' ).fadeIn( $animtionSpeed , function() { $( this ).parent().removeClass( 'hidden' ) } );
					else
						$( $thisObj ).parent().parent().find( '.btnRight' ).fadeOut( $animtionSpeed , function() { $( this ).addClass( 'hidden' ).css( { 'display' : 'block' , 'visibility' : 'hidden' } ).find( '*' ).hide(); } );

				} );

			} );
			
			// retorna false ja que o item desejado ja esta aberto
			return false;
		}

		// remove as proximas divs
		$( '#'+$rootId+' ~ .content_box' ).remove();

		// mostrar edit e delete
		$( '.edit_delete' ).hide();
		$( $thisEl ).find( '.edit_delete' ).show().removeClass( 'none' );
		$( '.edit_delete a.edit' ).unbind( 'click' );
		$( '.edit_delete a.delete' ).unbind( 'click' );

		// se tiver algum elemento aberto
		if ( $( $thisParent ).find( '.open' ).find( '.pagedetail' )[0] ) {
			$( $thisParent ).find( '.open' ).find( 'h2.menutitle' ).stop( true , true ).show( $animtionSpeed ).css( { 'font-size' : '12px' , 'line-height' : '16px' } );
			$( $thisParent ).find( '.open' ).find( 'div.section_content' ).remove();
			$( $thisParent ).find( '.open' ).stop( true , true ).animate( { width : $minWidthItemClicked } , $animtionSpeed , function() {
				$( this ).removeClass( 'open' ).find( '.menutitle' ).css( 'font-weight' , '' );
			});

		} else if ( $( $thisParent ).find( '.open' )[0] ) {

			$( $thisParent ).find( '.open' ).find( 'h2.menutitle' ).stop( true , true ).animate( { fontSize : '12px' , lineHeight : '16px' } , $animtionSpeed );
			$( $thisParent ).find( '.open' ).find( 'div.container' ).fadeOut( $animtionSpeed , function() { $( this ).remove(); } );
			$( $thisParent ).find( '.open' ).stop( true , true ).animate( { width : $minWidthItemClicked } , $animtionSpeed , function() {
				$( this ).removeClass( 'open' ).find( '.menutitle' ).css( 'font-weight' , '' );
			});

		}

		// append da div de conteudo
		$( '#contanier' ).append( '<div class="content_box grid_22 container none alpha omega" id="'+$idChild+'"><div class="grid_1 opacity btnLeft alpha hidden" ><img src="'+$baseurl+'media/img/left_arrow.png" /></div><div class="grid_20 section" style="overflow:hidden"></div><div class="grid_1 opacity btnRight omega hidden" ><img src="'+$baseurl+'media/img/right_arrow.png" /></div></div>' );

		// adiciona o conteudo
		$.get( $thisElTarget , function( data ) {

			if ( ! $( $thisEl ).hasClass( 'type_m' ) ) {
				$( $thisEl ).find( 'h2' ).hide();
				$( $thisEl ).append( $( data ) );
				$( $thisEl ).addClass( 'open' );
			} else {

				if ( $( data ).find( 'li' ).length == 0 ) {
					$( '#contanier .content_box:last' ).remove();
					return false;
				}

				$( '#'+$idChild ).find( '.section' ).html( data ).parent().fadeIn( $animtionSpeed );

				// verifico o tipo do conteudo para fazer o devido tratamento
				if ( $( '#'+$idChild ).find( '.section_content' ).hasClass( 'isMenu' ) )
					isMenu( $( '#'+$idChild ) , $idLinkNumber );

				// anulo as acoes de clicar no menu
				$( '#'+$idChild ).find( 'a' ).click( function() { $( this ).parent().parent().click(); });

				// seto as acoes de cada filho
				setMenuActions( $( '#'+$idChild ) );
			
				if ( $( '#'+$idChild ).find( '.highlights' )[0] ){
					setTimeout( "$( '#"+$idChild+"' ).find( '.highlights' ).find( '.menutitle' ).click()" , 10 );
				}
			}
			
			//resizeHomeImg( $( '.full_image' ) );
			

		});
		
		// elemento atual
		$( $thisEl ).stop( true , false ).animate( { width : $maxWidthItemClicked } , $animtionSpeed , function() {

			$( $thisEl ).addClass( 'open' );
			$( 'li.open h2.menutitle' ).css( 'font-weight' , 'bold' );

			// verifica se o container esta mais para a esquerda
			if ( parseInt( $( $root ).find( '.section_content' ).css( 'left' ).toString().replace( 'px' , '' ) ) < 0 )
				$( $root ).find( '.btnLeft' ).css( 'visibility' , 'visible' ).find( '*' ).fadeIn( $animtionSpeed , function() { $( this ).parent().removeClass( 'hidden' ) } );
			else                             
				$( $root ).find( '.btnLeft' ).fadeOut( $animtionSpeed , function() { $( this ).addClass( 'hidden' ).css( { 'display' : 'block' , 'visibility' : 'hidden' } ).find( '*' ).hide(); } );

			// verifica se o container esta escondendo alguma li a direita
			var $containerWidth = parseInt( $( $root ).find( '.section_content' ).css( 'width' ).toString().replace( 'px' , '' ) );
			if ( $containerWidth + parseInt( $( $root ).find( '.section_content' ).css( 'left' ).toString().replace( 'px' , '' ) ) > 945 )
				$( $root ).find( '.btnRight' ).css( 'visibility' , 'visible' ).find( '*' ).fadeIn( $animtionSpeed , function() { $( this ).parent().removeClass( 'hidden' ) } );
			else
				$( $root ).find( '.btnRight' ).fadeOut( $animtionSpeed , function() { $( this ).addClass( 'hidden' ).css( { 'display' : 'block' , 'visibility' : 'hidden' } ).find( '*' ).hide(); } );

		} );
		$( '#'+$idChild ).fadeIn( $animtionSpeed );
		if ( $( $thisEl ).hasClass( 'type_m' ) )
			$( $thisEl ).find( 'h2.menutitle' ).stop( true , true ).animate( { fontSize : '36px' , lineHeight : '36px' } , $animtionSpeed );

		// movimentando o ul para a esquerda
		$( $thisParent ).stop( true , true ).animate( { left : $leftOffset } , $animtionSpeed );
		
	}
	);
	
	// seta esquerda
	$( $child ).find( '.btnLeft' ).unbind( 'click' ).click( function() {

		var $este 			= $( $child ).attr( 'id' );
		var $esteBtn 		= $( this );
		var $posLeft        = parseInt( $( '#'+$este+' .section_content:not(.pagedetail)' ).position().left );
		var $itensInLeft    = $posLeft/86;
		var $totItens       = $( '#'+$este+' .section_content:not(.pagedetail) li' ).length;
		var $containerLeft  = parseInt( $( $child ).find( '.section_content:not(.pagedetail)' ).css( 'left' ).toString().replace( 'px' , '' ) );
		var $containerWidth = parseInt( $( $child ).find( '.section_content:not(.pagedetail)' ).css( 'width' ).toString().replace( 'px' , '' ) );
		var $itensInRight   = ( ( $containerWidth+$containerLeft ) - 944 ) / 86;
		var $leftStart 		= ( $totItens-$itensInRight ) - 3;
		var $leftToGo  		= 0;
		
		// setando o total a correr do slide
		for ( $i=0 ; $i<3 ; $i++ ) {
			/* MODO ANTIGO
			if ( $( $child ).find( '.section_content li' ).eq( ( $leftStart+$i ) ).outerWidth( true ) != null )
			 	$leftToGo += $( $child ).find( '.section_content li' ).eq( ( $leftStart+$i ) ).outerWidth( true );
			else
			*/
			$leftToGo += 86;
		}
		
		$( '#'+$este+' .section_content:not(.pagedetail,.isText) , #'+$este+' ~ .content_box .section_content:not(.pagedetail,.isText)' ).stop( true , true ).animate( { left : '+='+$leftToGo } , $animtionSpeed , function() {
			
			$( this ).each( function() {
				if ( $( this ).hasClass( 'isMenu' ) && $( this ).find( 'li' ).length > 0 ) {

					if ( parseInt( $( this ).css( 'left' ).toString().replace( 'px' , '' ) ) >= -1 )
						$( this ).parent().parent().find( '.btnLeft' ).fadeOut( $animtionSpeed , function() { $( this ).addClass( 'hidden' ).css( { 'display' : 'block' , 'visibility' : 'hidden' } ).find( '*' ).hide(); } );

					$containerWidth = parseInt( $( this ).css( 'width' ).toString().replace( 'px' , '' ) );
					if ( $containerWidth + parseInt( $( this ).css( 'left' ).toString().replace( 'px' , '' ) ) > 950 )
						$( this ).parent().parent().find( '.btnRight' ).css( 'visibility' , 'visible' ).find( '*' ).fadeIn( $animtionSpeed , function() { $( this ).parent().removeClass( 'hidden' ) } );

				}
			});

			/*
			if ( parseInt( $( '#'+$este+' .section_content' ).css( 'left' ).toString().replace( 'px' , '' ) ) >= -1 )
				$( $esteBtn ).fadeOut( $animtionSpeed , function() { $( this ).addClass( 'hidden' ).css( { 'display' : 'block' , 'visibility' : 'hidden' } ).find( '*' ).hide(); } );

			if ( $containerWidth + parseInt( $( '#'+$este+' .section_content' ).css( 'left' ).toString().replace( 'px' , '' ) ) > 950 )
				$( $esteBtn ).parent().find( '.btnRight' ).css( 'visibility' , 'visible' ).find( '*' ).fadeIn( $animtionSpeed , function() { $( this ).parent().removeClass( 'hidden' ) } );
			*/

		} );
		
	});
	
	// seta direita
	$( $child ).find( '.btnRight' ).unbind( 'click' ).click( function() {

		var $este 			= $( $child ).attr( 'id' );
		var $esteBtn 		= $( this );
		var $posLeft        = parseInt( $( '#'+$este+' .section_content:not(.pagedetail)' ).position().left )-86;
		var $itensInLeft    = parseInt( $posLeft/86 );
		var $totItens       = $( '#'+$este+' .section_content:not(.pagedetail) li' ).length;
		var $containerLeft  = parseInt( $( '#'+$este+' .section_content:not(.pagedetail)' ).css( 'left' ).toString().replace( 'px' , '' ) );
		var $containerWidth = parseInt( $( '#'+$este+' .section_content:not(.pagedetail)' ).css( 'width' ).toString().replace( 'px' , '' ) );
		var $itensInRight   = parseInt( ( ( $containerWidth+$containerLeft ) - 945 ) / 86 );
		var $leftStart 		= parseInt( ( parseInt( $( '#'+$este+' .section_content:not(.pagedetail)' ).position().left ) - 1 ) / 86 ) * -1 ;
		var $leftToGo  		= 0;

		// se for menor que zero, subtraio um, pois os indices dos elementos sempre comecao em zero
		$leftStart = ( $leftStart <= 0 ) ? $leftStart -1 : $leftStart + 1;

		// setando o total a correr do slide
		for ( $i=0 ; $i<3 ; $i++ ) {
			/* MODO ANTIGO
			if ( $( '#'+$este+' .section_content li' ).eq( ( $leftStart+$i ) ).outerWidth( true ) != null )
				$leftToGo += $( '#'+$este+' .section_content li' ).eq( ( $leftStart+$i ) ).outerWidth( true );
			else
			*/
				$leftToGo += 86;
		}

		$( '#'+$este+' .section_content:not(.pagedetail,.isText) , #'+$este+' ~ .content_box .section_content:not(.pagedetail,.isText)' ).stop( true , true ).animate( { left : '-='+$leftToGo } , $animtionSpeed , function() {
			
			$( this ).each( function() {
				if ( $( this ).hasClass( 'isMenu' ) && $( this ).find( 'li' ).length > 0 ) {
					
					$containerWidth = parseInt( $( this ).css( 'width' ).toString().replace( 'px' , '' ) );

					if ( $containerWidth+parseInt( $( this ).css( 'left' ).toString().replace( 'px' , '' ) ) <= 950 )
						$( this ).parent().parent().find( '.btnRight' ).fadeOut( $animtionSpeed , function() { $( this ).addClass( 'hidden' ).css( { 'display' : 'block' , 'visibility' : 'hidden' } ).find( '*' ).hide(); } );

					if ( parseInt( $( this ).css( 'left' ).toString().replace( 'px' , '' ) ) < -1 )
						$( this ).parent().parent().find( '.btnLeft' ).css( 'visibility' , 'visible' ).find( '*' ).fadeIn( $animtionSpeed , function() { $( this ).parent().removeClass( 'hidden' ) } );

				}
			});
			/*
			if ( $containerWidth+parseInt( $( '#'+$este+' .section_content' ).css( 'left' ).toString().replace( 'px' , '' ) ) <= 1286 )
				$( $esteBtn ).fadeOut( $animtionSpeed , function() { $( this ).addClass( 'hidden' ).css( { 'display' : 'block' , 'visibility' : 'hidden' } ).find( '*' ).hide(); } );

			if ( parseInt( $( '#'+$este+' .section_content' ).css( 'left' ).toString().replace( 'px' , '' ) ) < -1 )
				$( $esteBtn ).parent().find( '.btnLeft' ).css( 'visibility' , 'visible' ).find( '*' ).fadeIn( $animtionSpeed , function() { $( this ).parent().removeClass( 'hidden' ) } );
			*/

		} );
	});

}

// pega a posicao inicial dos filhos
function getChildInitialPosition( $parent )
{
	$( $parent ).find( 'li:regex( id , [#link]* )' ).each( function( i , el ) {
			$( el ).attr( 'posLeft' , ( $( el ).position().left+1 ) );
	} );
	return true;
}

// verifica se eh menu e seta os ids [talvez nao precise dessa funcao]
function isMenu( $obj , $idLinkNumber )
{
	var $width = 0;
	$( $obj ).find( 'li' ).each( function( i , el ) {
		$( this ).attr( 'id' , 'link_' + $idLinkNumber + '_' + i );
		$width += parseInt( $( this ).outerWidth( true ) );
	} );
	$( $obj ).find( '.section_content' ).width( $width + 430 );
}

// verifica se eh um formulario e aplica as determinadas configuracoes
function isForm()
{
	var $class = $( 'input:radio[name=type]:checked' ).attr( 'id' );
	var $baseurl = $( 'base' ).attr( 'href' );
	$( '.'+$class ).find( 'input , textarea , select' ).attr( 'disabled' , false );
	if ( $( '.'+$class ).hasClass( 'textImagePage' ) || $( '.'+$class ).hasClass( 'imagePage' ) ) {
		$.getScript( $baseurl + 'media/js/upload.js' , function() {
			$( '.'+$class ).find( 'input[name=upload_image]' ).doUpload( {
				inputFile	    : $( '.'+$class ).find( 'input[name=upload_image]' ) ,
				inputFileName   : 'image',
				baseurl         : $baseurl ,
				uploadScript    : $baseurl + 'index.php/publisher/images/upload' ,
				getReturn       : uploadComplete ,
				containerWidth  : $( '.'+$class ).find( 'input[name=upload_image]' ).parent().width() ,
				containerHeight : '22px'
			} );
		} );
		
		
		function uploadComplete( $image ) {

			if ( $image == null ) return false;
			
			var $imgSrc = $image;
			var $aux = $image.split( '/' );
			var $imgName = $aux[$aux.length-1];
			
			var $objContainer = $( '.'+$class ).find( '.resImage' );

			$objContainer.html( '<img src="'+$imgSrc+'" />' );
			if ( $objContainer.find( 'input[name=image]' )[0] )
				$objContainer.find( 'input[name=image]' ).val( $imgName );
			else
				$objContainer.append( '<input type="hidden" name="image" value="'+$imgName+'" />' );
            }
		
	}
}

// resizes the home img object
function resizeHomeImg( el )
{
	var win_w = $( window ).width();
	var win_h = $( window ).height();
	var field_w = win_w;
	var field_h = win_h;
	if( el ) {
		// resize container (parent li)
		el.parent().css( 'height' , field_h + 'px' ).css( 'width' , field_w + 'px' );
		// get image size
		var image_w = $( el ).width();
		var image_h = $( el ).height();
		var ratio;
		if (image_w/image_h >= field_w/field_h)
			ratio = field_h/image_h;
		else
			ratio = field_w/image_w;
		var final_w = image_w*ratio;
		var final_h = image_h*ratio;
		$( el ).css('width', final_w + 'px');
		$( el ).css('height', final_h + 'px');
		if ( final_w > field_w)
			$( el ).css('margin-left', '-'+((final_w-field_w)/2)+'px');
		else
			$( el ).css('margin-left', '0px');
		if ( final_h > field_h)
			$( el ).css('margin-top', '-'+((final_h-field_h)/2)+'px');
		else
			$( el ).css('margin-top', '0px');
	}
}


