$( window ).bind( 'load', function(){
	var portifa = new Portifolio();								
});

window.semaforoIndex = 3;
window.interval;
window.cache = [];

Portifolio = function()
{
	this.URL = '../xml/portifolio.xml';
	this.MODAL_URL = '../xml/portifolioInfo.xml';	
	this.MAX_ITENS = 14;
	this._dataSet = new Array;
	this._anos = new Array;
	this.modalData = new Function;
	this.load();
}

Portifolio.data = function( id, ano, titulo, thumb, info )
{
	this.id = id;
	this.ano = ano;
	this.titulo = titulo;
	this.thumb = thumb;
	this.info = info;
}

Portifolio.prototype.load = function()
{
	var ref = this;
	var ajaxOptions = {
		type: 'GET',
		dataType: 'XML',
		url: this.URL,
		success: function( data, status)
		{
			ref.storeData( data );
		}/*,
		complete: function( XHR, status )
		{
			ref.storeData( XHR );
		}*/
	}
	
	$.ajax( ajaxOptions );
}

Portifolio.prototype.storeData = function( XHR ){
	var _objXML = XHR.responseXML;
	var _dataSet = this.getData();
	var ref = this;	
	
	$( 'portifolio', XHR ).children( 'item' ).each( function( i ){
		var $this = $( this );
		
		_dataSet.push( new Portifolio.data( $this.children( 'id' ).text(), $this.children( 'ano' ).text(), $this.children( 'titulo' ).text(), $this.children( 'thumb' ).text(), $this.children( 'info' ).text() ) );
	});
	
	this.setData( _dataSet );
	this.sort();
}

Portifolio.prototype.sort = function()
{
	var _atual;
	var _arrAnos = new Array;
	var _dataSet = this.getData();
	
	for ( k = 0; k < _dataSet.length; k++ )
	{
		if ( _dataSet[k].ano != _atual ) 
		{
			_atual = _dataSet[k].ano;
			
			if ( $.inArray( _atual, _arrAnos ) == -1 )
			{
				_arrAnos.push( _atual );
			}
		}
	}

	this.setAnos( _arrAnos );
	this.show();
}

Portifolio.prototype.show = function()
{
	this.drawModal();
	this.showAnos();
}

Portifolio.prototype.showAnos = function()
{
	var ref = this;
	var _container = $( 'ul.carrosel' );
	var btAnterior = $( 'ul#alterarAno li' ).filter(':eq(0)').children('a');
	var btPosterior = $( 'ul#alterarAno li' ).filter(':eq(2)').children('a');
	var _arrAnos = this.getAnos();
	
	for ( k = 0; k < _arrAnos.length; k++ ) 
	{
		if ( k == 0 )
		{
			_container.prepend( '<li class="strAno itemVisivel">' + _arrAnos[k] + '</li>' );
		} else {
			_container.prepend( '<li class="strAno">' + _arrAnos[k] + '</li>' );
		}
	}

	_container.children().not('.strAno').remove();

	_container.parent().jCarouselLite({
		btnNext: "a#anoPosterior",
		btnPrev: "a#anoAnterior",
		beforeStart: function( itemVisivel )
		{
			itemVisivel.removeClass( 'itemVisivel' );
		},
		afterEnd: function( itemVisivel )
		{
			itemVisivel.addClass( 'itemVisivel' );
			ref.paginacaoAnos();
		},
		circular: false,
		visible: 1,
		start: _container.children().length - 1
	});

	this.paginacaoAnos();
}

Portifolio.prototype.paginacaoAnos = function()
{
	var ref = this;
	var _anoAtivo = $( '.itemVisivel' ).html();
	var _dataSet = this.getData();
	var _arrAuxiliar = new Array;
	var _containerHTML = $( 'ul#itens' );
	var _numItens;
	var _paginacaoHTML = $( 'ul#paginacao' );
	
	for ( k = 0; k < _dataSet.length; k++ )
	{
		if ( _dataSet[k].ano == _anoAtivo )
		{
			_arrAuxiliar.push( _dataSet[k] );
		}
	}
	
	_containerHTML.children().remove();
	_containerHTML.hide();

	for ( k = 0; k < _arrAuxiliar.length; k++ )
	{
		_strHTML = '<a href="' + _arrAuxiliar[k].info + '" class="replacement portifolioItem" title="' + _arrAuxiliar[k].titulo + '" id="item_' + _arrAuxiliar[k].id + '"><img src="' + _arrAuxiliar[k].thumb + '" width="33" height="41" alt="' + _arrAuxiliar[k].titulo + '" /></a>';
		
		if ( this.MAX_ITENS > k )
		{
			_containerHTML.append( '<li class="show">' + _strHTML + '</li>' );	
		} else {
			_containerHTML.append( '<li class="">' + _strHTML + '</li>' );	
		}
	}
	
	this.showModal();

	_containerHTML.fadeIn();
	
	_numItens = _containerHTML.children( 'li' ).length / 14;
	
	_paginacaoHTML.children().remove();

	if ( _numItens > 1)
	{
		for ( k = 0; k <= _numItens; k++ )
		{
			if ( ( k + 1 ) == 1 )
			{
				_paginacaoHTML.append( '<li><a href="#" class="paginacaoAno ativo">' + ( k + 1 ) + '</a></li>' );
			} else {
				_paginacaoHTML.append( '<li>&nbsp;.&nbsp;<a href="#" class="paginacaoAno">' + ( k + 1 ) + '</a></li>' );
			}
		}
		
		$( 'a.paginacaoAno' ).click( function()
		{
			$this = $( this );
			
			if ( !$this.hasClass( 'ativo' ) )
			{
				$this.parent().parent().find( 'a.ativo' ).removeClass( 'ativo' );
				$this.addClass( 'ativo' );
				
				minimo = ref.MAX_ITENS * ( parseInt( $this.html() ) - 1 );
				maximo = ref.MAX_ITENS * parseInt( $this.html() );

				minimo == -1 ? minimo = 0 : minimo = minimo;

				_containerHTML.children().removeClass('show');
				_containerHTML.children().slice(minimo, maximo).addClass('show');
			}
			
			return false;
		});
	}
}

Portifolio.prototype.drawModal = function()
{
	var _strModal = '<div class="modal"></div>';
	
	$( _strModal ).appendTo( document.body );
}

Portifolio.prototype.showModal = function()
{
	var _btPortifaItem = $( 'a.portifolioItem' );
	var ref = this;
	
	_btPortifaItem.click( function(){
		ref.loadModal( $( this ).attr( 'href' ) );
		
		return false;	
	} );	
}

Portifolio.modalData = function( ano, titulo, cliente, diretor, redator, producao, midia, atendimento, planejamento, imagens )
{
	this.ano = ano;
	this.titulo = titulo;
	this.cliente = cliente;
	this.diretor = diretor;
	this.redator = redator;
	this.producao = producao;
	this.midia = midia;	
	this.atendimento = atendimento;
	this.planejamento = planejamento;		
	this.imagens = imagens;
}

Portifolio.prototype.loadModal = function( url )
{
	var _modal = $( 'div.modal' );
	var ref = this;
	var _ajaxOptions = {
		type: 'GET',
		dataType: 'XML',
		url: url,
		success: function( XHR )
		{
			var _data = ref.storeModal( XHR );
			ref.drawModalContent( _data );
		}
	}
	
	$.ajax( _ajaxOptions );
}

Portifolio.prototype.storeModal = function( XHR )
{
	//var _objXML = $( 'item', XHR );
	var ref = this;	
	var _arrImagens = new Array;
	var _arrData = new Array;
	var _dataSet;
	
	//alert( $( 'ano', XHR ).text() );
	
	_arrData = [ $( 'ano', XHR ).text(), $( 'titulo', XHR ).text(), $( 'cliente', XHR ).text(), $( 'diretor', XHR ).text(), $( 'redator', XHR ).text(), $( 'producao', XHR ).text(), $( 'midia', XHR ).text(), $( 'atendimento', XHR ).text(), $( 'planejamento', XHR ).text() ];
	
	$( 'imagens', XHR ).children( 'imagem' ).each( function( i ){
		var $this = $( this );
		
		_arrImagens.push( $this.text() );
	});		
	
	_arrData.push( _arrImagens );
	
	_dataSet = new Portifolio.modalData( _arrData[0], _arrData[1], _arrData[2], _arrData[3], _arrData[4], _arrData[5], _arrData[6], _arrData[7], _arrData[8], _arrData[9] );

	for ( k = 0; k < _dataSet.imagens.length; k++ )
	{
		cache[k] = new Image();
		cache[k].src = _dataSet.imagens[k];
		cache[k].onload = function(){
			if ( k == _dataSet.imagens.length ) {
				loaded = true;
			}
		};
	}

	return _dataSet;
}	

window.loaded = false;
Portifolio.prototype.drawModalContent = function( _data )
{
	var ref = this;
	var _modal = $( 'div.modal' );
	
	_modal.load( '../includes/portifolioModal.html', function(){
		var $this = $( this );
		var _imagensHTML = "";
		
		interval = setInterval( function() {
			//alert( cache );
			if ( cache[0].width > 0 ) {
				clearInterval( interval );
				
				for ( i = 0; i < _data.imagens.length; i++ )
				{
					_imagensHTML += '<li><img src="' + _data.imagens[i] + '" width="' + cache[i].width + '" height="' + cache[i].height + '" alt="' + _data.titulo + '" tabindex="' + ( i + 1 ) + '" /></li>';		
				}
			
				$this.find( '#modalContadorTotal' ).html( _data.imagens.length < 10 ? "0" + _data.imagens.length : _data.imagens.length );
				$this.find( '#modalImagens ul' ).html( _imagensHTML );
				$this.find( '#modalAno' ).html( _data.ano );
				$this.find( '#modalTitulo' ).html( _data.titulo );
				_data.cliente.length == 0 ? $this.find( '#modalInfoCliente' ).parent().remove() : $this.find( '#modalInfoCliente' ).html( _data.cliente );
				_data.diretor.length == 0 ? $this.find( '#modalInfoDirecao' ).parent().remove() : $this.find( '#modalInfoDirecao' ).html( _data.diretor );
				_data.redator.length == 0 ? $this.find( '#modalInfoRedacao' ).parent().remove() : $this.find( '#modalInfoRedacao' ).html( _data.redator );
				_data.producao.length == 0 ? $this.find( '#modalInfoProducao' ).parent().remove() : $this.find( '#modalInfoProducao' ).html( _data.producao );
				_data.midia.length == 0 ? $this.find( '#modalInfoMidia' ).parent().remove() : $this.find( '#modalInfoMidia' ).html( _data.midia );			
				_data.atendimento.length == 0 ? $this.find( '#modalInfoAtendimento' ).parent().remove() : $this.find( '#modalInfoAtendimento' ).html( _data.atendimento );
				_data.planejamento.length == 0 ? $this.find( '#modalInfoPlanejamento' ).parent().remove() : $this.find( '#modalInfoPlanejamento' ).html( _data.planejamento );						
				
				setTimeout(function(){
					$this.find( '.btVoltar' ).hide();
					
					$this.find( '.btVoltar, .btAvancar' ).height( $this.find( '#modalImagens ul li:first img' ).height() ); 
					$this.find( '#modalInfo' ).width( $this.find( '#modalImagens ul li:first img' ).width() ); 	
					$( 'div.modal' ).width( $this.find( '#modalImagens ul li:first img' ).width() + 20 );
					$( 'div.modal' ).height( $this.find( '#modalImagens ul li:first img' ).height() + 40 );		
					
					if ( _data.imagens.length == 1 ){
						 $this.find( '.btAvancar' ).hide()
					}
					
					$this.find( '#modalImagens' ).jCarouselLite({
						btnNext: "a.btAvancar",
						btnPrev: "a.btVoltar",
						afterEnd: function( itemVisivel ){ 
							parseInt(itemVisivel.children().attr( 'tabindex' )) == 1 ? $this.find( '.btVoltar' ).hide() : $this.find( '.btVoltar' ).show();
							parseInt(itemVisivel.children().attr( 'tabindex' )) == _data.imagens.length  ? $this.find( '.btAvancar' ).hide() : $this.find( '.btAvancar' ).show();
							
							$( 'div.modal' ).width( itemVisivel.children( 'img' ).width() + 20 );
							$( 'div.modal' ).height( itemVisivel.children( 'img' ).height() + 40 );					
							$this.find( '.btVoltar, .btAvancar' ).height( itemVisivel.height() ); 
							$this.find( '#modalInfo' ).width( itemVisivel.width() ); 
							$this.find( '#modalContadorAtual' ).html( parseInt(itemVisivel.children( 'img' ).attr('tabindex')) < 10 ? "0" + parseInt(itemVisivel.children( 'img' ).attr('tabindex')) : parseInt(itemVisivel.children( 'img' ).attr('tabindex')) );
						},
						circular: false,
						visible: 1,
						speed: 1
					});
					
					$this.find( '.btVoltar' ).hover(function(){
						$( this ).css( 'background-position', 'center left' );
					}, function(){
						$( this ).css( 'background-position', '-1000px 0' );			
					});
					
					$this.find( '.btAvancar' ).hover(function(){
						$( this ).css( 'background-position', 'center right' );
					}, function(){
						$( this ).css( 'background-position', '-1000px 0' );			
					});
					
					$this.find( '#modalImagens ul li img' ).css( 'visibility', 'visible' );
					ref.centralizarModal();
				}, 100);
				
				$this.find( 'a.btFecharModal ' ).click(function(){
					_modal.modalToggle();
					
					return false;
				});
				
				var creditoPos;
				
				$.browser.msie ? creditoPos = 30 : creditoPos = 28;
				
				$( '.btCreditos' ).click(function(){
					$( this ).toggleClass( 'btCreditosFechar' );
					if ( parseInt($this.find( '#creditos' ).css( 'bottom' )) != 0 ) {
						$this.find( '#creditos' ).animate({ 'bottom': '0px' });
					} else {					
						$this.find( '#creditos' ).animate({ 'bottom': (- $( '#creditos' ).height() + creditoPos) + 'px' });
					}
					
					return false;
				});
				
				$this.modalToggle();
				
				$( '#creditos' ).css( 'bottom' , (- $( '#creditos' ).height() + creditoPos) );
			}
	 	}, 200 );	
	});
}	

Portifolio.prototype.centralizarModal = function()
{
    $( 'div.modal' ).css({
       	'top': '50%',
        'left': '50%',
        'margin-top': ( - ($( 'div.modal' ).height() / 2) + "px"),
        'margin-left': ( - ($( 'div.modal' ).width() / 2) + "px")

    });	
}

/* GETS e SETS */
Portifolio.prototype.setAnos = function( anos )
{
	this._anos = anos;	
}

Portifolio.prototype.getAnos = function()
{
	return this._anos;	
}

Portifolio.prototype.setData = function( dataSet )
{
	this._dataSet = dataSet;	
}

Portifolio.prototype.getData = function( dataSet )
{
	return this._dataSet;	
}

Portifolio.prototype.debug = function()
{
	return this;	
}
