//======================================================================================
ppanes = { 
	
	pane_builder: function(){
	
		//Set all of the buttons for initial state
		checkButtons(true, "#feature_arrows .rev a", "#feature_arrows .fwd a", iFeaturesRight, iTotalFeatures, 4);
		
		function gotoSelectedPane(iPaneNumber){
			iPainDifference =  iCurrentFeature - iPaneNumber;

			if(iPainDifference < 0){
				stMod = '+';
			}else{
				stMod = '-';
			}
			
			iMoveLocation = iPainDifference*960;
			
			$("#feature_panes_wrapper").animate({"left": "+="+iMoveLocation+"px"}, "slow",function(){
				moveStopPlay(iPaneNumber);
			});
			iCurrentFeature = iPaneNumber;
			
		}
		
		// NAVEGA??O ENTRE AS SETAS
		//_________________________________________________________
		
		$("#feature_arrows .rev a").click(function(event){
			$(document).stopTime("features");
			controlClick('stop');
			iFeaturesRight = moveFrames("#features_list_wrapper", 165, 'left', iTotalFeatures, 4, iFeaturesRight);
			checkButtons(true, "#feature_arrows .rev a", "#feature_arrows .fwd a", iFeaturesRight, iTotalFeatures, 4);
			return false;
		});
		
		$("#feature_arrows .fwd a").click(function(event){
			$(document).stopTime("features");
			controlClick('stop');
			iFeaturesRight = moveFrames("#features_list_wrapper", 165, 'right', iTotalFeatures, 4, iFeaturesRight);
			checkButtons(true, "#feature_arrows .rev a", "#feature_arrows .fwd a", iFeaturesRight, iTotalFeatures, 4);
			return false;
		});

		
		// AO CLICAR NO THUMB, MOVE OS QUADROS PARA O SELECIONADO
		//_________________________________________________________
		
		$('#features_list li').click(
			function() {
			$(document).stopTime("features");
				
    			controlClick('stop');
    			$('.acao-ativa b').html('stopAll()');
				
				$(".feature_selected").each(function () {
					$(this).removeClass('feature_selected');
				});
				
				$(this).addClass('feature_selected').addClass('feature_selected_ok'); 
				
				stFeatureSelected = $(this).attr('id').substr(13);
		
				iFeatureSelected = parseFloat(stFeatureSelected);

				gotoSelectedPane(iFeatureSelected);
				
				return false;
			}
		);
		
	},
	pane_auto_play: function(){
	
			isLooping = 1;
			inc = 0;
			
			checkFeatures = function() {
				
				$("#features_list li").removeClass("feature_selected");
				$("#features_list li").eq(iCurrentFeature).addClass("feature_selected").addClass('feature_selected_ok');
				
				//4 at a time
				if (iCurrentFeature < iTotalFeatures) {
					if(iCurrentFeature > 0 && iCurrentFeature%4 == 0){
						iFeaturesRight = moveFrames("#features_list_wrapper", 165, 'right', iTotalFeatures, 4, iFeaturesRight);
					}
					if (iCurrentFeature == 0 && inc > 0) {
						iFeaturesRight = moveFrames("#features_list_wrapper", 165, 'zero', iTotalFeatures, iTotalFeatures, iFeaturesRight);
					}
				}

				checkButtons(true, "#feature_arrows .rev a", "#feature_arrows .fwd a", iFeaturesRight, iTotalFeatures, 4);

				inc++;
				
			}

			slideTo = function(pos) {
				currentFeature = pos;
				pos = (pos) * -960;
				pos = pos + "px";
				$('.acao-ativa b').html('stopAll()');
				$("#feature_panes_wrapper").animate({ 
					left: pos
				}, 500,function(){
				    moveStopPlay(iCurrentFeature);
				});
				checkFeatures();
			}
			
			$("#feature_panes li a, #feature_panes").click(function () {
				controlClick('stop');
			});
		
			
			nextFeature = function() {
				if (iCurrentFeature < iTotalFeatures-1 ) {
					iCurrentFeature =  ++iCurrentFeature;
					slideTo(iCurrentFeature);
				} else {
					iCurrentFeature = 0;
					slideTo(0);
				}
			}
			
			checkFeatures();

			$(document).everyTime(5000, "features", function(i) {
				nextFeature();
			});			
		
			$("#loop_controls").click(function () { controlClick() });

			controlClick = function (request) {
				if ((isLooping == 1) || (request == "stop")) {
					$(document).stopTime("features");
					$("#loop_controls").addClass('paused');
					isLooping = 0;
				} else {
					$("#loop_controls").removeClass('paused');
					$(document).everyTime(5000, "features", function(i) {
						nextFeature();
					});
					isLooping = 1;
				}
			};

	
	},
	init: function(){
		iTotalFeatures = $("#features_list li").length;
		iCurrentFeature = 0;
		iCurrentPane = 0;
		iFeaturesRight = 4;
		
		iTotalProducts = $("#prod_panes li").length;
		iProdFeaturesRight = 1;
		
		ppanes.pane_builder();
		ppanes.pane_auto_play();
	}
}



function moveFrames(stFrameID, iFrameWidth, stDirection, iTotalQuantity, iMoveAmount, iCurrentEdgeElement){
	
	if(stDirection == 'right'){
		iFeaturesLeft = iTotalQuantity-(iCurrentEdgeElement);
		
		if(iFeaturesLeft <= 0){
			return iCurrentEdgeElement;
		}
		
		if(iMoveAmount >= iFeaturesLeft){
			iMoveAmount = iFeaturesLeft;
		}
		
		iCurrentEdgeElement += iMoveAmount;
		if(iCurrentEdgeElement >= iTotalQuantity){
			iCurrentEdgeElement = iTotalQuantity;
		}
		
		iFullMove = iMoveAmount*iFrameWidth;
		$(stFrameID).animate({"left": "-="+iFullMove+"px"}, "slow");
		
	}else if (stDirection == 'left'){
		// Left
		if(iCurrentEdgeElement == iMoveAmount){
			return iCurrentEdgeElement;
			
		}else if((iCurrentEdgeElement-iMoveAmount) > iMoveAmount){
			iShiftAmount = iMoveAmount;
			
		}else{
			iShiftAmount = (iCurrentEdgeElement-iMoveAmount);
		}

		iFullMove = iShiftAmount*iFrameWidth;
		$(stFrameID).animate({"left": "+="+iFullMove+"px"}, "slow");

		iCurrentEdgeElement -= iShiftAmount;
	}
	else {
		iCurrentEdgeElement = 4;
		$(stFrameID).animate({"left": "0px"}, "slow");
	}
	
	return iCurrentEdgeElement;
	
}

function checkButtons(isHorizontal, stLeftArrowID, stRightArrowID, iRightFeature, iTotalFeatures, iQuantityVisible){
	
	if(isHorizontal){
		if(iRightFeature >= iTotalFeatures){
			$(stRightArrowID).removeClass('on').addClass('off');
		}else{
			$(stRightArrowID).removeClass('off').addClass('on');
		}
		
		if((iRightFeature-iQuantityVisible) > 0){
			$(stLeftArrowID).removeClass('off').addClass('on');
		}else{
			$(stLeftArrowID).removeClass('on').addClass('off');
		}
		
	}else{
		if(iRightFeature >= (iTotalFeatures-1)){
			$(stRightArrowID).removeClass('on').addClass('off');
		}else{
			$(stRightArrowID).removeClass('off').addClass('on');
		}
		
		if((iRightFeature-iQuantityVisible) > 0){
			$(stLeftArrowID).removeClass('off').addClass('on');
		}else{
			$(stLeftArrowID).removeClass('on').addClass('off');
		}
		
	}
}

//======================================================================================
// CONTROLES FLASH - HTML

function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window.document[movieName];
	} else {
		return document[movieName];
	}
}

function htmlPlayFlash(value) {
	thisMovie(value.movieId).playFlash(value);
	// window["feature_item_0_flash"].playFlash({movieId:"feature_item_0_flash", texto:"blabla 2 do html/js"});
}

function htmlStopFlash(value) {
	thisMovie(value.movieId).stopFlash(value);
	// window["feature_item_0_flash"].stopFlash({movieId:"feature_item_0_flash"});
}

function moveStopPlay(location){
	
	$(".feature_selected_ok.flash").each(function () {
		htmlStopFlash({movieId:$(this).attr('id')+'_flash'});
	});

    if ( $("#feature_item_"+location).hasClass('flash') ){
		$(document).oneTime(250, function(){
			htmlPlayFlash({movieId:'feature_item_'+location+'_flash', texto:'blabla 2 do html/js'});
		});
    } else {
		//htmlStopFlash({movieId:'feature_item_'+location+'_flash'});
	}
}


// primeira função a ser chamada pelo flash, parando o tempo da animação em html
function inicioFlash(){
	$(document).stopTime("features");
	controlClick('stop');
	//alert('inicioflash');
}

//terminou o flash, para a animação, pula para o próximo quadro, e inicia contagem do tempo
function fimFlash(){
	$(document).stopTime("features");
	controlClick('stop');
	$(document).everyTime(5000, "features", function(i) {
		nextFeature();
	});
	nextFeature();
}



$(document).ready(function() {

	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
		$(".noflash").each(function(){ $(this).show(); });
		$(".hasflash").each(function(){ $(this).hide(); });
	}

	$.ajax({

		 type: "GET",
		 url: "/_xml/intro-home.xml",
		 dataType: "xml",
		 success: function(xml) {

			$(xml).find("destaques").each(function(){

				i=$(this).attr("nohtml");
					 
				$(xml).find("destaque").each(function(){
					
					var tipo =  $(this).attr("tipo");
					var name =  $(this).find("name").text();
					var thumb =  $(this).find("thumb").text();
					
					if( tipo == "imagem" ){
						$("<li id='feature_item_"+i+"'></li>").html("<img src='" + thumb + "' />").appendTo("#features_list");
						var link = $(this).find("link").text();
						var imagem = $(this).find("imagem").text();
						var analytics = $(this).find("analytics").text();
						
						$("<li id='feature_item_"+i+"_pane'></li>").html("<div class='nome fontCitroenLight'>" + name + "</div><a href='"+ link +"' target='_blank' onclick='pageTracker._trackPageview("+ analytics +")'><img src='" + imagem + "' /></a>").appendTo("#feature_panes");

						// condições ( texto legal )
						$(this).find("condicoes").each(function(){
							var icone = $(this).find("icone").text();
							var top = $(this).find("top").text();
							var left = $(this).find("left").text();
							var url = $(this).find("url").text();
							$("<span class='condicoes'></span>").html("<a style='top: " + top + "px; left: " + left + "px' href='http://www.citroen.com.br/condicoes/"+ url +"' target='_blank'><img src='" + icone + "' /></a>").appendTo("#feature_item_"+i+"_pane");
						});
						
						// preco
						$(this).find("preco").each(function(){
							var icone = $(this).find("icone").text();
							var top = $(this).find("top").text();
							var left = $(this).find("left").text();
							$("<span class='preco'></span>").html("<a href='"+ link +"' target='_blank' onclick='pageTracker._trackPageview("+ analytics +")' style='top: " + top + "px; left: " + left + "px'><img src='" + icone + "' /></a>").appendTo("#feature_item_"+i+"_pane");
						});
						
					} else
					if ( tipo == "flash" ){ } 

					
					i++;
				 });
				 
			});
			 
			ppanes.init();

            
			
			// flash está dando o play sozinho na primeira intro.
			//moveStopPlay("0")

            
            Cufon.replace('.fontCitroenLight', { fontFamily: 'Citroen Light' });
            Cufon.replace('.fontCitroen', { fontFamily: 'Citroen' });

		}

	 });
	
});